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
feat(webv2): state selection overhaul
joshistoastea5c016498e2
diff --git a/invokeai/frontend/webv2/.oxlintrc.json b/invokeai/frontend/webv2/.oxlintrc.jsonindex 66c2950a01..69f8d32079 100644--- a/invokeai/frontend/webv2/.oxlintrc.json+++ b/invokeai/frontend/webv2/.oxlintrc.json@@ -1,6 +1,6 @@{"$schema": "./node_modules/oxlint/configuration_schema.json",- "plugins": ["typescript", "react", "import", "unicorn", "oxc", "react-perf", "unicorn"],+ "plugins": ["typescript", "react", "import", "unicorn", "oxc", "react-perf", "eslint"],"categories": {"correctness": "error"},@@ -28,10 +28,12 @@"no-throw-literal": "error","no-unmodified-loop-condition": "error","no-var": "error",- "prefer-template": "error",+ "prefer-template": "error","radix": "error",+ // "eslint/complexity": "error",+"react/jsx-curly-brace-presence": ["error",{diff --git a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx b/invokeai/frontend/webv2/src/workbench/ThemeController.tsxindex 55c307cc56..64124ffe83 100644--- a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx+++ b/invokeai/frontend/webv2/src/workbench/ThemeController.tsx@@ -1,7 +1,8 @@import { DEFAULT_THEME, THEMES_BY_ID } from '@theme/system';import { useLayoutEffect } from 'react';-import { useWorkbenchSettings } from './settings/store';+import { useWorkbenchSettingsSelector } from './settings/store';+import { shallowEqual } from './WorkbenchContext';/*** Applies the persisted appearance preferences to the document root.@@ -21,8 +22,14 @@ const THEME_HINT_STORAGE_KEY = 'invokeai:v7:webv2:theme';const REDUCE_MOTION_HINT_STORAGE_KEY = 'invokeai:v7:webv2:reduce-motion';export const ThemeController = () => {- const { preferences, status } = useWorkbenchSettings();- const { reduceMotion, themeId } = preferences;+ const { reduceMotion, status, themeId } = useWorkbenchSettingsSelector(+ (snapshot) => ({+ reduceMotion: snapshot.preferences.reduceMotion,+ status: snapshot.status,+ themeId: snapshot.preferences.themeId,+ }),+ shallowEqual+ );// Until the settings store has resolved, the pre-paint hint script owns the// theme; applying the store's defaults here would flash and clobber it.const hasResolved = status === 'ready' || status === 'error';diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 72786247e9..8582e61b68 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -9,7 +9,14 @@ import {type ReactNode,} from 'react';-import type { Project, WorkbenchState } from './types';+import type {+ Project,+ ProjectLayoutState,+ ProjectSettings,+ WidgetInstanceId,+ WidgetTypeId,+ WorkbenchState,+} from './types';import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';import {@@ -17,7 +24,9 @@ import {type WorkbenchLoadOptions,type WorkbenchSaveResult,} from './projects/syncedPersistence';-import { getAutosaveScheduleDecision } from './workbenchAutosave';+import { getProjectWidgetValues } from './widgetState';+import { getAutosaveScheduleDecision, getPersistedStateKey, isAutosaveCompletionCurrent } from './workbenchAutosave';+import { shallowEqual as selectorShallowEqual, useExternalStoreSelector } from './workbenchSelectors';import {createWorkbenchStore,type WorkbenchAction,@@ -44,27 +53,7 @@ const WorkbenchStoreContext = createContext<WorkbenchStore | null>(null);const subscribeToNothing = (): (() => void) => () => {};const getNullSnapshot = (): null => null;-export const shallowEqual = <T,>(left: T, right: T): boolean => {- if (Object.is(left, right)) {- return true;- }-- if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {- return false;- }-- const leftRecord = left as Record<PropertyKey, unknown>;- const rightRecord = right as Record<PropertyKey, unknown>;- const leftKeys = Reflect.ownKeys(leftRecord);-- if (leftKeys.length !== Reflect.ownKeys(rightRecord).length) {- return false;- }-- return leftKeys.every(- (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && Object.is(leftRecord[key], rightRecord[key])- );-};+export const shallowEqual = selectorShallowEqual;/*** The reducer dispatch alone, on its own context. `dispatch` is stable for the@@ -76,15 +65,6 @@ const WorkbenchDispatchContext = createContext<Dispatch<WorkbenchAction> | null>const AUTOSAVE_DELAY_MS = 500;-const getPersistedStateKey = (state: WorkbenchState): string =>- JSON.stringify({- account: state.account,- activeProjectId: state.activeProjectId,- errorLog: state.errorLog,- projects: state.projects,- widgetFailures: state.widgetFailures,- });-export const WorkbenchProvider = ({children,loadOptions,@@ -103,7 +83,10 @@ export const WorkbenchProvider = ({const dispatch = store.dispatch;const [hasHydrated, setHasHydrated] = useState(store.getSnapshot().hasHydrated);const hasLoadedPersistenceRef = useRef(false);+ const lastSavedPersistedRevisionRef = useRef(store.getPersistedRevision());const lastSavedStateKeyRef = useRef(getPersistedStateKey(store.getState()));+ const failedPersistedRevisionRef = useRef<number | null>(null);+ const failedStateKeyRef = useRef<string | null>(null);// Captured once: the options describe how this mount of the editor boots.// Later search-param changes are handled live by WorkbenchSessionController.const bootOptionsRef = useRef(loadOptions);@@ -185,8 +168,7 @@ export const WorkbenchProvider = ({useEffect(() => {let timeoutId: number | null = null;let saveGeneration = 0;- let failedStateKey: string | null = null;- let scheduledStateKey: string | null = null;+ let scheduledPersistedRevision: number | null = null;const clearScheduledSave = (): void => {if (timeoutId !== null) {@@ -200,32 +182,51 @@ export const WorkbenchProvider = ({return;}- const state = store.getState();- const persistedStateKey = getPersistedStateKey(state);+ const persistedRevision = store.getPersistedRevision();const decision = getAutosaveScheduleDecision({- failedStateKey,- lastSavedStateKey: lastSavedStateKeyRef.current,- persistedStateKey,- scheduledStateKey,+ failedPersistedRevision: failedPersistedRevisionRef.current,+ lastSavedPersistedRevision: lastSavedPersistedRevisionRef.current,+ persistedRevision,+ scheduledPersistedRevision,});- failedStateKey = decision.failedStateKey;+ if (failedPersistedRevisionRef.current !== null && decision.failedPersistedRevision === null) {+ failedStateKeyRef.current = null;+ }++ failedPersistedRevisionRef.current = decision.failedPersistedRevision;if (!decision.shouldSchedule) {return;}- scheduledStateKey = persistedStateKey;+ scheduledPersistedRevision = persistedRevision;saveGeneration += 1;const generation = saveGeneration;- dispatch({ type: 'autosaveStarted' });clearScheduledSave();timeoutId = window.setTimeout(() => {const stateToSave = store.getState();+ const revisionToSave = store.getPersistedRevision();const stateKeyToSave = getPersistedStateKey(stateToSave);+ if (stateKeyToSave === lastSavedStateKeyRef.current) {+ lastSavedPersistedRevisionRef.current = revisionToSave;+ failedStateKeyRef.current = null;+ failedPersistedRevisionRef.current = null;+ scheduledPersistedRevision = null;+ return;+ }++ if (stateKeyToSave === failedStateKeyRef.current) {+ failedPersistedRevisionRef.current = revisionToSave;+ scheduledPersistedRevision = null;+ return;+ }++ dispatch({ type: 'autosaveStarted' });+syncedWorkbenchPersistence.saveWorkbench(stateToSave).then((result) => {@@ -234,8 +235,10 @@ export const WorkbenchProvider = ({}lastSavedStateKeyRef.current = stateKeyToSave;- failedStateKey = null;- scheduledStateKey = null;+ lastSavedPersistedRevisionRef.current = revisionToSave;+ failedStateKeyRef.current = null;+ failedPersistedRevisionRef.current = null;+ scheduledPersistedRevision = null;dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });applySaveResultRef.current(result);})@@ -244,8 +247,9 @@ export const WorkbenchProvider = ({return;}- failedStateKey = stateKeyToSave;- scheduledStateKey = null;+ failedStateKeyRef.current = stateKeyToSave;+ failedPersistedRevisionRef.current = revisionToSave;+ scheduledPersistedRevision = null;dispatch({error: error instanceof Error ? error.message : 'Failed to autosave workbench.',type: 'autosaveFailed',@@ -286,11 +290,52 @@ export const WorkbenchProvider = ({return;}- void syncedWorkbenchPersistence.saveWorkbench(store.getState()).then((result) => {- applySaveResultRef.current(result);- });+ const stateToSave = store.getState();+ const revisionToSave = store.getPersistedRevision();+ const stateKeyToSave = getPersistedStateKey(stateToSave);++ void syncedWorkbenchPersistence+ .saveWorkbench(stateToSave)+ .then((result) => {+ if (+ !isAutosaveCompletionCurrent({+ completedPersistedRevision: revisionToSave,+ completedStateKey: stateKeyToSave,+ currentPersistedRevision: store.getPersistedRevision(),+ currentStateKey: getPersistedStateKey(store.getState()),+ })+ ) {+ return;+ }++ lastSavedStateKeyRef.current = stateKeyToSave;+ lastSavedPersistedRevisionRef.current = revisionToSave;+ failedStateKeyRef.current = null;+ failedPersistedRevisionRef.current = null;+ dispatch({ savedAt: result.snapshot.savedAt, type: 'autosaveSucceeded' });+ applySaveResultRef.current(result);+ })+ .catch((error: unknown) => {+ if (+ !isAutosaveCompletionCurrent({+ completedPersistedRevision: revisionToSave,+ completedStateKey: stateKeyToSave,+ currentPersistedRevision: store.getPersistedRevision(),+ currentStateKey: getPersistedStateKey(store.getState()),+ })+ ) {+ return;+ }++ failedStateKeyRef.current = stateKeyToSave;+ failedPersistedRevisionRef.current = revisionToSave;+ dispatch({+ error: error instanceof Error ? error.message : 'Failed to autosave workbench.',+ type: 'autosaveFailed',+ });+ });});- }, [store]);+ }, [dispatch, store]);return (<WorkbenchStoreContext value={store}>@@ -315,26 +360,62 @@ export const useOptionalWorkbenchStore = (): WorkbenchStore | null => use(Workbeexport const useWorkbenchSelector = <Selected,>(selector: WorkbenchSelector<Selected>,+ isEqual: EqualityFn<Selected> = shallowEqual+): Selected => {+ const store = useWorkbenchStore();++ return useExternalStoreSelector(store.subscribe, store.getSnapshot, selector, isEqual);+};++export const useDebouncedWorkbenchSelector = <Selected,>(+ selector: WorkbenchSelector<Selected>,+ debounceMs = 300,isEqual: EqualityFn<Selected> = Object.is): Selected => {const store = useWorkbenchStore();- const selectionRef = useRef<Selected | undefined>(undefined);- const hasSelectionRef = useRef(false);+ const [selection, setSelection] = useState(() => selector(store.getSnapshot()));+ const selectionRef = useRef(selection);++ selectionRef.current = selection;- const getSelectedSnapshot = (): Selected => {- const next = selector(store.getSnapshot());+ useEffect(() => {+ let currentSelection = selector(store.getSnapshot());+ let timeoutId: number | null = null;- if (hasSelectionRef.current && isEqual(selectionRef.current as Selected, next)) {- return selectionRef.current as Selected;+ if (!isEqual(selectionRef.current, currentSelection)) {+ selectionRef.current = currentSelection;+ setSelection(currentSelection);}- hasSelectionRef.current = true;- selectionRef.current = next;+ const unsubscribe = store.subscribe(() => {+ const nextSelection = selector(store.getSnapshot());- return next;- };+ if (isEqual(currentSelection, nextSelection)) {+ return;+ }- return useSyncExternalStore(store.subscribe, getSelectedSnapshot, getSelectedSnapshot);+ if (timeoutId !== null) {+ window.clearTimeout(timeoutId);+ }++ timeoutId = window.setTimeout(() => {+ timeoutId = null;+ currentSelection = nextSelection;+ selectionRef.current = nextSelection;+ setSelection(nextSelection);+ }, debounceMs);+ });++ return () => {+ unsubscribe();++ if (timeoutId !== null) {+ window.clearTimeout(timeoutId);+ }+ };+ }, [debounceMs, isEqual, selector, store]);++ return selection;};export const useActiveProject = (): Project => useWorkbenchSelector((snapshot) => snapshot.activeProject);@@ -344,31 +425,60 @@ export const useActiveProjectSelector = <Selected,>(isEqual?: EqualityFn<Selected>): Selected => useWorkbenchSelector((snapshot) => selector(snapshot.activeProject), isEqual);+export const useActiveProjectId = (): string => useWorkbenchSelector((snapshot) => snapshot.state.activeProjectId);++export const useActiveProjectName = (): string => useActiveProjectSelector((project) => project.name);++export const useActiveProjectLayoutSelector = <Selected,>(+ selector: (layout: ProjectLayoutState) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected => useActiveProjectSelector((project) => selector(project.layout), isEqual);++export const useActiveProjectSettingsSelector = <Selected,>(+ selector: (settings: ProjectSettings) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected => useActiveProjectSelector((project) => selector(project.settings), isEqual);++export const useWidgetValuesSelector = <Selected,>(+ widgetId: WidgetTypeId,+ selector: (values: Record<string, unknown>) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected => useActiveProjectSelector((project) => selector(getProjectWidgetValues(project, widgetId)), isEqual);++export const useWidgetInstanceValuesSelector = <Selected,>(+ instanceId: WidgetInstanceId,+ selector: (values: Record<string, unknown>) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected =>+ useActiveProjectSelector((project) => selector(project.widgetInstances[instanceId]?.state.values ?? {}), isEqual);++export const useProjectWidgetInstanceValuesSelector = <Selected,>(+ projectId: string,+ instanceId: WidgetInstanceId,+ selector: (values: Record<string, unknown>) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected =>+ useWorkbenchSelector((snapshot) => {+ const project = snapshot.state.projects.find((candidate) => candidate.id === projectId);++ return selector(project?.widgetInstances[instanceId]?.state.values ?? {});+ }, isEqual);+export const useWorkbenchHasHydrated = (): boolean => useWorkbenchSelector((snapshot) => snapshot.hasHydrated);export const useOptionalWorkbenchSelector = <Selected,>(selector: WorkbenchSelector<Selected>,fallback: Selected,- isEqual: EqualityFn<Selected> = Object.is+ isEqual: EqualityFn<Selected> = shallowEqual): Selected => {const store = useOptionalWorkbenchStore();- const selectionRef = useRef<Selected | undefined>(undefined);- const hasSelectionRef = useRef(false);- const getSelectedSnapshot = (): Selected => {- const next = store ? selector(store.getSnapshot()) : fallback;-- if (hasSelectionRef.current && isEqual(selectionRef.current as Selected, next)) {- return selectionRef.current as Selected;- }-- hasSelectionRef.current = true;- selectionRef.current = next;-- return next;- };-- return useSyncExternalStore(store?.subscribe ?? subscribeToNothing, getSelectedSnapshot, getSelectedSnapshot);+ return useExternalStoreSelector(+ store?.subscribe ?? subscribeToNothing,+ store?.getSnapshot ?? getNullSnapshot,+ (snapshot) => (snapshot ? selector(snapshot) : fallback),+ isEqual+ );};export const useOptionalWorkbenchDispatch = (): Dispatch<WorkbenchAction> | null =>diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex cc42ab1274..cd6f3aa976 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -16,7 +16,13 @@ import { addImagesToGalleryBoard } from './gallery/api';import { getQueueItemResultImages } from './generation/api';import { sanitizeBatchCount } from './generation/batch';import { normalizeGenerateSettings } from './generation/settings';-import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } from './WorkbenchContext';+import {+ useWorkbenchDispatch,+ useWorkbenchHasHydrated,+ useWorkbenchSelector,+ useWorkbenchStore,+} from './WorkbenchContext';+import { createStableSelector } from './workbenchSelectors';import { ensureInvocationTemplatesLoaded } from './workflows/templates';const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {@@ -34,6 +40,28 @@ const getSnapshotBatchCount = (queueItem: QueueItem): number => {return sanitizeBatchCount(batchCount);};+const selectQueueRevision = createStableSelector((snapshot: { state: { projects: Project[] } }) =>+ snapshot.state.projects+ .map((project) =>+ [+ project.id,+ project.queue.items+ .map((item) =>+ [+ item.id,+ item.status,+ item.backendBatchId ?? '',+ item.backendItemIds?.join('.') ?? '',+ item.cancelledBackendItemIds?.join('.') ?? '',+ item.completedBackendItemIds?.join('.') ?? '',+ ].join(':')+ )+ .join(','),+ ].join('=')+ )+ .join('|')+);+/*** Await a tracked run's terminal outcome, route its images to the queue item's* destination, and reflect the outcome in workbench state.@@ -187,17 +215,25 @@ const submitQueueItem = (* inside the WorkbenchProvider; renders nothing.*/export const WorkbenchRuntime = () => {- const state = useWorkbenchSelector((snapshot) => snapshot.state);+ const store = useWorkbenchStore();const dispatch = useWorkbenchDispatch();const hasHydrated = useWorkbenchHasHydrated();+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);+ const queueRevision = useWorkbenchSelector(selectQueueRevision);const coordinatorRef = useRef<QueueCoordinator | null>(null);- const stateRef = useRef(state);+ const stateRef = useRef(store.getState());const startedQueueItemIdsRef = useRef(new Set<string>());const cancelledQueueItemIdsRef = useRef(new Set<string>());const reconcileStateRef = useRef<'idle' | 'running' | 'done'>('idle');const [isReconciled, setIsReconciled] = useState(false);- stateRef.current = state;+ useEffect(+ () =>+ store.subscribe(() => {+ stateRef.current = store.getState();+ }),+ [store]+ );// Mirror the shared socket's connection status (owned by the hub, above the// workbench) into workbench state so the editor's many `backendConnection`@@ -279,7 +315,7 @@ export const WorkbenchRuntime = () => {if (!coordinator ||!hasHydrated ||- state.backendConnection.status !== 'connected' ||+ backendConnectionStatus !== 'connected' ||reconcileStateRef.current !== 'idle') {return;@@ -287,7 +323,7 @@ export const WorkbenchRuntime = () => {reconcileStateRef.current = 'running';- const openItems = state.projects.flatMap((project) =>+ const openItems = stateRef.current.projects.flatMap((project) =>project.queue.items.filter((queueItem) => queueItem.status === 'pending' || queueItem.status === 'running').map((queueItem) => ({ project, queueItem }))@@ -368,7 +404,7 @@ export const WorkbenchRuntime = () => {reconcileStateRef.current = 'done';setIsReconciled(true);});- }, [dispatch, hasHydrated, state.backendConnection.status, state.projects]);+ }, [backendConnectionStatus, dispatch, hasHydrated, queueRevision]);useEffect(() => {const coordinator = coordinatorRef.current;@@ -377,7 +413,7 @@ export const WorkbenchRuntime = () => {return;}- for (const project of state.projects) {+ for (const project of stateRef.current.projects) {for (const queueItem of project.queue.items) {if (queueItem.status === 'pending' &&@@ -402,7 +438,7 @@ export const WorkbenchRuntime = () => {}}}- }, [dispatch, isReconciled, state.projects]);+ }, [dispatch, isReconciled, queueRevision]);return null;};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsxindex 0aa18629db..1655b5dab6 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx@@ -4,7 +4,9 @@ import { useEffect, useRef } from 'react';import type { WorkbenchSearch } from './projects/session';import { hydrateProjectFromServer } from './projects/syncedPersistence';+import { flushGenerateDrafts } from './widgets/generate/generateDraftRegistry';import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } from './WorkbenchContext';+import { areArraysEqual } from './workbenchSelectors';/*** Keeps a mounted editor in line with the /app search params. Renders nothing.@@ -19,15 +21,18 @@ import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } f* library and opens it if not.*/export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch }) => {- const state = useWorkbenchSelector((snapshot) => snapshot.state);+ const projectIds = useWorkbenchSelector(+ (snapshot) => snapshot.state.projects.map((project) => project.id),+ areArraysEqual+ );const dispatch = useWorkbenchDispatch();const hasHydrated = useWorkbenchHasHydrated();const navigate = useNavigate();- const latestStateRef = useRef(state);+ const latestProjectIdsRef = useRef(projectIds);// The mount-time param was already handled by the boot load options.const handledProjectIdRef = useRef<string | null>(search.project ?? null);- latestStateRef.current = state;+ latestProjectIdsRef.current = projectIds;const isNewRequested = search.new === true;@@ -48,7 +53,8 @@ export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearchhandledProjectIdRef.current = requestedProjectId;- if (latestStateRef.current.projects.some((project) => project.id === requestedProjectId)) {+ if (latestProjectIdsRef.current.includes(requestedProjectId)) {+ flushGenerateDrafts();dispatch({ projectId: requestedProjectId, type: 'switchProject' });return undefined;@@ -62,6 +68,7 @@ export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch}if (project) {+ flushGenerateDrafts();dispatch({ project, type: 'openProject' });} else {dispatch({diff --git a/invokeai/frontend/webv2/src/workbench/backend/connectionStore.ts b/invokeai/frontend/webv2/src/workbench/backend/connectionStore.tsindex 7925cf327e..d2e87c5beb 100644--- a/invokeai/frontend/webv2/src/workbench/backend/connectionStore.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/connectionStore.ts@@ -22,6 +22,8 @@ export const setConnectionStatus = (status: BackendConnectionStatus, error?: strexport const getConnectionStatus = (): ConnectionSnapshot => store.getSnapshot();+export const useConnectionStatusSelector = store.useSelector;+export const useConnectionStatus = (): ConnectionSnapshot => store.useSnapshot();export const subscribeConnection = (listener: () => void): (() => void) => store.subscribe(listener);diff --git a/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.ts b/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.tsindex 2f3e4f6810..d4835cd331 100644--- a/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/modelLoadStore.ts@@ -1,26 +1,10 @@-import { useSyncExternalStore } from 'react';+import { createExternalStore } from '@workbench/externalStore';export interface ModelLoadInfo {label: string;}-const listeners = new Set<() => void>();--let activeLoads: ModelLoadInfo[] = [];--const emit = (): void => {- for (const listener of listeners) {- listener();- }-};--const subscribe = (listener: () => void): (() => void) => {- listeners.add(listener);-- return () => {- listeners.delete(listener);- };-};+const store = createExternalStore<{ activeLoads: ModelLoadInfo[] }>({ activeLoads: [] });const getModelLoadLabel = (payload: unknown): string => {const record = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {};@@ -35,27 +19,20 @@ const getModelLoadLabel = (payload: unknown): string => {export const modelLoadStore = {started(payload: unknown): void {- activeLoads = [...activeLoads, { label: getModelLoadLabel(payload) }];- emit();+ store.patchSnapshot({ activeLoads: [...store.getSnapshot().activeLoads, { label: getModelLoadLabel(payload) }] });},completed(payload: unknown): void {const label = getModelLoadLabel(payload);+ const { activeLoads } = store.getSnapshot();const index = activeLoads.findIndex((load) => load.label === label);- if (index >= 0) {- activeLoads = activeLoads.filter((_, loadIndex) => loadIndex !== index);- } else {- activeLoads = activeLoads.slice(1);- }-- emit();+ store.patchSnapshot({+ activeLoads: index >= 0 ? activeLoads.filter((_, loadIndex) => loadIndex !== index) : activeLoads.slice(1),+ });},reset(): void {- if (activeLoads.length > 0) {- activeLoads = [];- emit();- }+ store.patchSnapshot({ activeLoads: [] });},};-export const useModelLoads = (): ModelLoadInfo[] => useSyncExternalStore(subscribe, () => activeLoads);+export const useModelLoads = (): ModelLoadInfo[] => store.useSelector((snapshot) => snapshot.activeLoads);diff --git a/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.tsindex feeae31499..477f732f64 100644--- a/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/nodeExecutionStore.ts@@ -1,4 +1,4 @@-import { useSyncExternalStore } from 'react';+import { createKeyedTransientStore } from '@workbench/externalStore';import type { InvocationCompleteEvent, InvocationErrorEvent, InvocationStartedEvent } from './events';@@ -24,22 +24,7 @@ export interface NodeExecutionState {error: string | null;}-const stateByNodeId = new Map<string, NodeExecutionState>();-const listeners = new Set<() => void>();--const emit = (): void => {- for (const listener of listeners) {- listener();- }-};--const subscribe = (listener: () => void): (() => void) => {- listeners.add(listener);-- return () => {- listeners.delete(listener);- };-};+const stateByNodeId = createKeyedTransientStore<string, NodeExecutionState>();/** Pull the produced image out of an invocation output, whatever the node type. */const getResultImageName = (result: InvocationCompleteEvent['result']): string | null => {@@ -50,10 +35,7 @@ const getResultImageName = (result: InvocationCompleteEvent['result']): string |export const nodeExecutionStore = {clearAll(): void {- if (stateByNodeId.size > 0) {- stateByNodeId.clear();- emit();- }+ stateByNodeId.clear();},completed(event: InvocationCompleteEvent): void {const imageName = getResultImageName(event.result);@@ -68,7 +50,6 @@ export const nodeExecutionStore = {progressMessage: null,status: 'completed',});- emit();},failed(event: InvocationErrorEvent): void {const previous = stateByNodeId.get(event.invocation_source_id);@@ -80,7 +61,6 @@ export const nodeExecutionStore = {progressMessage: null,status: 'failed',});- emit();},progress(nodeId: string, percentage: number | null, message: string): void {const previous = stateByNodeId.get(nodeId);@@ -92,22 +72,14 @@ export const nodeExecutionStore = {progressMessage: message,status: 'running',});- emit();},/** A queue item reached a terminal state: nothing can still be running. */settleRunning(): void {- let changed = false;-- for (const [nodeId, state] of stateByNodeId) {+ for (const [nodeId, state] of stateByNodeId.entries()) {if (state.status === 'running') {stateByNodeId.set(nodeId, { ...state, progress: null, progressMessage: null, status: 'completed' });- changed = true;}}-- if (changed) {- emit();- }},started(event: InvocationStartedEvent): void {const previous = stateByNodeId.get(event.invocation_source_id);@@ -119,11 +91,10 @@ export const nodeExecutionStore = {progressMessage: null,status: 'running',});- emit();},};export type NodeExecutionSink = typeof nodeExecutionStore;export const useNodeExecutionState = (nodeId: string): NodeExecutionState | null =>- useSyncExternalStore(subscribe, () => stateByNodeId.get(nodeId) ?? null);+ stateByNodeId.useValue(nodeId) ?? null;diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts b/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.tsindex ea72251399..b80aa68238 100644--- a/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/progressImageStore.ts@@ -1,4 +1,4 @@-import { useSyncExternalStore } from 'react';+import { createExternalStore, createKeyedTransientStore } from '@workbench/externalStore';/*** The most recent denoising preview image from `invocation_progress` events,@@ -19,67 +19,48 @@ export interface ProgressImageTarget {type LatestProgressImageSnapshot = ProgressImageSnapshot & { target?: ProgressImageTarget };-let latestSnapshot: LatestProgressImageSnapshot | null = null;-const snapshotsByTarget = new Map<string, ProgressImageSnapshot>();-const listeners = new Set<() => void>();+const latestSnapshotStore = createExternalStore<{ latestSnapshot: LatestProgressImageSnapshot | null }>({+ latestSnapshot: null,+});+const snapshotsByTarget = createKeyedTransientStore<string, ProgressImageSnapshot>();const getTargetKey = ({ itemIndex, queueItemId }: ProgressImageTarget): string => `${queueItemId}:${itemIndex}`;const isLatestTarget = (target: ProgressImageTarget): boolean =>- latestSnapshot?.target?.queueItemId === target.queueItemId && latestSnapshot.target.itemIndex === target.itemIndex;--const emit = (): void => {- for (const listener of listeners) {- listener();- }-};--const subscribe = (listener: () => void): (() => void) => {- listeners.add(listener);-- return () => {- listeners.delete(listener);- };-};+ latestSnapshotStore.getSnapshot().latestSnapshot?.target?.queueItemId === target.queueItemId &&+ latestSnapshotStore.getSnapshot().latestSnapshot?.target?.itemIndex === target.itemIndex;export const progressImageStore = {clear(target?: ProgressImageTarget): void {if (!target) {- if (latestSnapshot !== null || snapshotsByTarget.size > 0) {- latestSnapshot = null;- snapshotsByTarget.clear();- emit();- }+ latestSnapshotStore.patchSnapshot({ latestSnapshot: null });+ snapshotsByTarget.clear();return;}- const didDeleteTarget = snapshotsByTarget.delete(getTargetKey(target));+ const targetKey = getTargetKey(target);const didClearLatest = isLatestTarget(target);- if (didClearLatest) {- latestSnapshot = null;- }+ snapshotsByTarget.delete(targetKey);- if (didDeleteTarget || didClearLatest) {- emit();+ if (didClearLatest) {+ latestSnapshotStore.patchSnapshot({ latestSnapshot: null });}},set(image: ProgressImageSnapshot, target?: ProgressImageTarget): void {- latestSnapshot = target ? { ...image, target } : image;+ latestSnapshotStore.patchSnapshot({ latestSnapshot: target ? { ...image, target } : image });if (target) {snapshotsByTarget.set(getTargetKey(target), image);}-- emit();},};export type ProgressImageSink = typeof progressImageStore;export const useProgressImage = (): ProgressImageSnapshot | null =>- useSyncExternalStore(subscribe, () => latestSnapshot);+ latestSnapshotStore.useSelector((snapshot) => snapshot.latestSnapshot);export const useQueueItemProgressImage = (queueItemId: string, itemIndex: number): ProgressImageSnapshot | null =>- useSyncExternalStore(subscribe, () => snapshotsByTarget.get(getTargetKey({ itemIndex, queueItemId })) ?? null);+ snapshotsByTarget.useValue(getTargetKey({ itemIndex, queueItemId })) ?? null;diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts b/invokeai/frontend/webv2/src/workbench/backend/progressStore.tsindex ed44b184ff..b96ac07884 100644--- a/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts+++ b/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts@@ -1,4 +1,4 @@-import { useSyncExternalStore } from 'react';+import { createKeyedTransientStore } from '@workbench/externalStore';/*** Ephemeral live-progress store for in-flight queue items, keyed by the local@@ -25,40 +25,19 @@ export interface QueueItemProgressSink {clear(queueItemId: string): void;}-const progressByQueueItemId = new Map<string, QueueItemProgress>();-const listeners = new Set<() => void>();--const emit = (): void => {- for (const listener of listeners) {- listener();- }-};--const subscribe = (listener: () => void): (() => void) => {- listeners.add(listener);-- return () => {- listeners.delete(listener);- };-};+const progressByQueueItemId = createKeyedTransientStore<string, QueueItemProgress>();export const queueItemProgressStore: QueueItemProgressSink = {clearAll() {- if (progressByQueueItemId.size > 0) {- progressByQueueItemId.clear();- emit();- }+ progressByQueueItemId.clear();},clear(queueItemId) {- if (progressByQueueItemId.delete(queueItemId)) {- emit();- }+ progressByQueueItemId.delete(queueItemId);},set(queueItemId, progress) {progressByQueueItemId.set(queueItemId, progress);- emit();},};export const useQueueItemProgress = (queueItemId: string): QueueItemProgress | null =>- useSyncExternalStore(subscribe, () => progressByQueueItemId.get(queueItemId) ?? null);+ progressByQueueItemId.useValue(queueItemId) ?? null;diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.ts b/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.tsindex e28070ad4d..9acd002ff5 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.ts+++ b/invokeai/frontend/webv2/src/workbench/customNodes/installLogStore.ts@@ -33,4 +33,4 @@ export const clearCustomNodeInstallLog = (): void => {store.patchSnapshot({ log: [] });};-export const useCustomNodeInstallLog = (): CustomNodeInstallLogEntry[] => store.useSnapshot().log;+export const useCustomNodeInstallLog = (): CustomNodeInstallLogEntry[] => store.useSelector((snapshot) => snapshot.log);diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.ts b/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.tsindex fa1ab977e1..da7474a603 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.ts+++ b/invokeai/frontend/webv2/src/workbench/customNodes/nodesStore.ts@@ -60,4 +60,6 @@ export const removeCustomNodePackFromStore = (packName: string): void => {store.patchSnapshot({ nodePacks: store.getSnapshot().nodePacks.filter((pack) => pack.name !== packName) });};+export const useCustomNodesSelector = store.useSelector;+export const useCustomNodesSnapshot = (): CustomNodesSnapshot => store.useSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.ts b/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.tsindex c76879065a..c2b6fc0271 100644--- a/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.ts+++ b/invokeai/frontend/webv2/src/workbench/customNodes/nodesUiStore.ts@@ -40,4 +40,6 @@ export const setNodeActivityExpanded = (activityExpanded: boolean): void => {updateNodesUi({ activityExpanded });};+export const useNodesUiSelector = store.useSelector;+export const useNodesUi = (): NodesUiSnapshot => store.useSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.ts b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.tsnew file mode 100644index 0000000000..5fb22c8472--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.test.ts@@ -0,0 +1,44 @@+import type { WidgetContributionSource } from '@workbench/types';++import { describe, expect, it } from 'vitest';++import {+ areWidgetContributionSourcesEqual,+ getWidgetContributionRegistrationKey,+ getWidgetContributionSourceKey,+} from './contributionSource';++const source = (overrides: Partial<WidgetContributionSource> = {}): WidgetContributionSource => ({+ instanceId: 'generate',+ projectId: 'project-1',+ region: 'left',+ typeId: 'generate',+ ...overrides,+});++describe('areWidgetContributionSourcesEqual', () => {+ it('matches widget contribution sources by project, region, type, and instance', () => {+ expect(areWidgetContributionSourcesEqual(source(), source())).toBe(true);+ expect(areWidgetContributionSourcesEqual(source(), source({ projectId: 'project-2' }))).toBe(false);+ expect(areWidgetContributionSourcesEqual(source(), source({ instanceId: 'generate:2' }))).toBe(false);+ expect(areWidgetContributionSourcesEqual(source(), null)).toBe(false);+ });+});++describe('getWidgetContributionRegistrationKey', () => {+ it('creates stable replacement keys per command id and source', () => {+ expect(getWidgetContributionRegistrationKey('generate.run', source())).toBe(+ getWidgetContributionRegistrationKey('generate.run', source())+ );+ expect(getWidgetContributionRegistrationKey('generate.run', source())).not.toBe(+ getWidgetContributionRegistrationKey('generate.run', source({ projectId: 'project-2' }))+ );+ expect(getWidgetContributionRegistrationKey('generate.run', undefined)).not.toBe(+ getWidgetContributionRegistrationKey('generate.run', source())+ );+ });++ it('keeps source keys stable without depending on object identity', () => {+ expect(getWidgetContributionSourceKey(source())).toBe(getWidgetContributionSourceKey({ ...source() }));+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.ts b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.tsnew file mode 100644index 0000000000..b454643f2a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/extensions/contributionSource.ts@@ -0,0 +1,29 @@+import type { WidgetContributionSource } from '@workbench/types';++const GLOBAL_SOURCE_KEY = 'global';++export const areWidgetContributionSourcesEqual = (+ left: WidgetContributionSource | null | undefined,+ right: WidgetContributionSource | null | undefined+): boolean => {+ if (!left || !right) {+ return false;+ }++ return (+ left.projectId === right.projectId &&+ left.region === right.region &&+ left.typeId === right.typeId &&+ left.instanceId === right.instanceId+ );+};++export const getWidgetContributionSourceKey = (source: WidgetContributionSource | null | undefined): string =>+ source+ ? JSON.stringify(['widget', source.projectId, source.region, source.typeId, source.instanceId])+ : GLOBAL_SOURCE_KEY;++export const getWidgetContributionRegistrationKey = (+ id: string,+ source: WidgetContributionSource | null | undefined+): string => JSON.stringify([id, getWidgetContributionSourceKey(source)]);diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.tsindex 4673a1f2df..fa47c45b2f 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.ts@@ -14,4 +14,97 @@ describe('commandApi', () => {await expect(commandApi.execute('test.command')).resolves.toBeUndefined();});++ it('replaces duplicate global command registrations', async () => {+ const firstHandler = vi.fn(() => 'first');+ const secondHandler = vi.fn(() => 'second');+ const disposeFirst = commandApi.register({ handler: firstHandler, id: 'test.duplicate-command', title: 'First' });+ const disposeSecond = commandApi.register({+ handler: secondHandler,+ id: 'test.duplicate-command',+ title: 'Second',+ });++ await expect(commandApi.execute('test.duplicate-command')).resolves.toBe('second');++ disposeFirst();++ await expect(commandApi.execute('test.duplicate-command')).resolves.toBe('second');++ disposeSecond();++ await expect(commandApi.execute('test.duplicate-command')).resolves.toBeUndefined();+ });++ it('replaces duplicate command registrations from the same source', async () => {+ const firstHandler = vi.fn(() => 'first');+ const secondHandler = vi.fn(() => 'second');+ const source = { instanceId: 'alpha', projectId: 'project-1', region: 'right', typeId: 'test-widget' } as const;+ const disposeFirst = commandApi.register({+ handler: firstHandler,+ id: 'test.replace-command',+ source,+ title: 'First',+ });+ const disposeSecond = commandApi.register({+ handler: secondHandler,+ id: 'test.replace-command',+ source,+ title: 'Second',+ });++ await expect(commandApi.executeForSource('test.replace-command', source)).resolves.toBe('second');++ disposeFirst();++ await expect(commandApi.executeForSource('test.replace-command', source)).resolves.toBe('second');++ disposeSecond();++ await expect(commandApi.executeForSource('test.replace-command', source)).resolves.toBeUndefined();+ });++ it('does not execute a command registered by the same widget source in another project', async () => {+ const handler = vi.fn(() => 'project-1');+ const dispose = commandApi.register({+ handler,+ id: 'test.project-command',+ source: { instanceId: 'alpha', projectId: 'project-1', region: 'right', typeId: 'test-widget' },+ title: 'Project command',+ });++ await expect(+ commandApi.executeForSource('test.project-command', {+ instanceId: 'alpha',+ projectId: 'project-2',+ region: 'right',+ typeId: 'test-widget',+ })+ ).resolves.toBeUndefined();+ expect(handler).not.toHaveBeenCalled();++ dispose();+ });++ it('does not fall back to another widget instance when executing for a source', async () => {+ const handler = vi.fn(() => 'beta');+ const dispose = commandApi.register({+ handler,+ id: 'test.scoped-command',+ source: { instanceId: 'beta', projectId: 'project-1', region: 'right', typeId: 'test-widget' },+ title: 'Scoped command',+ });++ await expect(+ commandApi.executeForSource('test.scoped-command', {+ instanceId: 'alpha',+ projectId: 'project-1',+ region: 'right',+ typeId: 'test-widget',+ })+ ).resolves.toBeUndefined();+ expect(handler).not.toHaveBeenCalled();++ dispose();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.tsindex 70e919356a..fbc7e3e0f0 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts@@ -3,6 +3,7 @@ import type {WidgetCommandContribution,WidgetCommandPaletteApi,WidgetCommandPaletteContribution,+ WidgetContributionSource,WidgetHotkeyApi,WidgetHotkeyContribution,WidgetMenuApi,@@ -13,70 +14,54 @@ import type {WidgetToolbarContribution,} from '@workbench/types';-const noopDispose = (): void => {};--class ContributionStore<Contribution> {- private readonly contributions = new Map<string, Contribution>();- private readonly listeners = new Set<() => void>();-- register(contribution: Contribution, fallbackId: string): () => void {- const id = fallbackId;-- this.contributions.set(id, contribution);- this.notify();-- return () => {- this.contributions.delete(id);- this.notify();- };- }-- list(): Contribution[] {- return [...this.contributions.values()];- }+import { createCollectionStore } from '@workbench/externalStore';- subscribe(listener: () => void): () => void {- this.listeners.add(listener);+import { areWidgetContributionSourcesEqual, getWidgetContributionRegistrationKey } from './contributionSource';- return () => {- this.listeners.delete(listener);- };- }-- private notify(): void {- for (const listener of this.listeners) {- listener();- }- }-}+const noopDispose = (): void => {};-const commandStore = new ContributionStore<WidgetCommandContribution>();-const hotkeyStore = new ContributionStore<WidgetHotkeyContribution>();-const menuStore = new ContributionStore<WidgetMenuContribution>();-const paletteStore = new ContributionStore<WidgetCommandPaletteContribution>();-const searchStore = new ContributionStore<WidgetSearchProvider>();-const toolbarStore = new ContributionStore<WidgetToolbarContribution>();+const commandStore = createCollectionStore<WidgetCommandContribution>();+const hotkeyStore = createCollectionStore<WidgetHotkeyContribution>();+const menuStore = createCollectionStore<WidgetMenuContribution>();+const paletteStore = createCollectionStore<WidgetCommandPaletteContribution>();+const searchStore = createCollectionStore<WidgetSearchProvider>();+const toolbarStore = createCollectionStore<WidgetToolbarContribution>();++const findCommand = (+ commandId: string,+ source: WidgetContributionSource | null = null+): WidgetCommandContribution | undefined =>+ source+ ? (commandStore.findLatest(+ (candidate) => candidate.id === commandId && areWidgetContributionSourcesEqual(candidate.source, source)+ ) ?? commandStore.findLatest((candidate) => candidate.id === commandId && !candidate.source))+ : commandStore.findLatest((candidate) => candidate.id === commandId && !candidate.source);export const commandApi: WidgetCommandApi = {execute(commandId, ...args) {- const command = commandStore.list().find((candidate) => candidate.id === commandId);+ const command = findCommand(commandId);++ return Promise.resolve(command ? command.handler(...args) : undefined);+ },+ executeForSource(commandId, source, ...args) {+ const command = findCommand(commandId, source);return Promise.resolve(command ? command.handler(...args) : undefined);},register(command) {- return commandStore.register(command, command.id);+ return commandStore.register(command, getWidgetContributionRegistrationKey(command.id, command.source));},};export const hotkeyApi: WidgetHotkeyApi = {register(hotkey) {- return hotkeyStore.register(hotkey, hotkey.id);+ return hotkeyStore.register(hotkey, getWidgetContributionRegistrationKey(hotkey.id, hotkey.source));},};export const menuApi: WidgetMenuApi = {register(menu) {- return menuStore.register(menu, menu.id);+ return menuStore.register(menu, getWidgetContributionRegistrationKey(menu.id, menu.source));},};diff --git a/invokeai/frontend/webv2/src/workbench/externalStore.test.ts b/invokeai/frontend/webv2/src/workbench/externalStore.test.tsnew file mode 100644index 0000000000..7a39c7acac--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/externalStore.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it, vi } from 'vitest';++import { createCollectionStore, createExternalStore, createKeyedTransientStore } from './externalStore';++describe('createExternalStore', () => {+ it('does not notify listeners for identical snapshots or empty patches', () => {+ const initial = { count: 0, label: 'idle' };+ const store = createExternalStore(initial);+ const listener = vi.fn();++ store.subscribe(listener);++ store.setSnapshot(initial);+ store.setSnapshot({ count: 0, label: 'idle' });+ store.patchSnapshot({});+ store.patchSnapshot({ count: 0 });++ expect(listener).not.toHaveBeenCalled();+ });++ it('notifies when a patch adds an undefined optional key', () => {+ const store = createExternalStore<{ count: number; label?: string }>({ count: 0 });+ const listener = vi.fn();++ store.subscribe(listener);+ store.patchSnapshot({ label: undefined });++ expect(listener).toHaveBeenCalledTimes(1);+ expect(Object.prototype.hasOwnProperty.call(store.getSnapshot(), 'label')).toBe(true);+ });+});++describe('createKeyedTransientStore', () => {+ it('notifies only listeners for the changed key and global listeners', () => {+ const store = createKeyedTransientStore<string, number>();+ const keyListener = vi.fn();+ const otherKeyListener = vi.fn();+ const globalListener = vi.fn();++ store.subscribeKey('a', keyListener);+ store.subscribeKey('b', otherKeyListener);+ store.subscribe(globalListener);++ store.set('a', 1);++ expect(keyListener).toHaveBeenCalledTimes(1);+ expect(otherKeyListener).not.toHaveBeenCalled();+ expect(globalListener).toHaveBeenCalledTimes(1);+ expect(store.get('a')).toBe(1);+ });++ it('does not notify when setting an identical value', () => {+ const store = createKeyedTransientStore<string, number>();+ const listener = vi.fn();++ store.set('a', 1);+ store.subscribeKey('a', listener);+ store.set('a', 1);++ expect(listener).not.toHaveBeenCalled();+ });+});++describe('createCollectionStore', () => {+ it('returns a stable list snapshot until registrations change', () => {+ const store = createCollectionStore<{ id: string }>();++ const empty = store.list();++ expect(store.list()).toBe(empty);++ const dispose = store.register({ id: 'first' }, 'first');+ const populated = store.list();++ expect(populated).not.toBe(empty);+ expect(store.list()).toBe(populated);++ dispose();++ expect(store.list()).not.toBe(populated);+ expect(store.list()).toEqual([]);+ });++ it('replaces duplicate logical registrations and only the active disposer can clear them', () => {+ const store = createCollectionStore<{ id: string; value: string }>();+ const disposeFirst = store.register({ id: 'duplicate', value: 'first' }, 'duplicate');+ const disposeSecond = store.register({ id: 'duplicate', value: 'second' }, 'duplicate');++ expect(store.list()).toEqual([{ id: 'duplicate', value: 'second' }]);+ expect(store.findLatest((item) => item.id === 'duplicate')?.value).toBe('second');++ disposeFirst();++ expect(store.findLatest((item) => item.id === 'duplicate')?.value).toBe('second');++ disposeSecond();++ expect(store.findLatest((item) => item.id === 'duplicate')).toBeUndefined();+ });++ it('keeps registrations with different logical keys side by side', () => {+ const store = createCollectionStore<{ id: string; value: string }>();+ const disposeFirst = store.register({ id: 'duplicate', value: 'first' }, 'duplicate:first');+ const disposeSecond = store.register({ id: 'duplicate', value: 'second' }, 'duplicate:second');++ expect(store.list()).toEqual([+ { id: 'duplicate', value: 'first' },+ { id: 'duplicate', value: 'second' },+ ]);++ disposeFirst();++ expect(store.list()).toEqual([{ id: 'duplicate', value: 'second' }]);++ disposeSecond();++ expect(store.findLatest((item) => item.id === 'duplicate')).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/externalStore.ts b/invokeai/frontend/webv2/src/workbench/externalStore.tsindex 7b00877087..d0a26ae455 100644--- a/invokeai/frontend/webv2/src/workbench/externalStore.ts+++ b/invokeai/frontend/webv2/src/workbench/externalStore.ts@@ -1,4 +1,6 @@-import { useSyncExternalStore } from 'react';+import { useCallback, useSyncExternalStore } from 'react';++import { shallowEqual, useExternalStoreSelector, type EqualityFn } from './workbenchSelectors';/*** Minimal factory for module-level stores backed by `useSyncExternalStore`.@@ -42,8 +44,19 @@ export interface ExternalStore<Snapshot extends object> extends ListenerChannelsetSnapshotSilently: (next: Snapshot) => void;/** Subscribe the calling component to the snapshot. */useSnapshot: () => Snapshot;+ /** Subscribe the calling component to a selected snapshot value. */+ useSelector: <Selected>(+ selector: (snapshot: Snapshot) => Selected,+ isEqual?: (left: Selected, right: Selected) => boolean+ ) => Selected;}+const hasPatchChanges = <Snapshot extends object>(snapshot: Snapshot, patch: Partial<Snapshot>): boolean =>+ Object.entries(patch).some(+ ([key, value]) =>+ !Object.prototype.hasOwnProperty.call(snapshot, key) || !Object.is(snapshot[key as keyof Snapshot], value)+ );+export const createExternalStore = <Snapshot extends object>(initialSnapshot: Snapshot): ExternalStore<Snapshot> => {let snapshot = initialSnapshot;const channel = createListenerChannel();@@ -51,20 +64,175 @@ export const createExternalStore = <Snapshot extends object>(initialSnapshot: Snconst getSnapshot = (): Snapshot => snapshot;const setSnapshot = (next: Snapshot): void => {+ if (shallowEqual(next, snapshot)) {+ return;+ }+snapshot = next;channel.notify();};const useSnapshot = (): Snapshot => useSyncExternalStore(channel.subscribe, getSnapshot);+ const useSelector = <Selected>(+ selector: (snapshot: Snapshot) => Selected,+ isEqual: EqualityFn<Selected> = shallowEqual+ ): Selected => useExternalStoreSelector(channel.subscribe, getSnapshot, selector, isEqual);+return {...channel,getSnapshot,- patchSnapshot: (next) => setSnapshot({ ...snapshot, ...next }),+ patchSnapshot: (next) => {+ if (!hasPatchChanges(snapshot, next)) {+ return;+ }++ setSnapshot({ ...snapshot, ...next });+ },setSnapshot,setSnapshotSilently: (next) => {snapshot = next;},+ useSelector,useSnapshot,};};++export interface KeyedTransientStore<Key, Value> extends ListenerChannel {+ clear: () => void;+ delete: (key: Key) => void;+ entries: () => Array<[Key, Value]>;+ get: (key: Key) => Value | undefined;+ set: (key: Key, value: Value) => void;+ subscribeKey: (key: Key, listener: () => void) => () => void;+ useValue: (key: Key) => Value | undefined;+}++export const createKeyedTransientStore = <Key, Value>(+ isEqual: EqualityFn<Value | undefined> = Object.is+): KeyedTransientStore<Key, Value> => {+ const values = new Map<Key, Value>();+ const channel = createListenerChannel();+ const keyedListeners = new Map<Key, Set<() => void>>();++ const notifyKey = (key: Key): void => {+ for (const listener of keyedListeners.get(key) ?? []) {+ listener();+ }++ channel.notify();+ };++ const subscribeKey = (key: Key, listener: () => void): (() => void) => {+ const listeners = keyedListeners.get(key) ?? new Set<() => void>();++ listeners.add(listener);+ keyedListeners.set(key, listeners);++ return () => {+ listeners.delete(listener);++ if (listeners.size === 0) {+ keyedListeners.delete(key);+ }+ };+ };++ const get = (key: Key): Value | undefined => values.get(key);++ return {+ ...channel,+ clear: () => {+ if (values.size === 0) {+ return;+ }++ const keys = Array.from(values.keys());+ values.clear();++ for (const key of keys) {+ for (const listener of keyedListeners.get(key) ?? []) {+ listener();+ }+ }++ channel.notify();+ },+ delete: (key) => {+ if (values.delete(key)) {+ notifyKey(key);+ }+ },+ entries: () => [...values.entries()],+ get,+ set: (key, value) => {+ if (values.has(key) && isEqual(values.get(key), value)) {+ return;+ }++ values.set(key, value);+ notifyKey(key);+ },+ subscribeKey,+ useValue: (key) => {+ const subscribe = useCallback((listener: () => void) => subscribeKey(key, listener), [key]);+ const getKeySnapshot = useCallback(() => get(key), [key]);++ return useSyncExternalStore(subscribe, getKeySnapshot);+ },+ };+};++export interface CollectionStore<Contribution> extends ListenerChannel {+ findLatest: (predicate: (contribution: Contribution) => boolean) => Contribution | undefined;+ list: () => Contribution[];+ register: (contribution: Contribution, registrationKey: string) => () => void;+ useList: () => Contribution[];+}++export const createCollectionStore = <Contribution>(): CollectionStore<Contribution> => {+ let nextRegistrationId = 0;+ const contributions = new Map<string, { contribution: Contribution; token: number }>();+ const channel = createListenerChannel();+ let listSnapshot: Contribution[] = [];+ const refreshListSnapshot = (): void => {+ listSnapshot = [...contributions.values()].map((entry) => entry.contribution);+ };+ const list = (): Contribution[] => listSnapshot;++ return {+ ...channel,+ findLatest: (predicate) => {+ const items = list();++ for (let index = items.length - 1; index >= 0; index -= 1) {+ const contribution = items[index];++ if (contribution !== undefined && predicate(contribution)) {+ return contribution;+ }+ }++ return undefined;+ },+ list,+ register: (contribution, registrationKey) => {+ const id = registrationKey;+ const token = nextRegistrationId;++ nextRegistrationId += 1;+ contributions.delete(id);+ contributions.set(id, { contribution, token });+ refreshListSnapshot();+ channel.notify();++ return () => {+ if (contributions.get(id)?.token === token && contributions.delete(id)) {+ refreshListSnapshot();+ channel.notify();+ }+ };+ },+ useList: () => useSyncExternalStore(channel.subscribe, list),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 15181ea84c..8c368e1af2 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -4,7 +4,7 @@ import { createContext, use, useState } from 'react';import type { WidgetRegion } from './types';-import { useWorkbenchPreferences } from './settings/store';+import { useWorkbenchPreferenceSelector } from './settings/store';let focusedRegionSnapshot: WidgetRegion | null = null;@@ -62,7 +62,9 @@ const useFocusRegionContext = () => {export const useFocusRegionProps = (region: WidgetRegion) => {const { focusedRegion, setFocusedRegion } = useFocusRegionContext();- const { showFocusRegionHighlight } = useWorkbenchPreferences();+ const showFocusRegionHighlight = useWorkbenchPreferenceSelector(+ (preferences) => preferences.showFocusRegionHighlight+ );const isHighlighted = showFocusRegionHighlight && focusedRegion === region;return {diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsxindex 1464312ff4..432d438aef 100644--- a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewDialog.tsx@@ -3,9 +3,17 @@ import type { XYPosition } from '@workbench/workflows/types';import { Box, Dialog, Portal, SegmentGroup, Text } from '@chakra-ui/react';import { Button, JsonPreview } from '@workbench/components/ui';-import { formatRoute, isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';-import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import {+ createInvocationRouteInputSelector,+ formatRoute,+ isInvocationRouteValid,+ resolveInvocationRoute,+ resolveInvocationRouteInput,+} from '@workbench/invocation';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { useEffect, useState, type ReactNode } from 'react';import { GraphPreviewFlow } from './GraphPreviewFlow';@@ -23,6 +31,8 @@ interface GraphPreviewDialogProps {type PreviewMode = 'nodes' | 'json';+const selectInvocationRouteInput = createInvocationRouteInputSelector();+const PreviewPane = ({ children }: { children: ReactNode }) => (<Box flex="1" h="full" minH="0" minW="0" w="full" rounded="md" borderWidth={1} overflow="hidden">{children}@@ -38,16 +48,21 @@ export const GraphPreviewDialog = ({title,onOpenChange,}: GraphPreviewDialogProps) => {- const activeProject = useActiveProject();+ const routeInput = useActiveProjectSelector(selectInvocationRouteInput);const dispatch = useWorkbenchDispatch();- const { models, status: modelsStatus } = useModelsSnapshot();+ const store = useWorkbenchStore();+ const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const availabilityModels = modelsStatus === 'loaded' ? models : undefined;const [mode, setMode] = useState<PreviewMode>('nodes');++ useInvocationTemplatesSelector((snapshot) => snapshot.status);+const dialogRoute = sourceId- ? resolveInvocationRoute(- activeProject,+ ? resolveInvocationRouteInput(+ routeInput,'dialog',- { ...activeProject.invocation, sourceId, sourceLocked: true },+ { ...routeInput.invocation, sourceId, sourceLocked: true },availabilityModels): null;@@ -97,18 +112,31 @@ export const GraphPreviewDialog = ({<Dialog.Footer>{dialogRoute ? (<Button- disabled={!canInvoke}+ aria-disabled={!canInvoke}+ cursor={canInvoke ? undefined : 'not-allowed'}+ opacity={canInvoke ? undefined : 0.6}size="sm"title={dialogRoute.validationMessage}onClick={() => {- if (!canInvoke) {+ flushGenerateDrafts();+ const postFlushProject = store.getSnapshot().activeProject;+ const postFlushRoute = sourceId+ ? resolveInvocationRoute(+ postFlushProject,+ 'dialog',+ { ...postFlushProject.invocation, sourceId, sourceLocked: true },+ availabilityModels+ )+ : null;++ if (!postFlushRoute || !isInvocationRouteValid(postFlushRoute)) {return;}dispatch({backendSupportsCancellation: true,models: availabilityModels,- route: dialogRoute,+ route: postFlushRoute,type: 'submitResolvedInvocationSnapshot',});onOpenChange(false);diff --git a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsxindex 37bdebcc2b..164b2fd607 100644--- a/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/workbench/graph-preview/GraphPreviewFlow.tsx@@ -1,7 +1,7 @@import type { GraphContract } from '@workbench/types';import { Badge, Box, Stack, Text } from '@chakra-ui/react';-import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import '@xyflow/react/dist/style.css';import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@workbench/workflows/types';@@ -167,7 +167,7 @@ export const GraphPreviewFlow = ({graph: GraphContract;positionHints?: Record<string, XYPosition>;}) => {- const { themeId } = useWorkbenchPreferences();+ const themeId = useWorkbenchPreferenceSelector((preferences) => preferences.themeId);const backgroundId = useId().replace(/:/g, '');const nodes = useMemo(() => toPreviewNodes(graph, positionHints), [graph, positionHints]);const edges = useMemo(() => toPreviewEdges(graph), [graph]);diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.tsnew file mode 100644index 0000000000..fb48407956--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import type { RegisteredHotkey } from './types';++import { getHotkeyExecutionSource } from './WorkbenchHotkeyRuntime';++const source = { instanceId: 'alpha', projectId: 'project-1', region: 'right', typeId: 'test-widget' } as const;+const activeSource = { instanceId: 'beta', projectId: 'project-1', region: 'left', typeId: 'other-widget' } as const;++const createHotkey = (overrides: Partial<RegisteredHotkey>): RegisteredHotkey => ({+ category: 'app',+ commandId: 'test.command',+ defaultKeys: ['x'],+ id: 'test.hotkey',+ keys: ['x'],+ scope: { kind: 'global' },+ title: 'Test hotkey',+ ...overrides,+});++describe('getHotkeyExecutionSource', () => {+ it('does not let source-less global hotkeys execute against the focused widget source', () => {+ expect(getHotkeyExecutionSource(createHotkey({}), activeSource)).toBeNull();+ });++ it('uses the registering source for sourced global hotkeys', () => {+ expect(getHotkeyExecutionSource(createHotkey({ source }), activeSource)).toBe(source);+ });++ it('uses the focused source for widget-scoped hotkeys', () => {+ expect(+ getHotkeyExecutionSource(createHotkey({ scope: { kind: 'widget', typeId: 'test-widget' }, source }), activeSource)+ ).toBe(activeSource);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex 0719fb25f4..7739c2914a 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -1,8 +1,11 @@+import type { WidgetContributionSource } from '@workbench/types';+import { commandApi } from '@workbench/extensions/extensionApi';import { getFocusedRegionSnapshot } from '@workbench/focusRegions';-import { useWorkbenchPreferences } from '@workbench/settings/store';-import { useActiveProject } from '@workbench/WorkbenchContext';-import { useEffect, useEffectEvent, useMemo, useRef, useSyncExternalStore } from 'react';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useEffect, useEffectEvent, useMemo, useRef } from 'react';import { tinykeys } from 'tinykeys';import type { RegisteredHotkey } from './types';@@ -11,33 +14,33 @@ import { firstPartyHotkeyCatalog } from './catalog';import { useExtensionHotkeyDefinitions } from './extensionHotkeys';import { useRegisterFirstPartyCommands } from './firstPartyCommands';import { toTinykeysBinding } from './keys';-import { isHotkeyModalLayerActive, subscribeHotkeyModalLayers } from './modalLayer';+import { useIsHotkeyModalLayerActive } from './modalLayer';import { applyCustomHotkeys, resolveHotkey } from './resolve';import { getHotkeyTargetWidget } from './targetWidget';+export const getHotkeyExecutionSource = (+ hotkey: Pick<RegisteredHotkey, 'scope' | 'source'>,+ activeSource: WidgetContributionSource | null+): WidgetContributionSource | null => (hotkey.scope.kind === 'global' ? (hotkey.source ?? null) : activeSource);+export const WorkbenchHotkeyRuntime = () => {useRegisterFirstPartyCommands();- const preferences = useWorkbenchPreferences();- const project = useActiveProject();+ const customHotkeys = useWorkbenchPreferenceSelector((preferences) => preferences.customHotkeys);+ const project = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const extensionHotkeys = useExtensionHotkeyDefinitions();- const isModalLayerActive = useSyncExternalStore(- subscribeHotkeyModalLayers,- isHotkeyModalLayerActive,- isHotkeyModalLayerActive- );+ const isModalLayerActive = useIsHotkeyModalLayerActive();const projectRef = useRef(project);const registeredHotkeysRef = useRef<RegisteredHotkey[]>([]);projectRef.current = project;const registeredHotkeys = useMemo(() => {- const customHotkeys = preferences.customHotkeys;const firstPartyHotkeys = firstPartyHotkeyCatalog.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));const widgetHotkeys = extensionHotkeys.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));return [...firstPartyHotkeys, ...widgetHotkeys];- }, [extensionHotkeys, preferences.customHotkeys]);+ }, [customHotkeys, extensionHotkeys]);registeredHotkeysRef.current = registeredHotkeys;@@ -61,8 +64,8 @@ export const WorkbenchHotkeyRuntime = () => {return bindings;}, [registeredHotkeys]);- const executeHotkey = useEffectEvent((hotkey: RegisteredHotkey) => {- void commandApi.execute(hotkey.commandId);+ const executeHotkey = useEffectEvent((hotkey: RegisteredHotkey, source: WidgetContributionSource | null) => {+ void commandApi.executeForSource(hotkey.commandId, getHotkeyExecutionSource(hotkey, source));});const handleHotkey = useEffectEvent((event: KeyboardEvent, matchedKey: string) => {@@ -77,8 +80,23 @@ export const WorkbenchHotkeyRuntime = () => {const activeWidgetTypeId = activeInstanceId? (targetWidget?.typeId ?? projectRef.current.widgetInstances[activeInstanceId]?.typeId ?? null): null;+ const commandSource: WidgetContributionSource | null =+ activeInstanceId && activeWidgetTypeId && (targetWidget?.region || focusedRegion)+ ? {+ instanceId: activeInstanceId,+ projectId: projectRef.current.projectId ?? '',+ region: (targetWidget?.region ?? focusedRegion)!,+ typeId: activeWidgetTypeId,+ }+ : null;const hotkey = resolveHotkey({- context: { activeInstanceId, activeWidgetTypeId, focusedRegion, isModalLayerActive },+ context: {+ activeInstanceId,+ activeWidgetTypeId,+ focusedRegion,+ isModalLayerActive,+ projectId: projectRef.current.projectId ?? '',+ },event,hotkeys: registeredHotkeysRef.current,matchedKey,@@ -92,7 +110,7 @@ export const WorkbenchHotkeyRuntime = () => {event.preventDefault();}- executeHotkey(hotkey);+ executeHotkey(hotkey, commandSource);});useEffect(() => {diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsindex fe042d0207..5c5ebaf3e1 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -4,11 +4,12 @@ import { firstPartyHotkeyCatalog } from './catalog';describe('firstPartyHotkeyCatalog', () => {it('keeps legacy default hotkey parity', () => {- expect(firstPartyHotkeyCatalog).toHaveLength(90);+ expect(firstPartyHotkeyCatalog).toHaveLength(91);expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('canvas.mergeDown');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('workflows.copySelection');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.galleryNavLeft');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.remix');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('viewer.deleteImage');});});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex 91c75c89ca..08af2c39d0 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -46,6 +46,7 @@ const implemented = new Set(['gallery.selectAllOnPage','gallery.starImage','viewer.nextComparisonMode',+ 'viewer.deleteImage','viewer.recallAll','viewer.recallPrompts','viewer.recallSeed',@@ -169,6 +170,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('viewer', 'toggleViewer', ['z']),hotkey('viewer', 'swapImages', ['c']),hotkey('viewer', 'nextComparisonMode', ['m']),+ hotkey('viewer', 'deleteImage', ['delete', 'backspace']),hotkey('viewer', 'loadWorkflow', ['w']),hotkey('viewer', 'recallAll', ['a']),hotkey('viewer', 'recallSeed', ['s']),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.tsnew file mode 100644index 0000000000..badaa42210--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { toExtensionHotkeyDefinition } from './extensionHotkeys';++describe('toExtensionHotkeyDefinition', () => {+ it('preserves the registering widget source for command execution', () => {+ const source = { instanceId: 'alpha', projectId: 'project-1', region: 'right', typeId: 'test-widget' } as const;++ expect(+ toExtensionHotkeyDefinition({+ commandId: 'test.command',+ defaultKeys: ['mod+x'],+ id: 'test.hotkey',+ scope: 'global',+ source,+ title: 'Test hotkey',+ })+ ).toMatchObject({ source });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.tsindex 6341b68ffc..80e7ed5b44 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts@@ -1,7 +1,7 @@import type { WidgetHotkeyContribution, WidgetRegion, WorkbenchRegion } from '@workbench/types';import { extensionContributionStores } from '@workbench/extensions/extensionApi';-import { useEffect, useMemo, useState } from 'react';+import { useMemo } from 'react';import type { HotkeyDefinition } from './types';@@ -39,12 +39,7 @@ export const toExtensionHotkeyDefinition = (hotkey: WidgetHotkeyContribution): H};export const useExtensionHotkeyDefinitions = (): HotkeyDefinition[] => {- const [hotkeys, setHotkeys] = useState(() => extensionContributionStores.hotkeys.list());-- useEffect(- () => extensionContributionStores.hotkeys.subscribe(() => setHotkeys(extensionContributionStores.hotkeys.list())),- []- );+ const hotkeys = extensionContributionStores.hotkeys.useList();return useMemo(() => hotkeys.map(toExtensionHotkeyDefinition).filter((hotkey): hotkey is HotkeyDefinition => hotkey !== null),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex d38c97780e..2ae9bc9383 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -3,15 +3,16 @@ import { commandApi } from '@workbench/extensions/extensionApi';import { cancelCurrentQueueItem } from '@workbench/generation/api';import { executeImageRecall, getSelectedGalleryImage, type ImageRecallKind } from '@workbench/image-actions';import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';import { getWidgetsForRegion } from '@workbench/widgetRegistry';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';import { focusPositivePrompt } from '@workbench/widgets/generate/promptFields';import { adjustFocusedPromptAttention } from '@workbench/widgets/generate/promptFields/promptAttentionHotkeys';import { navigatePromptHistory } from '@workbench/widgets/generate/promptFields/promptHistoryNavigation';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { useEffect, useEffectEvent, useRef } from 'react';const imageRecallCommands: Record<string, ImageRecallKind> = {@@ -49,23 +50,33 @@ export const FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS = Object.keys(imageRecallCommaexport const FIRST_PARTY_COMMAND_IDS = [...FIRST_PARTY_APP_COMMAND_IDS, ...Object.keys(imageRecallCommands)] as const;export const useRegisterFirstPartyCommands = () => {- const project = useActiveProject();+ const store = useWorkbenchStore();const dispatch = useWorkbenchDispatch();- const { models, status: modelsStatus } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const availabilityModels = modelsStatus === 'loaded' ? models : undefined;- const projectRef = useRef(project);+ const projectRef = useRef(store.getSnapshot().activeProject);const modelsRef = useRef(availabilityModels);- useInvocationTemplatesSnapshot();+ useInvocationTemplatesSelector((snapshot) => snapshot.status);- projectRef.current = project;modelsRef.current = availabilityModels;+ useEffect(+ () =>+ store.subscribe(() => {+ projectRef.current = store.getSnapshot().activeProject;+ }),+ [store]+ );+useEffect(() => {ensureModelsLoaded();}, []);const submitInvocation = useEffectEvent(() => {+ flushGenerateDrafts();+const activeProject = projectRef.current;const resolvedRoute = resolveInvocationRoute(activeProject, 'global', activeProject.invocation, modelsRef.current);const { status } = getConnectionStatus();@@ -102,9 +113,10 @@ export const useRegisterFirstPartyCommands = () => {image,kind,models: modelsRef.current ?? [],+ projectId: activeProject.id,});- if (didRecall) {+ if (didRecall && store.getSnapshot().activeProject.id === activeProject.id) {openWidgetPlacement({dispatch,getWidgetsForRegion,@@ -191,24 +203,30 @@ export const useRegisterFirstPartyCommands = () => {title: 'Focus prompt',}),commandApi.register({- handler: () =>+ handler: () => {+ flushGenerateDrafts();+navigatePromptHistory({direction: -1,dispatch,models: modelsRef.current,project: projectRef.current,- }),+ });+ },id: 'app.promptHistoryPrev',title: 'Previous prompt history item',}),commandApi.register({- handler: () =>+ handler: () => {+ flushGenerateDrafts();+navigatePromptHistory({direction: 1,dispatch,models: modelsRef.current,project: projectRef.current,- }),+ });+ },id: 'app.promptHistoryNext',title: 'Next prompt history item',}),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.tsindex 9c03a50180..600bde0bd7 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts@@ -1,18 +1,19 @@-import { createListenerChannel } from '@workbench/externalStore';+import { createExternalStore } from '@workbench/externalStore';-const channel = createListenerChannel();-const activeLayerIds = new Set<string>();+const store = createExternalStore<{ activeLayerIds: ReadonlySet<string> }>({ activeLayerIds: new Set<string>() });export const registerHotkeyModalLayer = (id: string): (() => void) => {- activeLayerIds.add(id);- channel.notify();+ store.patchSnapshot({ activeLayerIds: new Set([...store.getSnapshot().activeLayerIds, id]) });return () => {+ const activeLayerIds = new Set(store.getSnapshot().activeLayerIds);+activeLayerIds.delete(id);- channel.notify();+ store.patchSnapshot({ activeLayerIds });};};-export const isHotkeyModalLayerActive = (): boolean => activeLayerIds.size > 0;+export const isHotkeyModalLayerActive = (): boolean => store.getSnapshot().activeLayerIds.size > 0;-export const subscribeHotkeyModalLayers = channel.subscribe;+export const useIsHotkeyModalLayerActive = (): boolean =>+ store.useSelector((snapshot) => snapshot.activeLayerIds.size > 0);diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.tsindex 73a51ad66c..b01b4a9ba0 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts@@ -10,6 +10,7 @@ const context = {activeWidgetTypeId: null,focusedRegion: null,isModalLayerActive: false,+ projectId: 'project-1',} as const;const base = {@@ -122,6 +123,26 @@ describe('resolveHotkey', () => {).toBe('focused');});+ it('does not resolve hotkeys contributed by another project source', () => {+ const staleProjectHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'stale',+ id: 'stale',+ scope: { kind: 'widget', typeId: 'gallery' },+ source: { instanceId: 'gallery-1', projectId: 'project-2', region: 'left', typeId: 'gallery' },+ title: 'Stale project',+ };++ expect(+ resolveHotkey({+ context: { ...context, activeInstanceId: 'gallery-1', activeWidgetTypeId: 'gallery', focusedRegion: 'left' },+ event,+ hotkeys: [staleProjectHotkey],+ matchedKey: 'x',+ })+ ).toBeNull();+ });+it('suppresses editable targets unless allowed', () => {class FakeHTMLElement {closest(): FakeHTMLElement {diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.tsindex ae8dfcab38..c939525477 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts@@ -5,6 +5,10 @@ import { isEditableHotkeyTarget, normalizeHotkeyString } from './keys';const getScopePriority = (hotkey: RegisteredHotkey, context: HotkeyContext): number => {const { scope } = hotkey;+ if (hotkey.source && hotkey.source.projectId !== context.projectId) {+ return -1;+ }+if (scope.kind === 'instance') {return scope.instanceId === context.activeInstanceId ? 400 : -1;}diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.tsindex 4b419267d0..a4b245fe7a 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts@@ -26,10 +26,11 @@ describe('getHotkeyTargetWidget', () => {getHotkeyTargetWidget(new FakeElement({'data-hotkey-widget-instance-id': 'preview',+ 'data-hotkey-widget-region': 'center','data-hotkey-widget-type-id': 'preview',}) as unknown as EventTarget)- ).toEqual({ instanceId: 'preview', typeId: 'preview' });+ ).toEqual({ instanceId: 'preview', region: 'center', typeId: 'preview' });});it('ignores targets outside widget shells', () => {diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.tsindex ba08f7550f..ce201e64ba 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts@@ -1,15 +1,18 @@-import type { WidgetInstanceId, WidgetTypeId } from '@workbench/types';+import type { WidgetInstanceId, WidgetTypeId, WorkbenchRegion } from '@workbench/types';export const getHotkeyTargetWidget = (target: EventTarget | null-): { instanceId: WidgetInstanceId; typeId: WidgetTypeId } | null => {+): { instanceId: WidgetInstanceId; region: WorkbenchRegion | null; typeId: WidgetTypeId } | null => {if (!(target instanceof Element)) {return null;}const widgetElement = target.closest('[data-hotkey-widget-instance-id][data-hotkey-widget-type-id]');const instanceId = widgetElement?.getAttribute('data-hotkey-widget-instance-id');+ const region = widgetElement?.getAttribute('data-hotkey-widget-region') ?? null;const typeId = widgetElement?.getAttribute('data-hotkey-widget-type-id');- return instanceId && typeId ? { instanceId, typeId: typeId as WidgetTypeId } : null;+ return instanceId && typeId+ ? { instanceId, region: region as WorkbenchRegion | null, typeId: typeId as WidgetTypeId }+ : null;};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.tsindex 26723f7028..3a586c98e2 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts@@ -1,4 +1,4 @@-import type { WidgetInstanceId, WidgetRegion, WidgetTypeId } from '@workbench/types';+import type { WidgetContributionSource, WidgetInstanceId, WidgetRegion, WidgetTypeId } from '@workbench/types';export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'viewer' | 'workflows';@@ -21,6 +21,7 @@ export interface HotkeyDefinition {allowInModal?: boolean;unavailableReason?: string;implemented?: boolean;+ source?: WidgetContributionSource;}export interface RegisteredHotkey extends HotkeyDefinition {@@ -32,6 +33,7 @@ export interface HotkeyContext {activeInstanceId: WidgetInstanceId | null;activeWidgetTypeId: WidgetTypeId | null;isModalLayerActive: boolean;+ projectId: string;}export type CustomHotkeys = Record<string, string[]>;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex 9a485d6aa0..d33146f69f 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -2,7 +2,7 @@ import type { GalleryBoard, GalleryImage } from '@workbench/gallery/api';import { Dialog, HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';import { Button, MenuContent, Tooltip } from '@workbench/components/ui';-import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import {AsteriskIcon,ChevronRightIcon,@@ -120,7 +120,7 @@ const ImageContextMenuContent = ({target: ImageContextMenuTarget;onClose: () => void;}) => {- const { confirmImageDeletion } = useWorkbenchPreferences();+ const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);const [pendingDeletion, setPendingDeletion] = useState<string[] | null>(null);const [recallCapabilities, setRecallCapabilities] = useState<ImageRecallCapabilities>(EMPTY_IMAGE_RECALL_CAPABILITIESdiff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex de0b599671..5be89556b7 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -54,11 +54,13 @@ describe('executeImageRecall', () => {image,kind: 'remix',models: [model],+ projectId: 'project-1',})).resolves.toBe(true);expect(galleryApi.getGalleryImageMetadata).toHaveBeenCalledWith('selected.png');expect(dispatch).toHaveBeenCalledWith({+ projectId: 'project-1',type: 'setGenerateSettings',values: expect.objectContaining({ positivePrompt: 'recalled prompt' }),});@@ -66,4 +68,26 @@ describe('executeImageRecall', () => {expect.objectContaining({ kind: 'success', title: 'Recalled remix settings', type: 'recordNotice' }));});++ it('uses the freshest Generate values when recalling image dimensions', async () => {+ const dispatch = vi.fn();++ await expect(+ executeImageRecall({+ dispatch,+ generateValues: { modelKey: model.key, positivePrompt: 'stale prompt' },+ getGenerateValues: () => ({ modelKey: model.key, positivePrompt: 'fresh prompt' }),+ image,+ kind: 'dimensions',+ models: [model],+ projectId: 'project-1',+ })+ ).resolves.toBe(true);++ expect(dispatch).toHaveBeenCalledWith({+ projectId: 'project-1',+ type: 'setGenerateSettings',+ values: expect.objectContaining({ positivePrompt: 'fresh prompt', height: image.height, width: image.width }),+ });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex 545c118e05..9773e22948 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -1,5 +1,5 @@import type { GalleryImage } from '@workbench/gallery/api';-import type { GenerateModelConfig, VaeModelConfig } from '@workbench/generation/types';+import type { GenerateModelConfig, GenerateWidgetValues, VaeModelConfig } from '@workbench/generation/types';import type { ModelConfig } from '@workbench/models/types';import type { WorkbenchAction } from '@workbench/workbenchState';import type { Dispatch } from 'react';@@ -52,25 +52,39 @@ export const getCurrentGenerateValues = ({const fallbackModelKey = typeof generateValues.modelKey === 'string' ? generateValues.modelKey : null;const fallbackModel = supportedModels.find((model) => model.key === fallbackModelKey) ?? supportedModels[0];- return fallbackModel ? { ...getDefaultGenerateSettings(fallbackModel), model: fallbackModel } : null;+ return fallbackModel+ ? ({+ ...getDefaultGenerateSettings(fallbackModel),+ ...generateValues,+ model: fallbackModel,+ modelKey: fallbackModel.key,+ } as GenerateWidgetValues)+ : null;};export const executeImageRecall = async ({dispatch,generateValues,+ getGenerateValues,image,kind,models,+ projectId,}: {dispatch: Dispatch<WorkbenchAction>;generateValues: Record<string, unknown>;+ getGenerateValues?: () => Record<string, unknown>;image: GalleryImage;kind: ImageRecallKind;models: ModelConfig[];+ projectId?: string;}): Promise<boolean> => {const supportedModels = models.filter(isSupportedGenerateModel);const vaeModels = models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig);- const currentGenerateValues = getCurrentGenerateValues({ generateValues, supportedModels });+ const currentGenerateValues = getCurrentGenerateValues({+ generateValues: getGenerateValues?.() ?? generateValues,+ supportedModels,+ });try {if (!currentGenerateValues) {@@ -104,7 +118,7 @@ export const executeImageRecall = async ({return false;}- dispatch({ type: 'setGenerateSettings', values: result.values });+ dispatch({ projectId, type: 'setGenerateSettings', values: result.values });dispatch({kind: 'success',message: getImageRecallMessage(result.fields),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex ba4f38a5f1..eb9b1ca838 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -14,8 +14,10 @@ import {} from '@workbench/gallery/api';import { isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';import { isVaeModelConfig } from '@workbench/generation/settings';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useWorkbenchStore } from '@workbench/WorkbenchContext';import { useEffect, useMemo, type Dispatch } from 'react';import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';@@ -78,17 +80,20 @@ export const useImageActions = ({generateValues,onImagesDeleted,onStarredChange,+ projectId,}: {boards: GalleryBoard[];dispatch: Dispatch<WorkbenchAction>;generateValues: Record<string, unknown>;+ projectId?: string;/** Called after a successful deletion so the host can select a neighboring image. */onImagesDeleted?: (imageNames: string[]) => void;/** Optional optimistic hook, called before the request and re-called inverted on failure. */onStarredChange?: (imageNames: string[], starred: boolean) => void;}): ImageActions => {const openWorkbenchWidget = useOpenWorkbenchWidget();- const { models } = useModelsSnapshot();+ const store = useWorkbenchStore();+ const models = useModelsSelector((snapshot) => snapshot.models);const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);const vaeModels = useMemo(() => models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig), [models]);const currentGenerateValues = useMemo(() => {@@ -103,9 +108,18 @@ export const useImageActions = ({const recordError = (error: unknown) => dispatch({ message: toErrorMessage(error), type: 'recordError' });const recordSuccess = (title: string, message?: string) =>dispatch({ kind: 'success', message, title, type: 'recordNotice' });- const refreshGallery = () => dispatch({ type: 'touchGalleryRefresh' });- const refreshGalleryImages = () => dispatch({ type: 'touchGalleryImagesRefresh' });+ const refreshGallery = () => dispatch({ projectId, type: 'touchGalleryRefresh' });+ const refreshGalleryImages = () => dispatch({ projectId, type: 'touchGalleryImagesRefresh' });const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';+ const getLatestGenerateValues = () => {+ const snapshot = store.getSnapshot();+ const project = projectId+ ? snapshot.state.projects.find((candidate) => candidate.id === projectId)+ : snapshot.activeProject;++ return project ? getProjectWidgetValues(project, 'generate') : {};+ };+return {copyImage: async (image) => {try {@@ -121,7 +135,7 @@ export const useImageActions = ({deleteImages: async (imageNames) => {try {await deleteGalleryImages(imageNames);- dispatch({ imageNames, type: 'removeGalleryImages' });+ dispatch({ imageNames, projectId, type: 'removeGalleryImages' });onImagesDeleted?.(imageNames);recordSuccess(imageNames.length === 1 ? 'Deleted image' : `Deleted ${imageNames.length} images`);refreshGallery();@@ -203,18 +217,26 @@ export const useImageActions = ({}},openImageInPreview: (image) => {- dispatch({ image, type: 'selectGalleryImage' });+ dispatch({ image, projectId, type: 'selectGalleryImage' });openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });},recallImageData: async (image, kind) => {- const didRecall = await executeImageRecall({ dispatch, generateValues, image, kind, models });+ const didRecall = await executeImageRecall({+ dispatch,+ generateValues,+ getGenerateValues: getLatestGenerateValues,+ image,+ kind,+ models,+ projectId,+ });- if (didRecall) {+ if (didRecall && (!projectId || store.getSnapshot().activeProject.id === projectId)) {openWorkbenchWidget('generate', { preferredRegions: ['left'] });}},selectForCompare: (image) => {- dispatch({ image, type: 'setGalleryCompareImage' });+ dispatch({ image, projectId, type: 'setGalleryCompareImage' });},setImagesStarred: async (imageNames, starred) => {onStarredChange?.(imageNames, starred);@@ -237,6 +259,8 @@ export const useImageActions = ({onImagesDeleted,onStarredChange,openWorkbenchWidget,+ projectId,+ store,supportedModels,vaeModels,]);diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex a11ec33124..34476c7ed1 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -8,6 +8,7 @@ import type {ResultDestination,WidgetId,} from './types';+import type { ProjectGraphState } from './workflows/types';import {getGenerationModelAvailabilityReasons,@@ -16,6 +17,7 @@ import {} from './generation/baseGenerationPolicies';import { normalizeGenerateWidgetValues } from './generation/settings';import { getProjectWidgetValues } from './widgetState';+import { areArraysEqual, createStableSelector } from './workbenchSelectors';import { getProjectGraphReadiness } from './workflows/buildGraph';import { getInvocationTemplatesSnapshot } from './workflows/templates';@@ -79,13 +81,56 @@ const sourceWidgetIds: Partial<Record<InvocationSourceId, WidgetId>> = {'project-graph': 'workflow',};-const isWidgetMounted = (project: Project, widgetId: WidgetId): boolean =>- Object.values(project.widgetRegions).some((region) =>- region.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === widgetId)- );+export interface InvocationRouteInput {+ generateValues: Record<string, unknown>;+ invocation: InvocationRoute;+ mountedWidgetIds: readonly WidgetId[];+ projectGraph: ProjectGraphState;+ projectId: string;+}++const getMountedWidgetIds = (project: Project): WidgetId[] => {+ const mountedWidgetIds = new Set<WidgetId>();++ for (const region of Object.values(project.widgetRegions)) {+ for (const instanceId of region.instanceIds) {+ const widgetId = project.widgetInstances[instanceId]?.typeId;-const getGenerateSnapshotValidationReasons = (project: Project, models?: readonly ModelConfig[]): string[] => {- const values = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));+ if (widgetId) {+ mountedWidgetIds.add(widgetId);+ }+ }+ }++ return Array.from(mountedWidgetIds).sort();+};++export const getInvocationRouteInput = (project: Project): InvocationRouteInput => ({+ generateValues: getProjectWidgetValues(project, 'generate'),+ invocation: project.invocation,+ mountedWidgetIds: getMountedWidgetIds(project),+ projectGraph: project.projectGraph,+ projectId: project.id,+});++export const areInvocationRouteInputsEqual = (left: InvocationRouteInput, right: InvocationRouteInput): boolean =>+ left.projectId === right.projectId &&+ left.invocation === right.invocation &&+ left.projectGraph === right.projectGraph &&+ left.generateValues === right.generateValues &&+ areArraysEqual(left.mountedWidgetIds, right.mountedWidgetIds);++export const createInvocationRouteInputSelector = () =>+ createStableSelector(getInvocationRouteInput, areInvocationRouteInputsEqual);++const isWidgetMounted = (input: InvocationRouteInput, widgetId: WidgetId): boolean =>+ input.mountedWidgetIds.includes(widgetId);++const getGenerateSnapshotValidationReasons = (+ generateValues: Record<string, unknown>,+ models?: readonly ModelConfig[]+): string[] => {+ const values = normalizeGenerateWidgetValues(generateValues);if (!values || !isSupportedGenerateModel(values.model)) {return ['Generate needs a supported model before it can be invoked.'];@@ -105,6 +150,13 @@ export const resolveInvocationRoute = (mode: InvocationMode = 'global',route: InvocationRoute = project.invocation,models?: readonly ModelConfig[]+): ResolvedInvocationRoute => resolveInvocationRouteInput(getInvocationRouteInput(project), mode, route, models);++export const resolveInvocationRouteInput = (+ input: InvocationRouteInput,+ mode: InvocationMode = 'global',+ route: InvocationRoute = input.invocation,+ models?: readonly ModelConfig[]): ResolvedInvocationRoute => {const sourceId = route.sourceId;const destination = route.destination;@@ -114,18 +166,18 @@ export const resolveInvocationRoute = (// templates store so the result stays live.const projectGraphReadiness =sourceId === 'project-graph'- ? getProjectGraphReadiness(project.projectGraph, getInvocationTemplatesSnapshot())+ ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot()): null;const validationReasons: string[] = [];if (!isInvocationSourceAvailable(sourceId)) {validationReasons.push(`${getSourceLabel(sourceId)} is not an available invocation source.`);- } else if (sourceWidgetId && !isWidgetMounted(project, sourceWidgetId)) {+ } else if (sourceWidgetId && !isWidgetMounted(input, sourceWidgetId)) {validationReasons.push(`The ${getSourceLabel(sourceId)} widget is not mounted in this project.`);}if (sourceId === 'generate') {- validationReasons.push(...getGenerateSnapshotValidationReasons(project, models));+ validationReasons.push(...getGenerateSnapshotValidationReasons(input.generateValues, models));}if (projectGraphReadiness && !projectGraphReadiness.canInvoke) {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsxindex 95c302061f..5d35c8f4ce 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx@@ -2,7 +2,7 @@ import type { BackendConnectionStatus } from '@workbench/types';import { Box, Flex, HStack, Text } from '@chakra-ui/react';import { AccountMenu } from '@workbench/auth/components/AccountMenu';-import { useConnectionStatus } from '@workbench/backend/connectionStore';+import { useConnectionStatusSelector } from '@workbench/backend/connectionStore';import { InvokeMark } from '@workbench/components/InvokeMark';import { SettingsButton } from '@workbench/settings/SettingsDialog';@@ -13,7 +13,7 @@ const CONNECTION_LABEL: Record<Exclude<BackendConnectionStatus, 'connected'>, st/** Subtle backend-connection indicator; hidden while the socket is healthy. */const ConnectionChip = () => {- const { status } = useConnectionStatus();+ const status = useConnectionStatusSelector((snapshot) => snapshot.status);if (status === 'connected') {return null;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsxindex dbd2aadc1e..42dd5cb955 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/ProjectsGrid.tsx@@ -1,6 +1,6 @@import { Alert, SimpleGrid, Skeleton, Stack } from '@chakra-ui/react';import { Button } from '@workbench/components/ui';-import { refreshProjectLibrary, useProjectLibrary } from '@workbench/projects/library';+import { refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';import { NewProjectCard } from './NewProjectCard';import { ProjectCard } from './ProjectCard';@@ -11,16 +11,18 @@ import { ProjectCard } from './ProjectCard';* leads, so an empty library still presents the next step.*/export const ProjectsGrid = () => {- const library = useProjectLibrary();- const isFirstLoad = library.summaries.length === 0 && (library.status === 'idle' || library.status === 'loading');+ const error = useProjectLibrarySelector((snapshot) => snapshot.error);+ const status = useProjectLibrarySelector((snapshot) => snapshot.status);+ const summaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);+ const isFirstLoad = summaries.length === 0 && (status === 'idle' || status === 'loading');return (<Stack gap="3">- {library.status === 'error' ? (+ {status === 'error' ? (<Alert.Root borderRadius="md" size="sm" status="error"><Alert.Indicator /><Alert.Title flex="1" fontSize="xs">- {library.error ?? 'Failed to load your projects.'}+ {error ?? 'Failed to load your projects.'}</Alert.Title><Button size="2xs" variant="outline" onClick={() => void refreshProjectLibrary()}>Retry@@ -31,7 +33,7 @@ export const ProjectsGrid = () => {<NewProjectCard />{isFirstLoad? Array.from({ length: 3 }, (_value, index) => <Skeleton key={index} minH="40" rounded="lg" />)- : library.summaries.map((summary) => <ProjectCard key={summary.id} summary={summary} />)}+ : summaries.map((summary) => <ProjectCard key={summary.id} summary={summary} />)}</SimpleGrid></Stack>);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsxindex 355db4f502..6daf24bdc7 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/add-models/AddModelsView.tsx@@ -6,8 +6,8 @@ import { Button, Scrollable, Tooltip } from '@workbench/components/ui';import { getExternalProviderConfigs, getHuggingFaceModels, scanFolderForModels } from '@workbench/models/api';import { getModelBaseLabel } from '@workbench/models/baseIdentity';import { collectBases, collectTypes } from '@workbench/models/library';-import { ensureStartersLoaded, useStartersSnapshot } from '@workbench/models/startersStore';-import { updateModelsUi, useModelsUi } from '@workbench/models/uiStore';+import { ensureStartersLoaded, useStartersSelector } from '@workbench/models/startersStore';+import { updateModelsUi, useModelsUiSelector } from '@workbench/models/uiStore';import { useNotify } from '@workbench/useNotify';import { DownloadIcon, FileIcon, FolderIcon, FolderSearchIcon, LinkIcon, SearchIcon } from 'lucide-react';import { useDeferredValue, useEffect, useMemo, useState } from 'react';@@ -55,8 +55,13 @@ const compareStarterModels = (a: IndexedStarterModel, b: IndexedStarterModel, fiexport const AddModelsView = () => {const notify = useNotify();const { install, pendingSources } = useInstallActions();- const { error: loadError, response, status } = useStartersSnapshot();- const { hfLookup, scan } = useModelsUi();+ const loadError = useStartersSelector((snapshot) => snapshot.error);+ const response = useStartersSelector((snapshot) => snapshot.response);+ const status = useStartersSelector((snapshot) => snapshot.status);+ const { hfLookup, scan } = useModelsUiSelector(+ (snapshot) => ({ hfLookup: snapshot.hfLookup, scan: snapshot.scan }),+ (left, right) => left.hfLookup === right.hfLookup && left.scan === right.scan+ );const [query, setQuery] = useState('');const [accessToken, setAccessToken] = useState('');diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsxindex 7ca092823e..166f1448a9 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/DefaultSettingsSection.tsx@@ -65,7 +65,15 @@ const PREPROCESSORS = ['tile',];-export const supportsDefaultSettings = (model: ModelConfig): boolean =>+type DefaultSettingsModel = Pick<ModelConfig, 'default_settings' | 'key' | 'type'>;++interface DefaultSettingsDraft {+ modelKey: string;+ settings: AnyModelDefaultSettings;+ source: AnyModelDefaultSettings | null | undefined;+}++export const supportsDefaultSettings = (model: Pick<ModelConfig, 'type'>): boolean =>model.type === 'main' || model.type === 'lora' || CONTROL_ADAPTER_TYPES.has(model.type);interface FieldSpec {@@ -213,7 +221,7 @@ const CONTROL_ADAPTER_FIELDS: FieldSpec[] = [},];-const getFieldsForModel = (model: ModelConfig): FieldSpec[] => {+const getFieldsForModel = (model: Pick<ModelConfig, 'type'>): FieldSpec[] => {if (model.type === 'main') {return MAIN_FIELDS;}@@ -225,7 +233,7 @@ const getFieldsForModel = (model: ModelConfig): FieldSpec[] => {return CONTROL_ADAPTER_FIELDS;};-const validateDefaults = (model: ModelConfig, settings: AnyModelDefaultSettings): string | null => {+const validateDefaults = (model: Pick<ModelConfig, 'type'>, settings: AnyModelDefaultSettings): string | null => {if (model.type === 'main') {const result = mainDefaultSettingsSchema.safeParse({cfgRescaleMultiplier: settings.cfg_rescale_multiplier ?? null,@@ -255,14 +263,23 @@ export const DefaultSettingsSection = ({onError,onSaved,}: {- model: ModelConfig;+ model: DefaultSettingsModel;onError: (message: string) => void;onSaved: () => void;}) => {const fields = useMemo(() => getFieldsForModel(model), [model]);- const [settings, setSettings] = useState<AnyModelDefaultSettings>(() => ({ ...model.default_settings }));+ const [draft, setDraft] = useState<DefaultSettingsDraft>(() => ({+ modelKey: model.key,+ settings: { ...model.default_settings },+ source: model.default_settings,+ }));const [error, setError] = useState<string | null>(null);const [isSaving, setIsSaving] = useState(false);+ const isDraftCurrent = draft.modelKey === model.key && draft.source === model.default_settings;+ const savedSettingsDraft = useMemo(() => ({ ...model.default_settings }), [model.default_settings]);+ const settings = isDraftCurrent ? draft.settings : savedSettingsDraft;+ const visibleError = isDraftCurrent ? error : null;+ const visibleIsSaving = isDraftCurrent ? isSaving : false;const isDirty = useMemo(() => {const saved = model.default_settings ?? {};@@ -271,7 +288,11 @@ export const DefaultSettingsSection = ({}, [fields, model.default_settings, settings]);const setFieldValue = (key: keyof AnyModelDefaultSettings, value: unknown) => {- setSettings((current) => ({ ...current, [key]: value as never }));+ setDraft({+ modelKey: model.key,+ settings: { ...settings, [key]: value as never },+ source: model.default_settings,+ });setError(null);};@@ -304,13 +325,19 @@ export const DefaultSettingsSection = ({Applied automatically when this model is selected. Off = use the app default.</Text></Stack>- <Button disabled={!isDirty} loading={isSaving} size="xs" variant="solid" onClick={() => void handleSave()}>+ <Button+ disabled={!isDirty}+ loading={visibleIsSaving}+ size="xs"+ variant="solid"+ onClick={() => void handleSave()}+ >Save Defaults</Button></HStack>- {error ? (+ {visibleError ? (<Text color="fg.error" fontSize="2xs" role="alert">- {error}+ {visibleError}</Text>) : null}<Grid gap="2.5" templateColumns="repeat(auto-fill, minmax(13rem, 1fr))">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsxindex 1343c6c339..90b87e29d3 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelDetail.tsx@@ -1,25 +1,95 @@-import type { ModelConfig } from '@workbench/models/types';+import type { AnyModelDefaultSettings, ModelConfig, ModelTaxonomyType } from '@workbench/models/types';import { DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';import { Button, IconButton, ConfirmDialog, MenuContent } from '@workbench/components/ui';import { isConvertibleToDiffusers } from '@workbench/models/baseIdentity';-import { useModelsSnapshot } from '@workbench/models/modelsStore';+import { useModelsSelector } from '@workbench/models/modelsStore';import { formatBytes } from '@workbench/models/taxonomy';import { useNotify } from '@workbench/useNotify';+import { areArraysEqual } from '@workbench/workbenchSelectors';import { ArrowLeftIcon, MoreHorizontalIcon, PencilIcon, RefreshCcwIcon, Trash2Icon } from 'lucide-react';-import { useCallback, useState } from 'react';+import { memo, useCallback, useState } from 'react';import { SiHuggingface } from 'react-icons/si';import { DefaultSettingsSection, supportsDefaultSettings } from './DefaultSettingsSection';-import { MissingFileBadge, ModelBadgeRow } from './ModelBadges';+import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from './ModelBadges';import { ModelEditForm } from './ModelEditForm';import { ModelImageUpload } from './ModelImageUpload';import { RelatedModelsSection } from './RelatedModelsSection';-import { TriggerPhrasesEditor } from './TriggerPhrasesEditor';+import { MemoizedTriggerPhrasesEditor } from './TriggerPhrasesEditor';import { useModelActions } from './useModelActions';const TRIGGER_PHRASE_TYPES = new Set(['main', 'lora', 'embedding']);const RELATED_MODEL_TYPES = new Set(['main', 'lora']);+const EMPTY_TRIGGER_PHRASES: readonly string[] = [];++type ModelDetailShellModel = Pick<ModelConfig, 'key' | 'type'>;+type DefaultSettingsModel = { default_settings?: AnyModelDefaultSettings | null; key: string; type: ModelTaxonomyType };+type TriggerPhrasesModel = Pick<ModelConfig, 'key' | 'trigger_phrases'>;+type ModelIdentityModel = Pick<+ ModelConfig,+ | 'base'+ | 'cover_image'+ | 'description'+ | 'file_size'+ | 'format'+ | 'hash'+ | 'key'+ | 'name'+ | 'path'+ | 'prediction_type'+ | 'source'+ | 'source_url'+ | 'type'+ | 'variant'+>;++const findModel = (models: readonly ModelConfig[], modelKey: string): ModelConfig | undefined =>+ models.find((candidate) => candidate.key === modelKey);++const selectModelShell = (models: readonly ModelConfig[], modelKey: string): ModelDetailShellModel | null => {+ const model = findModel(models, modelKey);++ return model ? { key: model.key, type: model.type } : null;+};++const selectModelIdentity = (models: readonly ModelConfig[], modelKey: string): ModelIdentityModel | null => {+ const model = findModel(models, modelKey);++ return model+ ? {+ base: model.base,+ cover_image: model.cover_image,+ description: model.description,+ file_size: model.file_size,+ format: model.format,+ hash: model.hash,+ key: model.key,+ name: model.name,+ path: model.path,+ prediction_type: model.prediction_type,+ source: model.source,+ source_url: model.source_url,+ type: model.type,+ variant: model.variant,+ }+ : null;+};++const selectDefaultSettingsModel = (models: readonly ModelConfig[], modelKey: string): DefaultSettingsModel | null => {+ const model = findModel(models, modelKey);++ return model ? { default_settings: model.default_settings, key: model.key, type: model.type } : null;+};++const selectTriggerPhrasesModel = (models: readonly ModelConfig[], modelKey: string): TriggerPhrasesModel | null => {+ const model = findModel(models, modelKey);++ return model ? { key: model.key, trigger_phrases: model.trigger_phrases } : null;+};++const areTriggerPhrasesModelsEqual = (left: TriggerPhrasesModel | null, right: TriggerPhrasesModel | null): boolean =>+ left?.key === right?.key && areArraysEqual(left?.trigger_phrases ?? [], right?.trigger_phrases ?? []);/*** Full detail pane for one model: identity (view/edit), per-model default@@ -38,20 +108,7 @@ export const ModelDetail = ({onBack?: () => void;onDeleted: () => void;}) => {- const notify = useNotify();- const { missingModelKeys, models } = useModelsSnapshot();- const { convert, reidentify, remove } = useModelActions();- const model = models.find((candidate) => candidate.key === modelKey);- const [isEditing, setIsEditing] = useState(false);- const [pendingAction, setPendingAction] = useState<'delete' | 'convert' | null>(null);- const [isActionBusy, setIsActionBusy] = useState(false);-- const handleSectionError = useCallback(- (message: string) => {- notify.error('Model manager', message);- },- [notify]- );+ const model = useModelsSelector((snapshot) => selectModelShell(snapshot.models, modelKey));if (!model) {return (@@ -64,22 +121,77 @@ export const ModelDetail = ({);}- const handleReidentify = async () => {- setIsActionBusy(true);-- try {- await reidentify(model);- } finally {- setIsActionBusy(false);- }- };-return (<Stack gap={density === 'panel' ? '3' : '4'} pb="4">{onBack ? <BackButton onBack={onBack} /> : null}+ <ModelIdentitySectionContainer density={density} modelKey={model.key} onDeleted={onDeleted} />++ {supportsDefaultSettings(model) ? (+ <>+ <Separator borderColor="border.subtle" />+ <DefaultSettingsSectionContainer modelKey={model.key} />+ </>+ ) : null}++ {RELATED_MODEL_TYPES.has(model.type) ? (+ <>+ <Separator borderColor="border.subtle" />+ <RelatedModelsSectionContainer modelKey={model.key} />+ </>+ ) : null}++ {TRIGGER_PHRASE_TYPES.has(model.type) ? (+ <>+ <Separator borderColor="border.subtle" />+ <TriggerPhrasesEditorContainer modelKey={model.key} />+ </>+ ) : null}+ </Stack>+ );+};++interface ModelIdentitySectionProps {+ density: 'panel' | 'full';+ isMissing: boolean;+ model: ModelIdentityModel;+ onDeleted: () => void;+}++const ModelIdentitySectionContainer = memo(function ModelIdentitySectionContainer({+ density,+ modelKey,+ onDeleted,+}: {+ density: 'panel' | 'full';+ modelKey: string;+ onDeleted: () => void;+}) {+ const model = useModelsSelector((snapshot) => selectModelIdentity(snapshot.models, modelKey));+ const isMissing = useModelsSelector((snapshot) => snapshot.missingModelKeys.has(modelKey));++ if (!model) {+ return null;+ }++ return <ModelIdentitySection density={density} isMissing={isMissing} model={model} onDeleted={onDeleted} />;+});++const ModelIdentitySection = memo(function ModelIdentitySection({+ density,+ isMissing,+ model,+ onDeleted,+}: ModelIdentitySectionProps) {+ const notify = useNotify();+ const [editingModelKey, setEditingModelKey] = useState<string | null>(null);+ const isEditing = editingModelKey === model.key;++ return (+ <><HStack align="start" gap="3"><ModelImageUpload+ key={model.key}model={model}onError={(message) => notify.error('Model image', message)}onUpdated={() => notify.success('Model image updated')}@@ -88,8 +200,11 @@ export const ModelDetail = ({<Text fontSize="sm" fontWeight="700" lineClamp={2}>{model.name}</Text>- <ModelBadgeRow model={model} />- {missingModelKeys.has(model.key) ? (+ <HStack gap="1" minW="0" wrap="wrap">+ <ModelBaseBadge base={model.base} />+ <ModelFormatBadge format={model.format} />+ </HStack>+ {isMissing ? (<HStack gap="1.5"><MissingFileBadge /><Text color="fg.subtle" fontSize="2xs">@@ -103,84 +218,89 @@ export const ModelDetail = ({</Text>) : null}</Stack>- <HStack flexShrink={0} gap="1" wrap="wrap">- {isConvertibleToDiffusers(model) ? (- <Button size="xs" variant="outline" onClick={() => setPendingAction('convert')}>- <Icon as={SiHuggingface} boxSize="3" />- Convert to Diffusers- </Button>- ) : null}- <Button- size="xs"- variant={isEditing ? 'solid' : 'outline'}- onClick={() => setIsEditing((editing) => !editing)}- >- <Icon as={PencilIcon} boxSize="3" />- {isEditing ? 'Editing' : 'Edit'}- </Button>- <Menu.Root positioning={{ placement: 'bottom-end' }}>- <Menu.Trigger asChild>- <IconButton aria-label="Model actions" loading={isActionBusy} size="xs" variant="ghost">- <Icon as={MoreHorizontalIcon} boxSize="4" />- </IconButton>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="12rem">- <Menu.Item value="reidentify" onClick={() => void handleReidentify()}>- <Icon as={RefreshCcwIcon} boxSize="3.5" />- <Menu.ItemText fontSize="xs">Re-identify model</Menu.ItemText>- </Menu.Item>- <Menu.Separator />- <Menu.Item color="fg.error" value="delete" onClick={() => setPendingAction('delete')}>- <Icon as={Trash2Icon} boxSize="3.5" />- <Menu.ItemText fontSize="xs">Delete model</Menu.ItemText>- </Menu.Item>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- </HStack>+ <ModelDetailActions+ isEditing={isEditing}+ model={model}+ onDeleted={onDeleted}+ onToggleEditing={() => setEditingModelKey((key) => (key === model.key ? null : model.key))}+ /></HStack>{isEditing ? (<ModelEditFormmodel={model}- onCancel={() => setIsEditing(false)}+ onCancel={() => setEditingModelKey(null)}onSaved={() => {- setIsEditing(false);+ setEditingModelKey(null);notify.success('Model updated', model.name);}}/>) : (<ModelAttributes density={density} model={model} />)}+ </>+ );+});- {supportsDefaultSettings(model) ? (- <>- <Separator borderColor="border.subtle" />- <DefaultSettingsSection- model={model}- onError={(message) => notify.error('Default settings', message)}- onSaved={() => notify.success('Default settings saved', model.name)}- />- </>- ) : null}+const ModelDetailActions = ({+ isEditing,+ model,+ onDeleted,+ onToggleEditing,+}: {+ isEditing: boolean;+ model: ModelIdentityModel;+ onDeleted: () => void;+ onToggleEditing: () => void;+}) => {+ const { convert, reidentify, remove } = useModelActions();+ const [pendingAction, setPendingAction] = useState<'delete' | 'convert' | null>(null);+ const [isActionBusy, setIsActionBusy] = useState(false);- {RELATED_MODEL_TYPES.has(model.type) ? (- <>- <Separator borderColor="border.subtle" />- <RelatedModelsSection model={model} onError={handleSectionError} />- </>- ) : null}+ const handleReidentify = async () => {+ setIsActionBusy(true);- {TRIGGER_PHRASE_TYPES.has(model.type) ? (- <>- <Separator borderColor="border.subtle" />- <TriggerPhrasesEditor model={model} onError={(message) => notify.error('Trigger phrases', message)} />- </>- ) : null}+ try {+ await reidentify(model);+ } finally {+ setIsActionBusy(false);+ }+ };+ return (+ <HStack flexShrink={0} gap="1" wrap="wrap">+ {isConvertibleToDiffusers(model) ? (+ <Button size="xs" variant="outline" onClick={() => setPendingAction('convert')}>+ <Icon as={SiHuggingface} boxSize="3" />+ Convert to Diffusers+ </Button>+ ) : null}+ <Button size="xs" variant={isEditing ? 'solid' : 'outline'} onClick={onToggleEditing}>+ <Icon as={PencilIcon} boxSize="3" />+ {isEditing ? 'Editing' : 'Edit'}+ </Button>+ <Menu.Root positioning={{ placement: 'bottom-end' }}>+ <Menu.Trigger asChild>+ <IconButton aria-label="Model actions" loading={isActionBusy} size="xs" variant="ghost">+ <Icon as={MoreHorizontalIcon} boxSize="4" />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="reidentify" onClick={() => void handleReidentify()}>+ <Icon as={RefreshCcwIcon} boxSize="3.5" />+ <Menu.ItemText fontSize="xs">Re-identify model</Menu.ItemText>+ </Menu.Item>+ <Menu.Separator />+ <Menu.Item color="fg.error" value="delete" onClick={() => setPendingAction('delete')}>+ <Icon as={Trash2Icon} boxSize="3.5" />+ <Menu.ItemText fontSize="xs">Delete model</Menu.ItemText>+ </Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root><ConfirmDialogbody={`Delete “${model.name}”? The database record is removed, and the model files are deleted if they live inside the InvokeAI models directory.`}confirmLabel="Delete Model"@@ -201,10 +321,71 @@ export const ModelDetail = ({onClose={() => setPendingAction(null)}onConfirm={() => convert(model)}/>- </Stack>+ </HStack>);};+const DefaultSettingsSectionContainer = memo(function DefaultSettingsSectionContainer({+ modelKey,+}: {+ modelKey: string;+}) {+ const notify = useNotify();+ const model = useModelsSelector((snapshot) => selectDefaultSettingsModel(snapshot.models, modelKey));++ if (!model || !supportsDefaultSettings(model)) {+ return null;+ }++ return (+ <DefaultSettingsSection+ model={model}+ onError={(message) => notify.error('Default settings', message)}+ onSaved={() => notify.success('Default settings saved')}+ />+ );+});++const TriggerPhrasesEditorContainer = memo(function TriggerPhrasesEditorContainer({ modelKey }: { modelKey: string }) {+ const notify = useNotify();+ const handleError = useCallback((message: string) => notify.error('Trigger phrases', message), [notify]);+ const model = useModelsSelector(+ (snapshot) => selectTriggerPhrasesModel(snapshot.models, modelKey),+ areTriggerPhrasesModelsEqual+ );++ if (!model) {+ return null;+ }++ return (+ <MemoizedTriggerPhrasesEditor+ modelKey={model.key}+ phrases={model.trigger_phrases ?? EMPTY_TRIGGER_PHRASES}+ onError={handleError}+ />+ );+});++const RelatedModelsSectionContainer = memo(function RelatedModelsSectionContainer({ modelKey }: { modelKey: string }) {+ const notify = useNotify();+ const model = useModelsSelector(+ (snapshot) => {+ const candidate = snapshot.models.find((model) => model.key === modelKey);++ return candidate ? { base: candidate.base, key: candidate.key } : null;+ },+ (left, right) => left?.key === right?.key && left?.base === right?.base+ );+ const handleSectionError = useCallback((message: string) => notify.error('Model manager', message), [notify]);++ if (!model) {+ return null;+ }++ return <RelatedModelsSection model={model} onError={handleSectionError} />;+});+const BackButton = ({ onBack }: { onBack: () => void }) => (<Button alignSelf="start" size="2xs" variant="ghost" onClick={onBack}><Icon as={ArrowLeftIcon} boxSize="3" />@@ -214,8 +395,8 @@ const BackButton = ({ onBack }: { onBack: () => void }) => (const isAbsolutePath = (path: string): boolean => path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path);-const ModelAttributes = ({ density, model }: { density: 'panel' | 'full'; model: ModelConfig }) => {- const { modelsDir } = useModelsSnapshot();+const ModelAttributes = ({ density, model }: { density: 'panel' | 'full'; model: ModelIdentityModel }) => {+ const modelsDir = useModelsSelector((snapshot) => snapshot.modelsDir);// Managed models store paths relative to the models directory; show the// resolved absolute path so it can be found on disk.const fullPath =diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsxindex 2d4c3adbbd..997f71487d 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelEditForm.tsx@@ -26,12 +26,17 @@ const KNOWN_BASES = [];/** Zod-validated editor for a model's identity fields. */+type ModelEditTarget = Pick<+ ModelConfig,+ 'base' | 'description' | 'key' | 'name' | 'prediction_type' | 'source_url' | 'type' | 'variant'+>;+export const ModelEditForm = ({model,onCancel,onSaved,}: {- model: ModelConfig;+ model: ModelEditTarget;onCancel: () => void;onSaved: () => void;}) => {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsxindex 34c0eafd9e..947bf7e961 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/ModelImageUpload.tsx@@ -3,9 +3,9 @@ import type { ModelConfig } from '@workbench/models/types';import { Box, Flex, Icon, Image, Stack, Text } from '@chakra-ui/react';import { IconButton, Tooltip } from '@workbench/components/ui';import { deleteModelImage, getModelImageUrl, updateModelImage } from '@workbench/models/api';-import { markCoverImageChanged, useModelsSnapshot } from '@workbench/models/modelsStore';+import { markCoverImageChanged, useModelsSelector } from '@workbench/models/modelsStore';import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';-import { useRef, useState, type DragEvent } from 'react';+import { useEffect, useRef, useState, type DragEvent } from 'react';const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);@@ -21,17 +21,23 @@ export const ModelImageUpload = ({onError,onUpdated,}: {- model: ModelConfig;+ model: Pick<ModelConfig, 'cover_image' | 'key' | 'name'>;onError: (message: string) => void;onUpdated: () => void;}) => {const inputRef = useRef<HTMLInputElement | null>(null);const dragDepthRef = useRef(0);- const { coverImageVersions } = useModelsSnapshot();+ const imageVersion = useModelsSelector((snapshot) => snapshot.coverImageVersions[model.key]);const [hasImage, setHasImage] = useState(Boolean(model.cover_image));const [isBusy, setIsBusy] = useState(false);const [isDropActive, setIsDropActive] = useState(false);- const imageVersion = coverImageVersions[model.key];++ useEffect(() => {+ dragDepthRef.current = 0;+ setHasImage(Boolean(model.cover_image));+ setIsBusy(false);+ setIsDropActive(false);+ }, [model.cover_image, model.key]);const handleFile = async (file: File | undefined) => {if (!file) {@@ -44,12 +50,13 @@ export const ModelImageUpload = ({}setIsBusy(true);+ const modelKey = model.key;try {- await updateModelImage(model.key, file);+ await updateModelImage(modelKey, file);setHasImage(true);// Bumps the cache-bust version so this tile and list thumbnails reload.- markCoverImageChanged(model.key, true);+ markCoverImageChanged(modelKey, true);onUpdated();} catch (error) {onError(error instanceof Error ? error.message : 'Failed to upload model image.');@@ -60,11 +67,12 @@ export const ModelImageUpload = ({const handleDelete = async () => {setIsBusy(true);+ const modelKey = model.key;try {- await deleteModelImage(model.key);+ await deleteModelImage(modelKey);setHasImage(false);- markCoverImageChanged(model.key, false);+ markCoverImageChanged(modelKey, false);onUpdated();} catch (error) {onError(error instanceof Error ? error.message : 'Failed to remove model image.');diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsxindex bb33465f34..d74cd09d71 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/RelatedModelsSection.tsx@@ -6,7 +6,7 @@ import { SourceListItem } from '@workbench/launchpad/models/shared/SourceListIteimport { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from '@workbench/models/api';import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';import { ModelSelect } from '@workbench/models/components';-import { useModelsSnapshot } from '@workbench/models/modelsStore';+import { useModelsSelector } from '@workbench/models/modelsStore';import { getModelTypeLabel } from '@workbench/models/taxonomy';import { Link2OffIcon } from 'lucide-react';import { useEffect, useMemo, useState } from 'react';@@ -32,10 +32,10 @@ export const RelatedModelsSection = ({model,onError,}: {- model: ModelConfig;+ model: Pick<ModelConfig, 'base' | 'key'>;onError: (message: string) => void;}) => {- const { models } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);const [relatedKeys, setRelatedKeys] = useState<string[] | null>(null);const [isMutating, setIsMutating] = useState(false);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsxindex cdcea1fcf3..b6492b9688 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/TriggerPhrasesEditor.tsx@@ -1,34 +1,52 @@-import type { ModelConfig } from '@workbench/models/types';-import { HStack, Icon, Input, Tag, Text, Wrap } from '@chakra-ui/react';import { Button, Field } from '@workbench/components/ui';import { updateModel } from '@workbench/models/api';import { replaceModelInStore } from '@workbench/models/modelsStore';import { triggerPhraseSchema } from '@workbench/models/schemas';import { PlusIcon } from 'lucide-react';-import { useState } from 'react';+import { memo, useState } from 'react';++interface TriggerPhrasesEditorState {+ draft: string;+ error: string | null;+ isSaving: boolean;+ modelKey: string;+}/*** Tag-style editor for a model's trigger phrases. Each add/remove persists* immediately — there is no separate save step for phrases.*/export const TriggerPhrasesEditor = ({- model,+ modelKey,onError,+ phrases,}: {- model: ModelConfig;+ modelKey: string;onError: (message: string) => void;+ phrases: readonly string[];}) => {- const [draft, setDraft] = useState('');- const [error, setError] = useState<string | null>(null);- const [isSaving, setIsSaving] = useState(false);- const phrases = model.trigger_phrases ?? [];+ const [editor, setEditor] = useState<TriggerPhrasesEditorState>(() => ({+ draft: '',+ error: null,+ isSaving: false,+ modelKey,+ }));+ const isEditorCurrent = editor.modelKey === modelKey;+ const draft = isEditorCurrent ? editor.draft : '';+ const error = isEditorCurrent ? editor.error : null;+ const isSaving = isEditorCurrent ? editor.isSaving : false;const persist = async (nextPhrases: string[]): Promise<boolean> => {- setIsSaving(true);+ setEditor((current) => ({+ draft: current.modelKey === modelKey ? current.draft : '',+ error: current.modelKey === modelKey ? current.error : null,+ isSaving: true,+ modelKey,+ }));try {- replaceModelInStore(await updateModel(model.key, { trigger_phrases: nextPhrases }));+ replaceModelInStore(await updateModel(modelKey, { trigger_phrases: nextPhrases }));return true;} catch (persistError) {@@ -36,7 +54,7 @@ export const TriggerPhrasesEditor = ({return false;} finally {- setIsSaving(false);+ setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));}};@@ -44,20 +62,20 @@ export const TriggerPhrasesEditor = ({const parsed = triggerPhraseSchema.safeParse(draft);if (!parsed.success) {- setError(parsed.error.issues[0]?.message ?? 'Invalid trigger phrase.');+ setEditor({ draft, error: parsed.error.issues[0]?.message ?? 'Invalid trigger phrase.', isSaving, modelKey });return;}if (phrases.some((phrase) => phrase.toLowerCase() === parsed.data.toLowerCase())) {- setError('That trigger phrase is already on this model.');+ setEditor({ draft, error: 'That trigger phrase is already on this model.', isSaving, modelKey });return;}- setError(null);+ setEditor({ draft, error: null, isSaving, modelKey });// Clear the draft only once it is saved, so a failure never eats the text.if (await persist([...phrases, parsed.data])) {- setDraft('');+ setEditor((current) => (current.modelKey === modelKey ? { ...current, draft: '' } : current));}};@@ -71,11 +89,10 @@ export const TriggerPhrasesEditor = ({<Inputaria-invalid={error ? true : undefined}placeholder="Add a trigger phrase…"- size="sm"+ size="xs"value={draft}onChange={(event) => {- setDraft(event.currentTarget.value);- setError(null);+ setEditor({ draft: event.currentTarget.value, error: null, isSaving, modelKey });}}onKeyDown={(event) => {if (event.key === 'Enter') {@@ -87,7 +104,7 @@ export const TriggerPhrasesEditor = ({<Buttondisabled={draft.trim().length === 0}loading={isSaving}- size="sm"+ size="xs"variant="outline"onClick={() => {void addPhrase();@@ -121,3 +138,5 @@ export const TriggerPhrasesEditor = ({</Field>);};++export const MemoizedTriggerPhrasesEditor = memo(TriggerPhrasesEditor);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.tsindex 8226589986..52865ed846 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/detail/useModelActions.ts@@ -11,11 +11,13 @@ import { useCallback } from 'react';* library row context menu so behavior and notifications stay identical.* Confirmation UI is the caller's job; these just act and notify.*/+type ModelActionTarget = Pick<ModelConfig, 'key' | 'name'>;+export const useModelActions = () => {const notify = useNotify();const remove = useCallback(- async (model: ModelConfig) => {+ async (model: ModelActionTarget) => {try {await deleteModel(model.key);removeModelsFromStore([model.key]);@@ -29,7 +31,7 @@ export const useModelActions = () => {);const convert = useCallback(- async (model: ModelConfig) => {+ async (model: ModelActionTarget) => {try {replaceModelInStore(await convertModelToDiffusers(model.key));notify.success('Converted to diffusers', model.name);@@ -41,7 +43,7 @@ export const useModelActions = () => {);const reidentify = useCallback(- async (model: ModelConfig) => {+ async (model: ModelActionTarget) => {try {replaceModelInStore(await reidentifyModel(model.key));notify.success('Model re-identified', model.name);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsxindex 6fb1e1c3df..bc1799d217 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallJobRow.tsx@@ -1,7 +1,7 @@import type { ModelInstallJob } from '@workbench/models/types';import { Badge, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { useConnectionStatus } from '@workbench/backend/connectionStore';+import { useConnectionStatusSelector } from '@workbench/backend/connectionStore';import { IconButton, Tooltip } from '@workbench/components/ui';import {cancelModelInstall,@@ -29,7 +29,7 @@ export const InstallJobRow = ({onError: (title: string, message: string) => void;}) => {const [isActing, setIsActing] = useState(false);- const { status: connectionStatus } = useConnectionStatus();+ const connectionStatus = useConnectionStatusSelector((snapshot) => snapshot.status);const badge = STATUS_BADGES[job.status] ?? { label: job.status, palette: 'gray' };const sourceLabel = getInstallSourceLabel(job.source);const displayName = getInstallJobDisplayName(job);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsxindex 0bbc555c1c..2b901607eb 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/install-queue/InstallQueueBar.tsx@@ -12,9 +12,9 @@ import {ensureInstallsLoaded,isActiveInstallStatus,refreshInstalls,- useInstallsSnapshot,+ useInstallsSelector,} from '@workbench/models/installsStore';-import { setQueueExpanded, useModelsUi } from '@workbench/models/uiStore';+import { setQueueExpanded, useModelsUiSelector } from '@workbench/models/uiStore';import { useNotify } from '@workbench/useNotify';import { ChevronUpIcon, ListOrderedIcon, PauseIcon, PlayIcon, RefreshCcwIcon, Trash2Icon, XIcon } from 'lucide-react';import { useEffect, useState } from 'react';@@ -25,8 +25,10 @@ import { getInstallJobDisplayName } from './queueUtils';/** Persistent, collapsible install queue footer for the model manager detail pane. */export const InstallQueueBar = () => {const notify = useNotify();- const { error, jobs, status } = useInstallsSnapshot();- const { queueExpanded } = useModelsUi();+ const error = useInstallsSelector((snapshot) => snapshot.error);+ const jobs = useInstallsSelector((snapshot) => snapshot.jobs);+ const status = useInstallsSelector((snapshot) => snapshot.status);+ const queueExpanded = useModelsUiSelector((snapshot) => snapshot.queueExpanded);useEffect(() => {ensureInstallsLoaded();diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsxindex 36e68c8df2..1e1cba2747 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelFilterBar.tsx@@ -4,6 +4,7 @@ import type { ModelTaxonomyType } from '@workbench/models/types';import { HStack, Icon, Input, InputGroup } from '@chakra-ui/react';import { FilterMenuItem, ModelFilterMenu } from '@workbench/launchpad/models/shared/ModelFilterMenu';import { SearchIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';const SORT_FIELDS: { field: ModelSortField; label: string }[] = [{ field: 'default', label: 'Default' },@@ -32,41 +33,67 @@ export const ModelFilterBar = ({filters: ModelLibraryFilters;missingCount: number;onChange: (filters: ModelLibraryFilters) => void;-}) => (- <HStack gap="1.5" w="full" px="3" pt="3">- <InputGroup startElement={<Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />}>- <Input- aria-label="Search models"- placeholder="Search models…"- size="xs"- value={filters.searchTerm}- onChange={(event) => onChange({ ...filters, searchTerm: event.currentTarget.value })}+}) => {+ const handleSearchChange = useCallback(+ (searchTerm: string) => onChange({ ...filters, searchTerm }),+ [filters, onChange]+ );+ const handleMissingFilterToggle = useCallback(+ () => onChange({ ...filters, missingOnly: !filters.missingOnly, typeFilter: null }),+ [filters, onChange]+ );+ const handleBaseFilterChange = useCallback(+ (baseFilter: string | null) => onChange({ ...filters, baseFilter }),+ [filters, onChange]+ );+ const handleSortChange = useCallback(+ (sortField: ModelSortField, sortDirection: 'asc' | 'desc') => onChange({ ...filters, sortDirection, sortField }),+ [filters, onChange]+ );+ const handleTypeFilterChange = useCallback(+ (typeFilter: ModelTaxonomyType | null) => onChange({ ...filters, missingOnly: false, typeFilter }),+ [filters, onChange]+ );+ const extraTypeItems = useMemo(+ () =>+ missingCount > 0 ? (+ <FilterMenuItem+ isChecked={filters.missingOnly}+ label={`Missing files (${missingCount})`}+ value="type-missing"+ onSelect={handleMissingFilterToggle}+ />+ ) : null,+ [filters.missingOnly, handleMissingFilterToggle, missingCount]+ );++ return (+ <HStack gap="1.5" w="full" px="3" pt="3">+ <InputGroup startElement={<Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />}>+ <Input+ aria-label="Search models"+ placeholder="Search models…"+ size="xs"+ value={filters.searchTerm}+ onChange={(event) => handleSearchChange(event.currentTarget.value)}+ />+ </InputGroup>+ <ModelFilterMenu+ ariaLabel="Filter and sort models"+ availableBases={availableBases}+ availableTypes={availableTypes}+ baseFilter={filters.baseFilter}+ extraTypeItems={extraTypeItems}+ isActive={isFiltering(filters)}+ sortDirection={filters.sortDirection}+ sortField={filters.sortField}+ sortFields={SORT_FIELDS}+ typeAllChecked={filters.typeFilter === null && !filters.missingOnly}+ typeFilter={filters.typeFilter}+ onBaseFilterChange={handleBaseFilterChange}+ onSortChange={handleSortChange}+ onTypeFilterChange={handleTypeFilterChange}/>- </InputGroup>- <ModelFilterMenu- ariaLabel="Filter and sort models"- availableBases={availableBases}- availableTypes={availableTypes}- baseFilter={filters.baseFilter}- extraTypeItems={- missingCount > 0 ? (- <FilterMenuItem- isChecked={filters.missingOnly}- label={`Missing files (${missingCount})`}- value="type-missing"- onSelect={() => onChange({ ...filters, missingOnly: !filters.missingOnly, typeFilter: null })}- />- ) : null- }- isActive={isFiltering(filters)}- sortDirection={filters.sortDirection}- sortField={filters.sortField}- sortFields={SORT_FIELDS}- typeAllChecked={filters.typeFilter === null && !filters.missingOnly}- typeFilter={filters.typeFilter}- onBaseFilterChange={(baseFilter) => onChange({ ...filters, baseFilter })}- onSortChange={(sortField, sortDirection) => onChange({ ...filters, sortDirection, sortField })}- onTypeFilterChange={(typeFilter) => onChange({ ...filters, missingOnly: false, typeFilter })}- />- </HStack>-);+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsxindex 150c547a70..fbebaf7e2e 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelLibraryList.tsx@@ -1,10 +1,8 @@-import type { ModelConfig } from '@workbench/models/types';-import { Box, Checkbox, Flex, HStack, Icon, Image, ScrollArea, Spinner, Stack, Text } from '@chakra-ui/react';import { defaultRangeExtractor, useVirtualizer, type Range } from '@tanstack/react-virtual';import { Button, Row } from '@workbench/components/ui';import { EmptyState } from '@workbench/components/ui/EmptyState';-import { ModelBadgeRow } from '@workbench/launchpad/models/detail/ModelBadges';+import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from '@workbench/launchpad/models/detail/ModelBadges';import { getModelImageUrl } from '@workbench/models/api';import {filterModels,@@ -12,11 +10,11 @@ import {groupModelsByType,type ModelLibraryFilters,} from '@workbench/models/library';-import { useModelsSnapshot } from '@workbench/models/modelsStore';+import { useModelsSelector } from '@workbench/models/modelsStore';import { formatBytes } from '@workbench/models/taxonomy';import { getLibraryScrollOffset, openModelManagerTab, saveLibraryScrollOffset } from '@workbench/models/uiStore';import { ArrowRightIcon, BoxIcon, CircleAlert } from 'lucide-react';-import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';import { ModelRowContextMenu, type ModelContextMenuTarget } from './ModelRowContextMenu';@@ -44,18 +42,36 @@ export const ModelLibraryList = ({filters: ModelLibraryFilters;/** Identifies this list's scroll-offset slot ('panel', 'manager', ...). */instanceId: string;- onActivate: (model: ModelConfig) => void;+ onActivate: (modelKey: string) => void;/** Present in the manager library: enables bulk-select checkboxes. */- onToggleSelected?: (model: ModelConfig) => void;+ onToggleSelected?: (modelKey: string) => void;selectedKeys?: ReadonlySet<string>;}) => {- const { coverImageVersions, error, missingModelKeys, models, status } = useModelsSnapshot();+ const { coverImageVersions, error, missingModelKeys, models, status } = useModelsSelector(+ (snapshot) => ({+ coverImageVersions: snapshot.coverImageVersions,+ error: snapshot.error,+ missingModelKeys: snapshot.missingModelKeys,+ models: snapshot.models,+ status: snapshot.status,+ }),+ (left, right) =>+ left.coverImageVersions === right.coverImageVersions &&+ left.error === right.error &&+ left.missingModelKeys === right.missingModelKeys &&+ left.models === right.models &&+ left.status === right.status+ );const deferredFilters = useDeferredValue(filters);const scrollRef = useRef<HTMLDivElement | null>(null);const [contextMenuTarget, setContextMenuTarget] = useState<ModelContextMenuTarget | null>(null);const openAddModels = () => {openModelManagerTab('add');};+ const handleContextMenu = useCallback(+ (modelKey: string, x: number, y: number) => setContextMenuTarget({ modelKey, x, y }),+ []+ );const rows = useMemo(() => flattenGroupsToRows(groupModelsByType(filterModels(models, deferredFilters, missingModelKeys))),@@ -81,6 +97,11 @@ export const ModelLibraryList = ({const virtualizer = useVirtualizer({count: rows.length,estimateSize: (index) => (rows[index]?.kind === 'header' ? HEADER_ROW_HEIGHT_PX : MODEL_ROW_HEIGHT_PX),+ getItemKey: (index) => {+ const row = rows[index];++ return row?.kind === 'model' ? row.model.key : `header:${row?.group.type ?? index}`;+ },getScrollElement: () => scrollRef.current,initialOffset: () => getLibraryScrollOffset(instanceId),overscan: 8,@@ -143,31 +164,31 @@ export const ModelLibraryList = ({return null;}- return (- <Box+ return row.kind === 'header' ? (+ <VirtualHeaderRowkey={virtualRow.key}- left="0"- position="absolute"- top="0"- transform={`translateY(${virtualRow.start}px)`}- w="full"- px="3"- >- {row.kind === 'header' ? (- <GroupHeader count={row.group.models.length} label={row.group.label} />- ) : (- <ModelRow- imageVersion={coverImageVersions[row.model.key]}- isActive={row.model.key === activeModelKey}- isMissing={missingModelKeys.has(row.model.key)}- isSelected={selectedKeys?.has(row.model.key) ?? false}- model={row.model}- onActivate={onActivate}- onContextMenu={(model, x, y) => setContextMenuTarget({ model, x, y })}- onToggleSelected={onToggleSelected}- />- )}- </Box>+ count={row.group.models.length}+ label={row.group.label}+ virtualStart={virtualRow.start}+ />+ ) : (+ <VirtualModelRow+ key={virtualRow.key}+ base={row.model.base}+ coverImage={row.model.cover_image}+ fileSize={row.model.file_size}+ format={row.model.format}+ imageVersion={coverImageVersions[row.model.key]}+ isActive={row.model.key === activeModelKey}+ isMissing={missingModelKeys.has(row.model.key)}+ isSelected={selectedKeys?.has(row.model.key) ?? false}+ modelKey={row.model.key}+ name={row.model.name}+ virtualStart={virtualRow.start}+ onActivate={onActivate}+ onContextMenu={handleContextMenu}+ onToggleSelected={onToggleSelected}+ />);})}</Box>@@ -200,81 +221,137 @@ const GroupHeader = ({ count, label }: { count: number; label: string }) => (</HStack>);-const ModelRow = ({+interface VirtualHeaderRowProps {+ count: number;+ label: string;+ virtualStart: number;+}++const VirtualHeaderRow = memo(function VirtualHeaderRow({ count, label, virtualStart }: VirtualHeaderRowProps) {+ return (+ <Box left="0" position="absolute" top="0" transform={`translateY(${virtualStart}px)`} w="full" px="3">+ <GroupHeader count={count} label={label} />+ </Box>+ );+});++interface ModelRowProps {+ base: Parameters<typeof ModelBaseBadge>[0]['base'];+ coverImage?: string | null;+ fileSize: number;+ format: Parameters<typeof ModelFormatBadge>[0]['format'];+ imageVersion?: number;+ isActive: boolean;+ isMissing: boolean;+ isSelected: boolean;+ modelKey: string;+ name: string;+ onActivate: (modelKey: string) => void;+ onContextMenu: (modelKey: string, x: number, y: number) => void;+ onToggleSelected?: (modelKey: string) => void;+}++interface VirtualModelRowProps extends ModelRowProps {+ virtualStart: number;+}++const VirtualModelRow = memo(function VirtualModelRow({ virtualStart, ...rowProps }: VirtualModelRowProps) {+ return (+ <Box left="0" position="absolute" top="0" transform={`translateY(${virtualStart}px)`} w="full" px="3">+ <ModelRow {...rowProps} />+ </Box>+ );+});++const ModelRow = memo(function ModelRow({+ base,+ coverImage,+ fileSize,+ format,imageVersion,isActive,isMissing,isSelected,- model,+ modelKey,+ name,onActivate,onContextMenu,onToggleSelected,-}: {- /** Cover-image cache-bust version from the models store. */- imageVersion?: number;- isActive: boolean;- isMissing: boolean;- isSelected: boolean;- model: ModelConfig;- onActivate: (model: ModelConfig) => void;- onContextMenu: (model: ModelConfig, x: number, y: number) => void;- onToggleSelected?: (model: ModelConfig) => void;-}) => (- <Row- active={isActive ? 'accent' : isSelected ? 'muted' : 'none'}- aria-current={isActive || undefined}- h={`${MODEL_ROW_HEIGHT_PX - 4}px`}- mb="1"- minW="0"- px="2"- role="button"- rounded="md"- tabIndex={0}- _focusVisible={{ boxShadow: 'inset 0 0 0 2px {colors.accent.solid}', outline: 'none' }}- onClick={() => onActivate(model)}- onContextMenu={(event) => {- event.preventDefault();- onContextMenu(model, event.clientX, event.clientY);- }}- onKeyDown={(event) => {- if (event.key === 'Enter' || event.key === ' ') {+}: ModelRowProps) {+ return (+ <Row+ active={isActive ? 'accent' : isSelected ? 'muted' : 'none'}+ aria-current={isActive || undefined}+ h={`${MODEL_ROW_HEIGHT_PX - 4}px`}+ mb="1"+ minW="0"+ px="2"+ role="button"+ rounded="md"+ tabIndex={0}+ _focusVisible={{ boxShadow: 'inset 0 0 0 2px {colors.accent.solid}', outline: 'none' }}+ onClick={() => onActivate(modelKey)}+ onContextMenu={(event) => {event.preventDefault();- onActivate(model);- }- }}- >- {onToggleSelected ? (- <Checkbox.Root- aria-label={`Select ${model.name}`}- checked={isSelected}- colorPalette="accent"- size="xs"- onCheckedChange={() => onToggleSelected(model)}- onClick={(event) => event.stopPropagation()}- >- <Checkbox.HiddenInput />- <Checkbox.Control />- </Checkbox.Root>- ) : null}- {/* Keyed by version so a stale load error clears when the image changes. */}- <ModelRowThumbnail key={imageVersion ?? 0} imageVersion={imageVersion} model={model} />- <Stack flex="1" gap="0.5" minW="0">- <Text fontSize="xs" fontWeight="600" truncate>- {model.name}+ onContextMenu(modelKey, event.clientX, event.clientY);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ onActivate(modelKey);+ }+ }}+ >+ {onToggleSelected ? (+ <Checkbox.Root+ aria-label={`Select ${name}`}+ checked={isSelected}+ colorPalette="accent"+ size="xs"+ onCheckedChange={() => onToggleSelected(modelKey)}+ onClick={(event) => event.stopPropagation()}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ </Checkbox.Root>+ ) : null}+ {/* Keyed by version so a stale load error clears when the image changes. */}+ <ModelRowThumbnail+ key={`${modelKey}:${imageVersion ?? 0}`}+ coverImage={coverImage}+ imageVersion={imageVersion}+ modelKey={modelKey}+ />+ <Stack flex="1" gap="0.5" minW="0">+ <Text fontSize="xs" fontWeight="600" truncate>+ {name}+ </Text>+ <HStack gap="1" minW="0" wrap="wrap">+ <ModelBaseBadge base={base} />+ <ModelFormatBadge format={format} />+ {isMissing ? <MissingFileBadge /> : null}+ </HStack>+ </Stack>+ <Text color={isActive ? 'accent.solid' : 'fg.subtle'} flexShrink={0} fontSize="2xs">+ {formatBytes(fileSize)}</Text>- <ModelBadgeRow isMissing={isMissing} model={model} />- </Stack>- <Text color={isActive ? 'accent.solid' : 'fg.subtle'} flexShrink={0} fontSize="2xs">- {formatBytes(model.file_size)}- </Text>- </Row>-);+ </Row>+ );+});-const ModelRowThumbnail = ({ imageVersion, model }: { imageVersion?: number; model: ModelConfig }) => {+const ModelRowThumbnail = ({+ coverImage,+ imageVersion,+ modelKey,+}: {+ coverImage?: string | null;+ imageVersion?: number;+ modelKey: string;+}) => {// The cover_image marker can be stale; fall back to the icon on load error.const [hasImageError, setHasImageError] = useState(false);- if (!model.cover_image || hasImageError) {+ if (!coverImage || hasImageError) {return (<Flexalign="center"@@ -300,7 +377,7 @@ const ModelRowThumbnail = ({ imageVersion, model }: { imageVersion?: number; modflexShrink={0}loading="lazy"rounded="md"- src={getModelImageUrl(model.key, imageVersion ? String(imageVersion) : undefined)}+ src={getModelImageUrl(modelKey, imageVersion ? String(imageVersion) : undefined)}onError={() => setHasImageError(true)}/>);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsxindex e4a8c37f83..4695eeb5d5 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/library/ModelRowContextMenu.tsx@@ -4,12 +4,13 @@ import { Icon, Menu, Portal } from '@chakra-ui/react';import { ConfirmDialog, MenuContent } from '@workbench/components/ui';import { useModelActions } from '@workbench/launchpad/models/detail/useModelActions';import { isConvertibleToDiffusers } from '@workbench/models/baseIdentity';+import { useModelsSelector } from '@workbench/models/modelsStore';import { RefreshCcwIcon, Trash2Icon } from 'lucide-react';import { useRef, useState } from 'react';import { SiHuggingface } from 'react-icons/si';export interface ModelContextMenuTarget {- model: ModelConfig;+ modelKey: string;x: number;y: number;}@@ -32,12 +33,14 @@ export const ModelRowContextMenu = ({targetRef.current = target;- const model = target?.model ?? null;+ const model = useModelsSelector((snapshot) =>+ target ? (snapshot.models.find((candidate) => candidate.key === target.modelKey) ?? null) : null+ );return (<><Menu.Root- key={target ? target.model.key : 'closed'}+ key={target ? target.modelKey : 'closed'}lazyMountopen={target !== null}positioning={{diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsxindex d39ff9565b..b43e34093f 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/DetailPane.tsx@@ -4,19 +4,22 @@ import { AddModelsView } from '@workbench/launchpad/models/add-models/AddModelsVimport { ApiKeysSection } from '@workbench/launchpad/models/credentials/ApiKeysSection';import { ModelDetail } from '@workbench/launchpad/models/detail/ModelDetail';import { InstallQueueBar } from '@workbench/launchpad/models/install-queue/InstallQueueBar';-import { useModelsSnapshot } from '@workbench/models/modelsStore';-import { updateModelsUi, useModelsUi, type ModelManagerTab } from '@workbench/models/uiStore';+import { useModelsSelector } from '@workbench/models/modelsStore';+import { updateModelsUi, useModelsUiSelector, type ModelManagerTab } from '@workbench/models/uiStore';import { BoxIcon, KeyRoundIcon, PlusIcon } from 'lucide-react';+import { useCallback } from 'react';import { HEADER_MIN_HEIGHT } from './layoutConstants';/** The tabbed detail pane: selected model, Add Models, API Keys, and queue footer. */export const DetailPane = () => {- const { activeModelKey, activeTab } = useModelsUi();- const { models } = useModelsSnapshot();-- const activeModel = activeModelKey ? models.find((model) => model.key === activeModelKey) : undefined;- const detailLabel = activeModel?.name ?? 'Model Details';+ const { activeModelKey, activeTab } = useModelsUiSelector(+ (snapshot) => ({ activeModelKey: snapshot.activeModelKey, activeTab: snapshot.activeTab }),+ (left, right) => left.activeModelKey === right.activeModelKey && left.activeTab === right.activeTab+ );+ const detailLabel = useModelsSelector(+ (snapshot) => snapshot.models.find((model) => model.key === activeModelKey)?.name ?? 'Model Details'+ );return (<Flex direction="column" flex="1" minH="0" minW="0">@@ -62,6 +65,8 @@ export const DetailPane = () => {};const DetailTab = ({ modelKey }: { modelKey: string | null }) => {+ const handleDeleted = useCallback(() => updateModelsUi({ activeModelKey: null }), []);+if (modelKey === null) {return (<Flex align="center" direction="column" gap="2" h="full" justify="center" p="6">@@ -79,12 +84,7 @@ const DetailTab = ({ modelKey }: { modelKey: string | null }) => {return (<Scrollable h="full" label="Model details" minH="0" p="3">- <ModelDetail- key={modelKey}- density="full"- modelKey={modelKey}- onDeleted={() => updateModelsUi({ activeModelKey: null })}- />+ <ModelDetail key={modelKey} density="full" modelKey={modelKey} onDeleted={handleDeleted} /></Scrollable>);};diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsxindex f53b23115d..bcbd28fae0 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/manager/LibraryColumn.tsx@@ -5,29 +5,42 @@ import { ModelFilterBar } from '@workbench/launchpad/models/library/ModelFilterBimport { ModelLibraryList } from '@workbench/launchpad/models/library/ModelLibraryList';import { bulkDeleteModels } from '@workbench/models/api';import { collectBases, collectTypes } from '@workbench/models/library';-import { refreshModels, removeModelsFromStore, useModelsSnapshot } from '@workbench/models/modelsStore';+import { refreshModels, removeModelsFromStore, useModelsSelector } from '@workbench/models/modelsStore';import {openModelDetail,pruneModelsUiKeys,toggleModelSelection,updateModelsUi,- useModelsUi,+ useModelsUiSelector,} from '@workbench/models/uiStore';import { useNotify } from '@workbench/useNotify';import { Trash2Icon, XIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { HEADER_MIN_HEIGHT, LIBRARY_WIDTH } from './layoutConstants';/** The persistent master list: header, search/filter bar, and bulk actions. */export const LibraryColumn = () => {const notify = useNotify();- const { missingModelKeys, models } = useModelsSnapshot();- const { activeModelKey, filters, selectedKeys } = useModelsUi();+ const models = useModelsSelector((snapshot) => snapshot.models);+ const missingCount = useModelsSelector((snapshot) => snapshot.missingModelKeys.size);+ const { activeModelKey, filters, selectedKeys } = useModelsUiSelector(+ (snapshot) => ({+ activeModelKey: snapshot.activeModelKey,+ filters: snapshot.filters,+ selectedKeys: snapshot.selectedKeys,+ }),+ (left, right) =>+ left.activeModelKey === right.activeModelKey &&+ left.filters === right.filters &&+ left.selectedKeys === right.selectedKeys+ );const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);const availableTypes = useMemo(() => collectTypes(models), [models]);const availableBases = useMemo(() => collectBases(models), [models]);+ const handleActivate = useCallback((modelKey: string) => openModelDetail(modelKey), []);+ const handleToggleSelected = useCallback((modelKey: string) => toggleModelSelection(modelKey), []);const handleBulkDelete = async () => {const keys = [...selectedKeys];@@ -74,7 +87,7 @@ export const LibraryColumn = () => {availableBases={availableBases}availableTypes={availableTypes}filters={filters}- missingCount={missingModelKeys.size}+ missingCount={missingCount}onChange={(nextFilters) => updateModelsUi({ filters: nextFilters })}/>@@ -83,8 +96,8 @@ export const LibraryColumn = () => {filters={filters}instanceId="manager"selectedKeys={selectedKeys}- onActivate={(model) => openModelDetail(model.key)}- onToggleSelected={(model) => toggleModelSelection(model.key)}+ onActivate={handleActivate}+ onToggleSelected={handleToggleSelected}/>{selectedKeys.size > 0 ? (diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsxindex 791df4198b..8325648cc2 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/models/shared/ModelFilterMenu.tsx@@ -7,6 +7,7 @@ import { IconButton, MenuContent } from '@workbench/components/ui';import { getModelBaseLabel } from '@workbench/models/baseIdentity';import { getModelTypeLabel } from '@workbench/models/taxonomy';import { CheckIcon, SlidersHorizontalIcon } from 'lucide-react';+import { memo } from 'react';export interface ModelFilterSortOption {field: ModelSortField;@@ -68,20 +69,18 @@ export const ModelFilterMenu = ({<Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">Model Type</Menu.ItemGroupLabel>- <FilterMenuItem+ <AllTypesFilterMenuItemisChecked={typeAllChecked ?? typeFilter === null}label={typeAllLabel}- value="type-all"- onSelect={() => onTypeFilterChange(null)}+ onTypeFilterChange={onTypeFilterChange}/>{extraTypeItems}{availableTypes.map((type) => (- <FilterMenuItem+ <TypeFilterMenuItemkey={type}- isChecked={typeFilter === type}- label={getModelTypeLabel(type)}- value={`type-${type}`}- onSelect={() => onTypeFilterChange(typeFilter === type ? null : type)}+ type={type}+ typeFilter={typeFilter}+ onTypeFilterChange={onTypeFilterChange}/>))}</Menu.ItemGroup>@@ -90,19 +89,13 @@ export const ModelFilterMenu = ({<Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">Base Architecture</Menu.ItemGroupLabel>- <FilterMenuItem- isChecked={baseFilter === null}- label="All bases"- value="base-all"- onSelect={() => onBaseFilterChange(null)}- />+ <AllBasesFilterMenuItem isChecked={baseFilter === null} onBaseFilterChange={onBaseFilterChange} />{availableBases.map((base) => (- <FilterMenuItem+ <BaseFilterMenuItemkey={base}- isChecked={baseFilter === base}- label={getModelBaseLabel(base)}- value={`base-${base}`}- onSelect={() => onBaseFilterChange(baseFilter === base ? null : base)}+ base={base}+ baseFilter={baseFilter}+ onBaseFilterChange={onBaseFilterChange}/>))}</Menu.ItemGroup>@@ -112,15 +105,13 @@ export const ModelFilterMenu = ({Sort By</Menu.ItemGroupLabel>{sortFields.map(({ field, label }) => (- <FilterMenuItem+ <SortFilterMenuItemkey={field}- isChecked={sortField === field}+ field={field}label={label}- value={`sort-${field}`}- onSelect={() =>- onSortChange(field, sortField === field ? (sortDirection === 'asc' ? 'desc' : 'asc') : 'asc')- }- trailing={sortField === field ? (sortDirection === 'asc' ? 'Asc' : 'Desc') : undefined}+ sortDirection={sortDirection}+ sortField={sortField}+ onSortChange={onSortChange}/>))}</Menu.ItemGroup>@@ -131,26 +122,123 @@ export const ModelFilterMenu = ({);/** Checkmark-style menu item shared by the model filter menus. */-export const FilterMenuItem = ({+interface FilterMenuItemProps {+ isChecked: boolean;+ label: string;+ onSelect: () => void;+ trailing?: string;+ value: string;+}++export const FilterMenuItem = memo(function FilterMenuItem({isChecked,label,onSelect,trailing,value,+}: FilterMenuItemProps) {+ return (+ <Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>+ <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />+ <Menu.ItemText fontSize="xs">{label}</Menu.ItemText>+ {trailing ? (+ <Text color="fg.subtle" fontSize="2xs" ms="auto">+ {trailing}+ </Text>+ ) : null}+ </Menu.Item>+ );+});++const AllTypesFilterMenuItem = memo(function AllTypesFilterMenuItem({+ isChecked,+ label,+ onTypeFilterChange,}: {isChecked: boolean;label: string;- onSelect: () => void;- trailing?: string;- value: string;-}) => (- <Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>- <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />- <Menu.ItemText fontSize="xs">{label}</Menu.ItemText>- {trailing ? (- <Text color="fg.subtle" fontSize="2xs" ms="auto">- {trailing}- </Text>- ) : null}- </Menu.Item>-);+ onTypeFilterChange: (type: ModelTaxonomyType | null) => void;+}) {+ return (+ <FilterMenuItem isChecked={isChecked} label={label} value="type-all" onSelect={() => onTypeFilterChange(null)} />+ );+});++const TypeFilterMenuItem = memo(function TypeFilterMenuItem({+ type,+ typeFilter,+ onTypeFilterChange,+}: {+ type: ModelTaxonomyType;+ typeFilter: ModelTaxonomyType | null;+ onTypeFilterChange: (type: ModelTaxonomyType | null) => void;+}) {+ return (+ <FilterMenuItem+ isChecked={typeFilter === type}+ label={getModelTypeLabel(type)}+ value={`type-${type}`}+ onSelect={() => onTypeFilterChange(typeFilter === type ? null : type)}+ />+ );+});++const AllBasesFilterMenuItem = memo(function AllBasesFilterMenuItem({+ isChecked,+ onBaseFilterChange,+}: {+ isChecked: boolean;+ onBaseFilterChange: (base: string | null) => void;+}) {+ return (+ <FilterMenuItem+ isChecked={isChecked}+ label="All bases"+ value="base-all"+ onSelect={() => onBaseFilterChange(null)}+ />+ );+});++const BaseFilterMenuItem = memo(function BaseFilterMenuItem({+ base,+ baseFilter,+ onBaseFilterChange,+}: {+ base: string;+ baseFilter: string | null;+ onBaseFilterChange: (base: string | null) => void;+}) {+ return (+ <FilterMenuItem+ isChecked={baseFilter === base}+ label={getModelBaseLabel(base)}+ value={`base-${base}`}+ onSelect={() => onBaseFilterChange(baseFilter === base ? null : base)}+ />+ );+});++const SortFilterMenuItem = memo(function SortFilterMenuItem({+ field,+ label,+ sortDirection,+ sortField,+ onSortChange,+}: {+ field: ModelSortField;+ label: string;+ sortDirection: 'asc' | 'desc';+ sortField: ModelSortField;+ onSortChange: (field: ModelSortField, direction: 'asc' | 'desc') => void;+}) {+ return (+ <FilterMenuItem+ isChecked={sortField === field}+ label={label}+ value={`sort-${field}`}+ onSelect={() => onSortChange(field, sortField === field ? (sortDirection === 'asc' ? 'desc' : 'asc') : 'asc')}+ trailing={sortField === field ? (sortDirection === 'asc' ? 'Asc' : 'Desc') : undefined}+ />+ );+});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsxindex 5da484ca1b..5b4f9e8520 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/activity/NodeActivityBar.tsx@@ -1,14 +1,14 @@import { Badge, Box, Collapsible, Flex, HStack, Icon, Spinner, Text } from '@chakra-ui/react';import { Button } from '@workbench/components/ui';import { clearCustomNodeInstallLog, useCustomNodeInstallLog } from '@workbench/customNodes/installLogStore';-import { setNodeActivityExpanded, useNodesUi } from '@workbench/customNodes/nodesUiStore';+import { setNodeActivityExpanded, useNodesUiSelector } from '@workbench/customNodes/nodesUiStore';import { ChevronUpIcon, ListOrderedIcon, Trash2Icon } from 'lucide-react';import { NodeInstallLog } from './NodeInstallLog';/** Persistent, collapsible install activity footer for the nodes manager detail pane. */export const NodeActivityBar = () => {- const { activityExpanded } = useNodesUi();+ const activityExpanded = useNodesUiSelector((snapshot) => snapshot.activityExpanded);const log = useCustomNodeInstallLog();const installingCount = log.filter((entry) => entry.status === 'installing').length;const summary =diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsxindex ce3cf9e681..90c517aecf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/add-nodes/AddNodesView.tsx@@ -3,8 +3,8 @@ import { getApiErrorMessage } from '@workbench/backend/http';import { Button, Field, Scrollable, Tabs, toaster } from '@workbench/components/ui';import { installCustomNodePack } from '@workbench/customNodes/api';import { addCustomNodeInstallLogEntry } from '@workbench/customNodes/installLogStore';-import { refreshCustomNodePacks, useCustomNodesSnapshot } from '@workbench/customNodes/nodesStore';-import { updateNodesUi, useNodesUi, type AddNodesTab } from '@workbench/customNodes/nodesUiStore';+import { refreshCustomNodePacks, useCustomNodesSelector } from '@workbench/customNodes/nodesStore';+import { updateNodesUi, useNodesUiSelector, type AddNodesTab } from '@workbench/customNodes/nodesUiStore';import { FolderOpenIcon, GitBranchIcon } from 'lucide-react';import { useState } from 'react';@@ -14,8 +14,8 @@ import { useState } from 'react';* active sub-tab lives in the nodes UI store so it survives navigation.*/export const AddNodesView = () => {- const { addTab } = useNodesUi();- const { customNodesPath } = useCustomNodesSnapshot();+ const addTab = useNodesUiSelector((snapshot) => snapshot.addTab);+ const customNodesPath = useCustomNodesSelector((snapshot) => snapshot.customNodesPath);return (<Stack gap="3" h="full" minH="0">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsxindex 79d03d69aa..e2a082b0a6 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/detail/NodePackDetail.tsx@@ -4,7 +4,7 @@ import { Badge, Box, Flex, HStack, Icon, Spinner, Stack, Text } from '@chakra-uiimport { Button, ConfirmDialog } from '@workbench/components/ui';import { EmptyState } from '@workbench/components/ui/EmptyState';import { useNodePackActions } from '@workbench/launchpad/nodes/shared/useNodePackActions';-import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { BlocksIcon, TriangleAlertIcon, Trash2Icon } from 'lucide-react';import { useEffect, useMemo, useState } from 'react';@@ -18,7 +18,8 @@ import { NodePreviewCard } from './NodePreviewCard';* share `template.nodePack === pack.name`.*/export const NodePackDetail = ({ onUninstalled, pack }: { onUninstalled: () => void; pack: NodePackInfo }) => {- const { status, templates } = useInvocationTemplatesSnapshot();+ const status = useInvocationTemplatesSelector((snapshot) => snapshot.status);+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);useEffect(() => {ensureInvocationTemplatesLoaded();diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsxindex 005413cd23..681dd8389c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/DetailPane.tsx@@ -1,7 +1,7 @@import { Box, Flex, Icon, Text } from '@chakra-ui/react';import { Scrollable, Tabs } from '@workbench/components/ui';-import { useCustomNodesSnapshot } from '@workbench/customNodes/nodesStore';-import { updateNodesUi, useNodesUi, type NodesManagerTab } from '@workbench/customNodes/nodesUiStore';+import { useCustomNodesSelector } from '@workbench/customNodes/nodesStore';+import { updateNodesUi, useNodesUiSelector, type NodesManagerTab } from '@workbench/customNodes/nodesUiStore';import { NodeActivityBar } from '@workbench/launchpad/nodes/activity/NodeActivityBar';import { AddNodesView } from '@workbench/launchpad/nodes/add-nodes/AddNodesView';import { NodePackDetail } from '@workbench/launchpad/nodes/detail/NodePackDetail';@@ -11,8 +11,9 @@ import { HEADER_MIN_HEIGHT } from './layoutConstants';/** Right side of the nodes manager: selected pack details, Add Nodes, and activity footer. */export const DetailPane = () => {- const { activePackName, activeTab } = useNodesUi();- const { nodePacks } = useCustomNodesSnapshot();+ const activePackName = useNodesUiSelector((snapshot) => snapshot.activePackName);+ const activeTab = useNodesUiSelector((snapshot) => snapshot.activeTab);+ const nodePacks = useCustomNodesSelector((snapshot) => snapshot.nodePacks);const activePack = nodePacks.find((pack) => pack.name === activePackName) ?? null;const detailLabel = activePack?.name ?? 'Node Pack Details';@@ -51,7 +52,7 @@ export const DetailPane = () => {};const DetailTab = ({ packName }: { packName: string | null }) => {- const { nodePacks } = useCustomNodesSnapshot();+ const nodePacks = useCustomNodesSelector((snapshot) => snapshot.nodePacks);const activePack = nodePacks.find((pack) => pack.name === packName) ?? null;if (!activePack) {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsxindex 36d0eee3e3..3eaef1bfa8 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/nodes/manager/LibraryColumn.tsx@@ -1,6 +1,6 @@import { Box, Flex, HStack, Text } from '@chakra-ui/react';-import { useCustomNodesSnapshot } from '@workbench/customNodes/nodesStore';-import { openNodePackDetail, updateNodesUi, useNodesUi } from '@workbench/customNodes/nodesUiStore';+import { useCustomNodesSelector } from '@workbench/customNodes/nodesStore';+import { openNodePackDetail, updateNodesUi, useNodesUiSelector } from '@workbench/customNodes/nodesUiStore';import { NodePackList } from '@workbench/launchpad/nodes/library/NodePackList';import { HEADER_MIN_HEIGHT, PACK_LIBRARY_WIDTH } from './layoutConstants';@@ -8,8 +8,11 @@ import { ReloadNodesButton } from './ReloadNodesButton';/** Persistent custom-node pack list, matching the model manager's library column. */export const LibraryColumn = () => {- const { activePackName, searchTerm } = useNodesUi();- const { error, nodePacks, status } = useCustomNodesSnapshot();+ const activePackName = useNodesUiSelector((snapshot) => snapshot.activePackName);+ const searchTerm = useNodesUiSelector((snapshot) => snapshot.searchTerm);+ const error = useCustomNodesSelector((snapshot) => snapshot.error);+ const nodePacks = useCustomNodesSelector((snapshot) => snapshot.nodePacks);+ const status = useCustomNodesSelector((snapshot) => snapshot.status);return (<Flexdiff --git a/invokeai/frontend/webv2/src/workbench/models/baseIdentity.ts b/invokeai/frontend/webv2/src/workbench/models/baseIdentity.tsindex c6846cf47d..d21ab9b71e 100644--- a/invokeai/frontend/webv2/src/workbench/models/baseIdentity.ts+++ b/invokeai/frontend/webv2/src/workbench/models/baseIdentity.ts@@ -110,7 +110,7 @@ export const getModelBaseColorPalette = (base: ModelBase): string => getModelBasexport const isKnownModelBase = (base: ModelBase): base is KnownModelBase => base in MODEL_BASES;-export const isConvertibleToDiffusers = (model: ModelConfig): boolean =>+export const isConvertibleToDiffusers = (model: Pick<ModelConfig, 'base' | 'format' | 'type'>): boolean =>model.format === 'checkpoint' &&model.type === 'main' &&Boolean(getModelBaseInfo(model.base).supportsDiffusersConversion);diff --git a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsxindex c0a1317660..498020e99b 100644--- a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx@@ -17,9 +17,9 @@ import { Link } from '@tanstack/react-router';import { Button, CloseButton, IconButton, Tooltip } from '@workbench/components/ui';import { getModelBaseColorPalette, getModelBaseLabel } from '@workbench/models/baseIdentity';import { getModelPickerGroups } from '@workbench/models/library';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { formatBytes, getModelTypePluralLabel } from '@workbench/models/taxonomy';-import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { BoxIcon, CheckIcon, ChevronDownIcon, RotateCcwIcon, SearchIcon, XIcon } from 'lucide-react';import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';@@ -63,8 +63,8 @@ export const ModelSelect = ({/** Selected model key, or null. */value: string | null;}) => {- const { enableModelDescriptions } = useWorkbenchPreferences();- const { models } = useModelsSnapshot();+ const enableModelDescriptions = useWorkbenchPreferenceSelector((preferences) => preferences.enableModelDescriptions);+ const models = useModelsSelector((snapshot) => snapshot.models);const [isOpen, setIsOpen] = useState(false);const [searchTerm, setSearchTerm] = useState('');const [selectedBases, setSelectedBases] = useState<ReadonlySet<string>>(EMPTY_BASES);diff --git a/invokeai/frontend/webv2/src/workbench/models/installsStore.ts b/invokeai/frontend/webv2/src/workbench/models/installsStore.tsindex 8af0441a22..581d839f60 100644--- a/invokeai/frontend/webv2/src/workbench/models/installsStore.ts+++ b/invokeai/frontend/webv2/src/workbench/models/installsStore.ts@@ -1,5 +1,4 @@-import { createExternalStore, createListenerChannel } from '@workbench/externalStore';-import { useSyncExternalStore } from 'react';+import { createExternalStore, createKeyedTransientStore } from '@workbench/externalStore';import type { ModelInstallJob, ModelInstallStatus } from './types';@@ -41,14 +40,10 @@ const REFRESH_COALESCE_MS = 250;const OUTCOME_LIMIT = 16;const store = createExternalStore<InstallsSnapshot>({ error: null, jobs: [], status: 'idle' });--let outcomes: InstallOutcome[] = [];+const outcomesStore = createExternalStore<{ outcomes: InstallOutcome[] }>({ outcomes: [] });let nextOutcomeId = 1;-const progressByJobId = new Map<number, InstallDownloadProgress>();--const progressChannel = createListenerChannel();-const outcomesChannel = createListenerChannel();+const progressByJobId = createKeyedTransientStore<number, InstallDownloadProgress>();let inflightRefresh: Promise<void> | null = null;let refreshTimer: ReturnType<typeof setTimeout> | null = null;@@ -64,14 +59,13 @@ export const refreshInstalls = (): Promise<void> => {.then((jobs) => {const activeJobIds = new Set(jobs.map((job) => job.id));- for (const jobId of progressByJobId.keys()) {+ for (const [jobId] of progressByJobId.entries()) {if (!activeJobIds.has(jobId)) {progressByJobId.delete(jobId);}}store.patchSnapshot({ error: null, jobs, status: 'loaded' });- progressChannel.notify();}).catch((error: unknown) => {store.patchSnapshot({@@ -121,9 +115,10 @@ export const addInstallJob = (job: ModelInstallJob): void => {};const recordOutcome = (outcome: Omit<InstallOutcome, 'id'>): void => {- outcomes = [{ ...outcome, id: nextOutcomeId }, ...outcomes].slice(0, OUTCOME_LIMIT);+ outcomesStore.patchSnapshot({+ outcomes: [{ ...outcome, id: nextOutcomeId }, ...outcomesStore.getSnapshot().outcomes].slice(0, OUTCOME_LIMIT),+ });nextOutcomeId += 1;- outcomesChannel.notify();};interface ModelInstallSocketPayload {@@ -176,7 +171,6 @@ export const handleModelInstallSocketEvent = (event: ModelInstallSocketEvent, paif (event === 'model_install_download_progress') {progressByJobId.set(data.id, { bytes: data.bytes ?? 0, totalBytes: data.total_bytes ?? 0 });- progressChannel.notify();const job = store.getSnapshot().jobs.find((candidate) => candidate.id === data.id);@@ -228,36 +222,28 @@ const ACTIVE_STATUSES: ModelInstallStatus[] = ['waiting', 'downloading', 'downloexport const isActiveInstallStatus = (status: ModelInstallStatus): boolean => ACTIVE_STATUSES.includes(status);+export const useInstallsSelector = store.useSelector;+export const useInstallsSnapshot = (): InstallsSnapshot => store.useSnapshot();/*** Source strings (URL, repo id, or path) of jobs currently in flight, cached* per jobs-array so list rows can show an "installing" state by source.*/-let activeSourcesCache: { jobs: ModelInstallJob[]; sources: ReadonlySet<string> } | null = null;--const getActiveInstallSources = (): ReadonlySet<string> => {- const { jobs } = store.getSnapshot();-- if (activeSourcesCache?.jobs !== jobs) {- activeSourcesCache = {- jobs,- sources: new Set(- jobs- .filter((job) => isActiveInstallStatus(job.status) || job.status === 'paused')- .map((job) => describeSource(job.source))- ),- };- }+const areSetsEqual = <Value>(left: ReadonlySet<Value>, right: ReadonlySet<Value>): boolean =>+ left.size === right.size && Array.from(left).every((value) => right.has(value));- return activeSourcesCache.sources;-};+const getActiveInstallSources = (jobs: ModelInstallJob[]): ReadonlySet<string> =>+ new Set(+ jobs+ .filter((job) => isActiveInstallStatus(job.status) || job.status === 'paused')+ .map((job) => describeSource(job.source))+ );export const useActiveInstallSources = (): ReadonlySet<string> =>- useSyncExternalStore(store.subscribe, getActiveInstallSources);+ store.useSelector((snapshot) => getActiveInstallSources(snapshot.jobs), areSetsEqual);export const useInstallProgress = (jobId: number): InstallDownloadProgress | null =>- useSyncExternalStore(progressChannel.subscribe, () => progressByJobId.get(jobId) ?? null);+ progressByJobId.useValue(jobId) ?? null;-export const useInstallOutcomes = (): InstallOutcome[] =>- useSyncExternalStore(outcomesChannel.subscribe, () => outcomes);+export const useInstallOutcomes = (): InstallOutcome[] => outcomesStore.useSelector((snapshot) => snapshot.outcomes);diff --git a/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts b/invokeai/frontend/webv2/src/workbench/models/modelsStore.tsindex 360bb2acaf..fdd31a69ee 100644--- a/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts+++ b/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts@@ -114,4 +114,10 @@ export const markCoverImageChanged = (key: string, hasImage: boolean): void => {});};+export const setModelsSnapshotForTests = (next: Partial<ModelsSnapshot>): void => {+ store.patchSnapshot(next);+};++export const useModelsSelector = store.useSelector;+export const useModelsSnapshot = (): ModelsSnapshot => store.useSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/models/startersStore.ts b/invokeai/frontend/webv2/src/workbench/models/startersStore.tsindex 7b8d7083fb..df668c7262 100644--- a/invokeai/frontend/webv2/src/workbench/models/startersStore.ts+++ b/invokeai/frontend/webv2/src/workbench/models/startersStore.ts@@ -57,4 +57,6 @@ export const refreshStartersIfLoaded = (): void => {}};+export const useStartersSelector = store.useSelector;+export const useStartersSnapshot = (): StartersSnapshot => store.useSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/models/uiStore.ts b/invokeai/frontend/webv2/src/workbench/models/uiStore.tsindex 130fd871dd..57b2c52667 100644--- a/invokeai/frontend/webv2/src/workbench/models/uiStore.ts+++ b/invokeai/frontend/webv2/src/workbench/models/uiStore.ts@@ -112,4 +112,6 @@ export const saveLibraryScrollOffset = (instanceId: string, offset: number): voiexport const getLibraryScrollOffset = (instanceId: string): number =>store.getSnapshot().libraryScrollOffsets[instanceId] ?? 0;+export const useModelsUiSelector = store.useSelector;+export const useModelsUi = (): ModelsUiSnapshot => store.useSnapshot();diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex 130c541b3a..fd8c7f17a1 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -1,11 +1,13 @@import { Dialog, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { Button, CloseButton, Row, Scrollable } from '@workbench/components/ui';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';-import { refreshProjectLibrary, useProjectLibrary, type ProjectSummary } from '@workbench/projects/library';+import { refreshProjectLibrary, useProjectLibrarySelector, type ProjectSummary } from '@workbench/projects/library';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';import { adoptProjectRecord, hydrateProjectFromServer } from '@workbench/projects/syncedPersistence';import { useNotify } from '@workbench/useNotify';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';import { useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { areArraysEqual } from '@workbench/workbenchSelectors';import { ArrowRightIcon, FileUpIcon } from 'lucide-react';import { useEffect, useState } from 'react';@@ -15,10 +17,13 @@ import { useEffect, useState } from 'react';* library and opens it in place — no navigation, the editor stays mounted.*/export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {- const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);+ const projectIds = useWorkbenchSelector(+ (snapshot) => snapshot.state.projects.map((project) => project.id),+ areArraysEqual+ );const dispatch = useWorkbenchDispatch();const notify = useNotify();- const library = useProjectLibrary();+ const summaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);const [busyProjectId, setBusyProjectId] = useState<string | null>(null);useEffect(() => {@@ -27,8 +32,8 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos}}, [isOpen]);- const openProjectIds = new Set(projects.map((project) => project.id));- const available = library.summaries.filter((summary) => !openProjectIds.has(summary.id));+ const openProjectIds = new Set(projectIds);+ const available = summaries.filter((summary) => !openProjectIds.has(summary.id));const openProject = async (summary: ProjectSummary) => {setBusyProjectId(summary.id);@@ -44,6 +49,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosreturn;}+ flushGenerateDrafts();dispatch({ project, type: 'openProject' });onClose();};@@ -60,6 +66,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosconst project = adoptProjectRecord(record);if (project) {+ flushGenerateDrafts();dispatch({ project, type: 'openProject' });onClose();}@@ -114,9 +121,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos))}{available.length === 0 ? (<Text color="fg.muted" fontSize="xs" px="2.5" py="4" textAlign="center">- {library.summaries.length === 0- ? 'No saved projects yet.'- : 'All saved projects are already open.'}+ {summaries.length === 0 ? 'No saved projects yet.' : 'All saved projects are already open.'}</Text>) : null}</Stack>diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsxindex b72b0a2fc2..b777e57698 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx@@ -13,12 +13,33 @@ import {import { exportOpenProject } from '@workbench/projects/projectFile';import { useProjectActions } from '@workbench/projects/useProjectActions';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';+import {+ useActiveProjectSelector,+ useWorkbenchDispatch,+ useWorkbenchSelector,+ useWorkbenchStore,+} from '@workbench/WorkbenchContext';import { FileDownIcon, FolderCogIcon, FolderOpenIcon, PencilIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react';import { useRef, useState, type MouseEvent } from 'react';import { OpenProjectDialog } from './OpenProjectDialog';+interface ProjectTabSummary {+ id: string;+ name: string;+}++const areProjectTabSummariesEqual = (+ left: readonly ProjectTabSummary[],+ right: readonly ProjectTabSummary[]+): boolean =>+ left.length === right.length &&+ left.every((summary, index) => summary.id === right[index]?.id && summary.name === right[index]?.name);++const selectProjectTabSummaries = (projects: readonly Project[]): ProjectTabSummary[] =>+ projects.map(({ id, name }) => ({ id, name }));+/*** Document-style tabs for the open projects (the session), immediately right* of the Invoke control. Tabs are not the library: closing one only removes@@ -31,20 +52,28 @@ import { OpenProjectDialog } from './OpenProjectDialog';* with rename, details, export, close, and delete.*/export const ProjectTabs = () => {- const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);+ const projectTabSummaries = useWorkbenchSelector(+ (snapshot) => selectProjectTabSummaries(snapshot.state.projects),+ areProjectTabSummariesEqual+ );const activeProjectId = useActiveProjectSelector((project) => project.id);+ const store = useWorkbenchStore();const dispatch = useWorkbenchDispatch();const { closeProject, deleteProject } = useProjectActions();- const [menuTarget, setMenuTarget] = useState<{ project: Project; x: number; y: number } | null>(null);- const [renameTarget, setRenameTarget] = useState<Project | null>(null);- const [deleteTarget, setDeleteTarget] = useState<Project | null>(null);+ const [menuTarget, setMenuTarget] = useState<{ project: ProjectTabSummary; x: number; y: number } | null>(null);+ const [renameTarget, setRenameTarget] = useState<ProjectTabSummary | null>(null);+ const [deleteTarget, setDeleteTarget] = useState<ProjectTabSummary | null>(null);const [isOpenDialogVisible, setIsOpenDialogVisible] = useState(false);+ const getProject = (projectId: string): Project | null =>+ store.getState().projects.find((project) => project.id === projectId) ?? null;+const onSwitchProject = (projectId: string) => {+ flushGenerateDrafts();dispatch({ projectId, type: 'switchProject' });};- const openContextMenu = (project: Project, event: MouseEvent) => {+ const openContextMenu = (project: ProjectTabSummary, event: MouseEvent) => {event.preventDefault();setMenuTarget({ project, x: event.clientX, y: event.clientY });};@@ -53,7 +82,7 @@ export const ProjectTabs = () => {<><Tabs.Root minW="max-content" variant="subtle" value={activeProjectId} h="full" w="full"><Tabs.List flex="1 1 auto" h="full" py="1">- {projects.map((project) => (+ {projectTabSummaries.map((project) => (<Tabs.Triggerkey={project.id}value={project.id}@@ -71,7 +100,11 @@ export const ProjectTabs = () => {aria-label={`Close ${project.name}`}onClick={(event) => {event.stopPropagation();- closeProject(project);+ const currentProject = getProject(project.id);++ if (currentProject) {+ closeProject(currentProject);+ }}}/></Tabs.Trigger>@@ -84,7 +117,10 @@ export const ProjectTabs = () => {size="xs"variant="ghost"alignSelf="center"- onClick={() => dispatch({ type: 'createProject' })}+ onClick={() => {+ flushGenerateDrafts();+ dispatch({ type: 'createProject' });+ }}><PlusIcon /></IconButton>@@ -106,7 +142,13 @@ export const ProjectTabs = () => {<ProjectTabContextMenutarget={menuTarget}onClose={() => setMenuTarget(null)}- onCloseProject={closeProject}+ onCloseProject={(project) => {+ const currentProject = getProject(project.id);++ if (currentProject) {+ closeProject(currentProject);+ }+ }}onDelete={(project) => setDeleteTarget(project)}onRename={(project) => setRenameTarget(project)}/>@@ -128,11 +170,15 @@ export const ProjectTabs = () => {onClose={() => setDeleteTarget(null)}onConfirm={async () => {if (deleteTarget) {- await deleteProject(deleteTarget);+ const currentProject = getProject(deleteTarget.id);++ if (currentProject) {+ await deleteProject(currentProject);+ }}}}/>- <OpenProjectDialog isOpen={isOpenDialogVisible} onClose={() => setIsOpenDialogVisible(false)} />+ {isOpenDialogVisible ? <OpenProjectDialog isOpen onClose={() => setIsOpenDialogVisible(false)} /> : null}</>);};@@ -145,18 +191,26 @@ const ProjectTabContextMenu = ({target,}: {onClose: () => void;- onCloseProject: (project: Project) => void;- onDelete: (project: Project) => void;- onRename: (project: Project) => void;- target: { project: Project; x: number; y: number } | null;+ onCloseProject: (project: ProjectTabSummary) => void;+ onDelete: (project: ProjectTabSummary) => void;+ onRename: (project: ProjectTabSummary) => void;+ target: { project: ProjectTabSummary; x: number; y: number } | null;}) => {const dispatch = useWorkbenchDispatch();+ const store = useWorkbenchStore();const openWorkbenchWidget = useOpenWorkbenchWidget();const targetRef = useRef(target);targetRef.current = target;- const openProjectDetails = (project: Project) => {+ const openProjectDetails = (projectSummary: ProjectTabSummary) => {+ const project = store.getState().projects.find((candidate) => candidate.id === projectSummary.id);++ if (!project) {+ return;+ }++ flushGenerateDrafts();dispatch({ projectId: project.id, type: 'switchProject' });// Reveal the Project panel wherever the project already shows it; default@@ -205,7 +259,16 @@ const ProjectTabContextMenu = ({<Icon as={FolderCogIcon} boxSize="3.5" />Project details</Menu.Item>- <Menu.Item value="export" onClick={() => exportOpenProject(target.project)}>+ <Menu.Item+ value="export"+ onClick={() => {+ const project = store.getState().projects.find((candidate) => candidate.id === target.project.id);++ if (project) {+ exportOpenProject(project);+ }+ }}+ ><Icon as={FileDownIcon} boxSize="3.5" />Export</Menu.Item>diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 83eee7724e..1c3654d700 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -69,6 +69,8 @@ const sortSummaries = (summaries: ProjectSummary[]): ProjectSummary[] =>export const useProjectLibrary = (): ProjectLibrarySnapshot => store.useSnapshot();+export const useProjectLibrarySelector = store.useSelector;+export const getProjectLibrary = (): ProjectLibrarySnapshot => store.getSnapshot();/** Adopt summaries already fetched elsewhere (the workbench boot pass). */diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex aff79d3a9d..1ab80c4f76 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -27,6 +27,8 @@ const store = createExternalStore<ProjectSyncSnapshot>({export const useProjectSync = (): ProjectSyncSnapshot => store.useSnapshot();+export const useProjectSyncSelector = store.useSelector;+export const reportProjectSync = (update: Omit<ProjectSyncSnapshot, 'lastSyncedAt'>): void => {store.setSnapshot({...update,diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 08a0f70bc4..af0a9b8729 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -2,7 +2,8 @@ import type { Project } from '@workbench/types';import { useNavigate } from '@tanstack/react-router';import { useNotify } from '@workbench/useNotify';-import { useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';+import { useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';import { deleteLibraryProject } from './library';import {@@ -27,13 +28,15 @@ export const useProjectActions = (): {closeProject: (project: Project) => void;deleteProject: (project: Project) => Promise<void>;} => {- const state = useWorkbenchSelector((snapshot) => snapshot.state);+ const store = useWorkbenchStore();const dispatch = useWorkbenchDispatch();const navigate = useNavigate();const notify = useNotify();/** When the last tab goes, the session empties and Home takes over. */const leaveEditorIfLast = (projectId: string): boolean => {+ const state = store.getState();+if (state.projects.some((project) => project.id !== projectId)) {return false;}@@ -45,7 +48,11 @@ export const useProjectActions = (): {};const closeProject = (project: Project): void => {- void flushProjectToServer(project).finally(() => {+ flushGenerateDrafts();++ const projectToFlush = store.getState().projects.find((candidate) => candidate.id === project.id) ?? project;++ void flushProjectToServer(projectToFlush).finally(() => {releaseProjectSync(project.id);});@@ -57,6 +64,7 @@ export const useProjectActions = (): {};const deleteProject = async (project: Project): Promise<void> => {+ flushGenerateDrafts();// Marked before the request so an in-flight autosave cannot recreate the// project server-side between the DELETE and the tab closing.markProjectDeleted(project.id);diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex 2a352e81ab..4c944e169d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -32,6 +32,7 @@ import { Button, CloseButton, IconButton, ConfirmDialog, Tabs, Tooltip } from '@import { registerHotkeyModalLayer } from '@workbench/hotkeys';import { syncedWorkbenchPersistence } from '@workbench/projects/syncedPersistence';import {+ shallowEqual,useOptionalWorkbenchDispatch,useOptionalWorkbenchSelector,useOptionalWorkbenchStore,@@ -87,7 +88,7 @@ const updatePreferences = (patch: Partial<WorkbenchPreferences>): void => {* `openWorkbenchSettings('workflow')`.*/export const SettingsButton = () => {- const { isOpen } = settingsDialogStore.useSnapshot();+ const isOpen = settingsDialogStore.useSelector((snapshot) => snapshot.isOpen);return (<>@@ -225,7 +226,7 @@ const SettingsTabs = () => {},];const tabs = SETTINGS_TABS.filter((tab) => tab.condition !== false);- const { sectionId } = settingsDialogStore.useSnapshot();+ const sectionId = settingsDialogStore.useSelector((snapshot) => snapshot.sectionId);const activeSectionId = tabs.some((tab) => tab.value === sectionId) ? sectionId : 'appearance';return (@@ -397,7 +398,11 @@ const BehaviorSection = () => {};const ProjectSection = () => {- const activeProject = useOptionalWorkbenchSelector<Project | null>((snapshot) => snapshot.activeProject, null);+ const activeProject = useOptionalWorkbenchSelector<Pick<Project, 'name' | 'settings'> | null>(+ (snapshot) => ({ name: snapshot.activeProject.name, settings: snapshot.activeProject.settings }),+ null,+ shallowEqual+ );const dispatch = useOptionalWorkbenchDispatch();if (!activeProject || !dispatch) {diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex e0751b9be8..136a2a952e 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -11,7 +11,6 @@ import { getUserStorageScope } from '@workbench/auth/session';import { createExternalStore } from '@workbench/externalStore';import { deleteClientStateValue, getClientStateValue, setClientStateValue } from '@workbench/projects/api';import { fetchSessionBlob } from '@workbench/projects/session';-import { useSyncExternalStore } from 'react';const SETTINGS_BASE_STORAGE_KEY = 'invokeai:v7:webv2:settings';const LEGACY_WORKBENCH_BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';@@ -405,14 +404,27 @@ export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {export const useWorkbenchSettings = (): WorkbenchSettingsSnapshot => store.useSnapshot();-export const useWorkbenchPreferences = (): WorkbenchPreferences => store.useSnapshot().preferences;+export const useWorkbenchPreferences = (): WorkbenchPreferences =>+ store.useSelector((snapshot) => snapshot.preferences);++type EqualityFn<T> = (left: T, right: T) => boolean;++export const useWorkbenchSettingsSelector = <Selected>(+ selector: (snapshot: WorkbenchSettingsSnapshot) => Selected,+ isEqual: EqualityFn<Selected> = Object.is+): Selected => store.useSelector(selector, isEqual);++export const useWorkbenchPreferenceSelector = <Selected>(+ selector: (preferences: WorkbenchPreferences) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected => useWorkbenchSettingsSelector((snapshot) => selector(snapshot.preferences), isEqual);export const getWorkbenchPreferences = (): WorkbenchPreferences => store.getSnapshot().preferences;export const getWorkbenchReduceMotion = (): boolean => store.getSnapshot().preferences.reduceMotion;export const useWorkbenchReduceMotion = (): boolean =>- useSyncExternalStore(store.subscribe, getWorkbenchReduceMotion, getWorkbenchReduceMotion);+ store.useSelector((snapshot) => snapshot.preferences.reduceMotion);export const patchWorkbenchPreferences = async (preferences: Partial<WorkbenchPreferences>): Promise<void> => {const next = normalizeWorkbenchPreferences({ ...store.getSnapshot().preferences, ...preferences });diff --git a/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx b/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsxindex 8cf0d81c47..e66d3012e1 100644--- a/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/BottomPanel.tsx@@ -1,11 +1,15 @@-import { MissingWidgetFrame, WidgetRenderer } from '@workbench/widget-frame';+import { MissingWidgetFrame, WidgetRendererById } from '@workbench/widget-frame';+import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';import { getWidgetById } from '@workbench/widgetRegistry';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';export const BottomPanel = () => {const panels = useActiveProjectSelector((project) => project.layout.panels);const bottomRegion = useActiveProjectSelector((project) => project.widgetRegions.bottom);- const instance = useActiveProjectSelector((project) => project.widgetInstances[bottomRegion.activeInstanceId]);+ const instance = useActiveProjectSelector(+ (project) => project.widgetInstances[bottomRegion.activeInstanceId],+ areWidgetRenderInstancesEqual+ );const widget = instance ? getWidgetById(instance.typeId) : undefined;const View = widget?.manifest.view;const canShowBottomPanel =@@ -23,5 +27,5 @@ export const BottomPanel = () => {return <MissingWidgetFrame label={widget?.manifest.labelText ?? bottomRegion.activeInstanceId} region="bottom" />;}- return <WidgetRenderer instance={instance} widget={widget} presentation="expanded" region="bottom" />;+ return <WidgetRendererById instanceId={instance.id} widget={widget} presentation="expanded" region="bottom" />;};diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex 1dff15f6f8..1299db86bd 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -1,5 +1,9 @@import type { WidgetRegionDropState } from '@workbench/widgetDnd';-import type { PlacedWidgetRegionItem, WidgetRegionItem } from '@workbench/widgetRegionViewModel';+import type {+ PlacedWidgetRegionItem,+ WidgetPlacementInstanceMeta,+ WidgetRegionItem,+} from '@workbench/widgetRegionViewModel';import { Box, Flex, Text } from '@chakra-ui/react';import { horizontalListSortingStrategy } from '@dnd-kit/sortable';@@ -9,7 +13,7 @@ import { WidgetIcon } from '@workbench/iconResolver';import {WidgetEnableMenu,WidgetInstanceContextMenu,- WidgetRenderer,+ WidgetRendererById,WidgetStrip,useWidgetSortable,type WidgetEnableMenuItem,@@ -26,13 +30,12 @@ import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { type MouseEvent, useState } from 'react';-type CenterWidgetItem = PlacedWidgetRegionItem;+type CenterWidgetItem = PlacedWidgetRegionItem<WidgetPlacementInstanceMeta>;/** Center work area: the view tab strip plus the active registered center view. */export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState }) => {const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const centerRegion = useActiveProjectSelector((project) => project.widgetRegions.center);- const widgetInstances = useActiveProjectSelector((project) => project.widgetInstances);const dispatch = useWorkbenchDispatch();const [enableMenuTarget, setEnableMenuTarget] = useState<{ x: number; y: number } | null>(null);const [instanceMenuTarget, setInstanceMenuTarget] = useState<WidgetInstanceContextMenuTarget | null>(null);@@ -40,7 +43,7 @@ export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState })const centerRegionViewModel = createWidgetRegionViewModelFromState({region: 'center',regionState: centerRegion,- widgetInstances,+ widgetInstances: placementProject.widgetInstances,widgets: getWidgetsForRegion('center'),});const centerWidgetMenuItems = getWidgetRegionItems(centerRegionViewModel);@@ -116,7 +119,7 @@ export const CenterArea = ({ dropState }: { dropState: WidgetRegionDropState })<Box flex="1" />{centerToolbarItems.map((item) => (<Flex key={item.id} align="center" h="full">- <WidgetRenderer instance={item.instance} widget={item.widget} presentation="compact" region="center" />+ <WidgetRendererById instanceId={item.id} widget={item.widget} presentation="compact" region="center" /></Flex>))}<WidgetEnableMenu@@ -194,7 +197,7 @@ const CenterViewSlot = ({return <FallbackCenterView label="Center widget unavailable" />;}- return <WidgetRenderer instance={instance} widget={widget} region="center" />;+ return <WidgetRendererById instanceId={instance.id} widget={widget} region="center" />;};const FallbackCenterView = ({ label }: { label: string }) => (diff --git a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsxindex d71ce24d65..b840c31790 100644--- a/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/Panels.tsx@@ -1,6 +1,7 @@import type { WidgetInstanceId, WorkbenchRegion } from '@workbench/types';-import { MissingWidgetFrame, WidgetRenderer } from '@workbench/widget-frame';+import { MissingWidgetFrame, WidgetRendererById } from '@workbench/widget-frame';+import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';import { getWidgetById } from '@workbench/widgetRegistry';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';@@ -20,7 +21,10 @@ const panelRegions = {} as const satisfies Record<string, WorkbenchRegion>;const WidgetPanelSlot = ({ instanceId, panel }: { instanceId: WidgetInstanceId; panel: keyof typeof panelRegions }) => {- const instance = useActiveProjectSelector((project) => project.widgetInstances[instanceId]);+ const instance = useActiveProjectSelector(+ (project) => project.widgetInstances[instanceId],+ areWidgetRenderInstancesEqual+ );const widget = instance ? getWidgetById(instance.typeId) : undefined;const View = widget?.manifest.view;const region = panelRegions[panel];@@ -29,5 +33,5 @@ const WidgetPanelSlot = ({ instanceId, panel }: { instanceId: WidgetInstanceId;return <MissingWidgetFrame label={widget?.manifest.labelText ?? instanceId} region={region} />;}- return <WidgetRenderer instance={instance} widget={widget} region={region} />;+ return <WidgetRendererById instanceId={instance.id} widget={widget} region={region} />;};diff --git a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsxindex 81d94fbda9..cf2bce20b1 100644--- a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx@@ -1,6 +1,6 @@import type { WidgetInstanceId } from '@workbench/types';import type { WidgetRegionDropState } from '@workbench/widgetDnd';-import type { PlacedWidgetRegionItem } from '@workbench/widgetRegionViewModel';+import type { PlacedWidgetRegionItem, WidgetPlacementInstanceMeta } from '@workbench/widgetRegionViewModel';import { Box } from '@chakra-ui/react';import { horizontalListSortingStrategy } from '@dnd-kit/sortable';@@ -8,7 +8,7 @@ import { Row, Tooltip } from '@workbench/components/ui';import {WidgetEnableMenu,WidgetInstanceContextMenu,- WidgetRenderer,+ WidgetRendererById,WidgetStrip,useWidgetSortable,type WidgetEnableMenuItem,@@ -26,21 +26,20 @@ import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { type KeyboardEvent, type MouseEvent, useState } from 'react';-interface BottomWidgetItem extends PlacedWidgetRegionItem {+interface BottomWidgetItem extends PlacedWidgetRegionItem<WidgetPlacementInstanceMeta> {isExpandable: boolean;}export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) => {const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const bottomRegion = useActiveProjectSelector((project) => project.widgetRegions.bottom);- const widgetInstances = useActiveProjectSelector((project) => project.widgetInstances);const dispatch = useWorkbenchDispatch();const [enableMenuTarget, setEnableMenuTarget] = useState<{ x: number; y: number } | null>(null);const [instanceMenuTarget, setInstanceMenuTarget] = useState<WidgetInstanceContextMenuTarget | null>(null);const bottomRegionViewModel = createWidgetRegionViewModelFromState({region: 'bottom',regionState: bottomRegion,- widgetInstances,+ widgetInstances: placementProject.widgetInstances,widgets: getWidgetsForRegion('bottom'),});const items = getWidgetRegionItems(bottomRegionViewModel);@@ -184,7 +183,7 @@ const CompactBottomWidget = ({onContextMenu={(event) => onContextMenu(item, event)}>{item.instance ? (- <WidgetRenderer instance={item.instance} widget={item.widget} presentation="compact" region="bottom" />+ <WidgetRendererById instanceId={item.id} widget={item.widget} presentation="compact" region="bottom" />) : null}</Row></Box>@@ -208,7 +207,7 @@ const CompactBottomWidget = ({closeDelay={80}content={item.instance ? (- <WidgetRenderer instance={item.instance} widget={item.widget} presentation="tooltip" region="bottom" />+ <WidgetRendererById instanceId={item.id} widget={item.widget} presentation="tooltip" region="bottom" />) : null}openDelay={250}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsxindex f271c58138..c9043592b1 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx@@ -1,7 +1,6 @@import { NumberInput } from '@chakra-ui/react';import { MIN_BATCH_COUNT, sanitizeBatchCount } from '@workbench/generation/batch';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useWidgetValuesSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';const getBatchCount = (values: Record<string, unknown>): number => {const batchCount = values.batchCount;@@ -10,9 +9,8 @@ const getBatchCount = (values: Record<string, unknown>): number => {};export const BatchCountField = () => {- const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));+ const batchCount = useWidgetValuesSelector('generate', getBatchCount);const dispatch = useWorkbenchDispatch();- const batchCount = getBatchCount(generateValues);return (<NumberInput.Rootdiff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 12a49eb30d..a05e27d242 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -1,34 +1,32 @@-import type { InvocationSourceId, Project, ResultDestination } from '@workbench/types';+import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/types';import { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';import { Button, IconButton, Tooltip } from '@workbench/components/ui';import { sanitizeBatchCount } from '@workbench/generation/batch';import {formatRoute,+ createInvocationRouteInputSelector,getDestinationLabel,invocationSources,isInvocationRouteValid,resolveInvocationRoute,+ resolveInvocationRouteInput,resultDestinations,} from '@workbench/invocation';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProject, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';+import {+ useActiveProjectSelector,+ useWorkbenchDispatch,+ useWorkbenchSelector,+ useWorkbenchStore,+} from '@workbench/WorkbenchContext';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';import { useEffect, useRef } from 'react';-/**- * Fixed-width global Invoke control.- *- * The defining Phase 1 requirement: the primary label stays `Invoke`, the- * secondary line shows the resolved `Source → Destination` route with a compact- * lock indicator, and the control reserves stable horizontal space so project- * tabs never shift when the route text changes. The caret opens the Invocation- * Controller menu (source / destination / lock), which is wired to project-owned- * state even though full invocation lands in Phase 4.- */-const CONTROL_WIDTH = '12rem';+const CONTROL_WIDTH = '10rem';+const selectInvocationRouteInput = createInvocationRouteInputSelector();const getBatchCount = (values: Record<string, unknown>): number => {const batchCount = values.batchCount;@@ -46,17 +44,19 @@ const compactBlockingReason = (reason: string): string => {const InvokeTooltipContent = ({blockingReasons,+ generateValues,+ invocation,isValid,- project,}: {blockingReasons: string[];+ generateValues: Record<string, unknown>;+ invocation: InvocationRoute;isValid: boolean;- project: Project;}) => {- const batchCount = getBatchCount(getProjectWidgetValues(project, 'generate'));- const destination = getDestinationLabel(project.invocation.destination);+ const batchCount = getBatchCount(generateValues);+ const destination = getDestinationLabel(invocation.destination);const summary =- project.invocation.sourceId === 'generate'+ invocation.sourceId === 'generate'? `1 prompt × ${batchCount} iteration${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`: `Workflow × ${batchCount} run${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`;@@ -97,32 +97,31 @@ const InvokeTooltipContent = ({};export const InvokeControl = () => {- const activeProject = useActiveProject();+ const routeInput = useActiveProjectSelector(selectInvocationRouteInput);const dispatch = useWorkbenchDispatch();+ const store = useWorkbenchStore();const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);- const { models, status: modelsStatus } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const availabilityModels = modelsStatus === 'loaded' ? models : undefined;- const { invocation } = activeProject;+ const { invocation } = routeInput;// Project-graph route validation reads the invocation templates imperatively;// subscribing here keeps the resolved route live while they load.- useInvocationTemplatesSnapshot();+ useInvocationTemplatesSelector((snapshot) => snapshot.status);- const resolvedRoute = resolveInvocationRoute(activeProject, 'global', activeProject.invocation, availabilityModels);+ const resolvedRoute = resolveInvocationRouteInput(routeInput, 'global', routeInput.invocation, availabilityModels);const isLocked = invocation.sourceLocked || invocation.destinationLocked;const isConnected = backendConnectionStatus === 'connected';- // Legacy parity: the queue button disables with the full list of reasons,- // including a disconnected backend.+const blockingReasons = [...(isConnected ? [] : ['The backend is disconnected.']),...resolvedRoute.validationReasons,];const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));- const resolvedRouteRef = useRef(resolvedRoute);const modelsRef = useRef(availabilityModels);- resolvedRouteRef.current = resolvedRoute;modelsRef.current = availabilityModels;useEffect(() => {@@ -130,14 +129,23 @@ export const InvokeControl = () => {}, []);const onInvoke = () => {- if (!isValid) {+ flushGenerateDrafts();+ const snapshot = store.getSnapshot();+ const postFlushRoute = resolveInvocationRoute(+ snapshot.activeProject,+ 'global',+ snapshot.activeProject.invocation,+ modelsRef.current+ );++ if (!isInvocationRouteValid(postFlushRoute) || snapshot.state.backendConnection.status !== 'connected') {return;}dispatch({backendSupportsCancellation: true,- models: availabilityModels,- route: resolvedRouteRef.current,+ models: modelsRef.current,+ route: postFlushRoute,type: 'submitResolvedInvocationSnapshot',});};@@ -148,13 +156,17 @@ export const InvokeControl = () => {<Group attached><Tooltipcontent={- <InvokeTooltipContent blockingReasons={blockingReasons} isValid={isValid} project={activeProject} />+ <InvokeTooltipContent+ blockingReasons={blockingReasons}+ generateValues={routeInput.generateValues}+ invocation={invocation}+ isValid={isValid}+ />}contentProps={{ p: '0' }}openDelay={200}showArrow>- {/* aria-disabled (not disabled) keeps hover alive so the reasons tooltip can show. */}<Buttonaria-disabled={!isValid}colorPalette="brand"diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsxindex 982a9acb1c..a9084b955a 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetMenu.tsx@@ -4,8 +4,8 @@ import type { MouseEvent } from 'react';import { HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { Button, ConfirmDialog, IconButton, MenuContent, RenameDialog } from '@workbench/components/ui';import { layoutPresets } from '@workbench/layoutPresets';-import { doesProjectMatchLayoutPreset } from '@workbench/layoutPresetSnapshots';-import { useActiveProject, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { areLayoutPresetSnapshotsEqual, createLayoutPresetSnapshot } from '@workbench/layoutPresetSnapshots';+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { CheckIcon, ChevronDownIcon, EllipsisVerticalIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';import { useState } from 'react';@@ -22,7 +22,7 @@ const createCustomPresetId = (): string =>/** Global layout preset registry surfaced as a menu. */export const LayoutPresetMenu = () => {- const activeProject = useActiveProject();+ const activeLayoutSnapshot = useActiveProjectSelector(createLayoutPresetSnapshot, areLayoutPresetSnapshotsEqual);const customPresets = useWorkbenchSelector((snapshot) => snapshot.state.account.customLayoutPresets ?? []);const dispatch = useWorkbenchDispatch();const [isAddOpen, setIsAddOpen] = useState(false);@@ -30,7 +30,9 @@ export const LayoutPresetMenu = () => {const [deleteTarget, setDeleteTarget] = useState<LayoutPreset | null>(null);const [actionTarget, setActionTarget] = useState<PresetActionTarget | null>(null);const allPresets = [...layoutPresets, ...customPresets];- const matchingPreset = allPresets.find((preset) => doesProjectMatchLayoutPreset(activeProject, preset));+ const matchingPreset = allPresets.find((preset) =>+ areLayoutPresetSnapshotsEqual(activeLayoutSnapshot, preset.snapshot)+ );const canAddCurrentLayout = !matchingPreset;const triggerLabel = matchingPreset?.label ?? 'Custom';diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsxindex c3cd5908be..db2367c6df 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueActions.tsx@@ -1,5 +1,3 @@-import type { QueueItem } from '@workbench/types';-import { Group, Icon, Menu, Portal } from '@chakra-ui/react';import { IconButton, Tooltip } from '@workbench/components/ui';import {@@ -10,58 +8,20 @@ import {} from '@workbench/generation/api';import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { getQueueActionState } from '@workbench/widgets/queue/queueViewModel';import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { ChevronDownIcon, ListOrderedIcon, PauseIcon, PlayIcon, XIcon } from 'lucide-react';-const isCancellableQueueItem = (item: QueueItem): boolean =>- item.cancellable && (item.status === 'pending' || item.status === 'running');--const compareQueueSubmittedAt = (left: QueueItem, right: QueueItem): number => {- const leftTime = Date.parse(left.snapshot.submittedAt);- const rightTime = Date.parse(right.snapshot.submittedAt);-- return (Number.isFinite(leftTime) ? leftTime : 0) - (Number.isFinite(rightTime) ? rightTime : 0);-};--const getCurrentQueueActionItem = (queueItems: QueueItem[]): QueueItem | null => {- const runningItem = queueItems.filter(isCancellableQueueItem).find((item) => item.status === 'running');-- if (runningItem) {- return runningItem;- }-- return queueItems.filter(isCancellableQueueItem).sort(compareQueueSubmittedAt)[0] ?? null;-};--const getOpenBackendSlotCount = (item: QueueItem): number => {- if (!item.backendItemIds?.length) {- return item.status === 'pending' || item.status === 'running' ? 1 : 0;- }-- const terminalBackendItemIds = new Set([- ...(item.completedBackendItemIds ?? []),- ...(item.cancelledBackendItemIds ?? []),- ]);-- return item.backendItemIds.filter((backendItemId) => !terminalBackendItemIds.has(backendItemId)).length;-};-/** Queue cancel cluster and processor actions. */export const QueueActions = () => {const activeProjectId = useWorkbenchSelector((snapshot) => snapshot.state.activeProjectId);const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);- const queueItems = useActiveProjectSelector((project) => project.queue.items);+ const { cancellableCount, currentItemId, hasPendingQueueWork, hasRunningItem } = useActiveProjectSelector((project) =>+ getQueueActionState(project.queue.items)+ );const dispatch = useWorkbenchDispatch();const notify = useNotify();const openWorkbenchWidget = useOpenWorkbenchWidget();- const currentItem = getCurrentQueueActionItem(queueItems);- const hasRunningItem = queueItems.some((item) => isCancellableQueueItem(item) && item.status === 'running');- const cancellableCount = queueItems.filter(isCancellableQueueItem).length;- const hasPendingQueueWork = queueItems.some((item) =>- item.id === currentItem?.id- ? item.status === 'running' && getOpenBackendSlotCount(item) > 1- : item.status === 'pending'- );const isConnected = backendConnectionStatus === 'connected';const cancelCurrent = () => {@@ -84,7 +44,7 @@ export const QueueActions = () => {cancelAllExceptCurrentQueueItems().then(() => {dispatch({- currentQueueItemId: currentItem?.id ?? null,+ currentQueueItemId: currentItemId,projectId: activeProjectId,type: 'cancelAllQueueItemsExceptCurrent',});diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex c1228b18e5..3c0d613f42 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -108,6 +108,13 @@ export interface WidgetInstanceContract {createdAt: string;}+export interface WidgetInstanceRuntimeMeta {+ id: WidgetInstanceId;+ typeId: WidgetTypeId;+ title?: string;+ createdAt: string;+}+export interface GraphBearingSurfaceContract {surfaceId: string;widgetId: WidgetId;@@ -122,7 +129,8 @@ export interface GraphBearingSurfaceContract {export interface WidgetViewProps {region: WorkbenchRegion;manifest: WidgetManifest;- instance: WidgetInstanceContract;+ /** Chrome metadata only. Read reactive widget values through `runtime.state`. */+ instance: WidgetInstanceRuntimeMeta;runtime: WidgetRuntimeApi;presentation?: 'compact' | 'expanded' | 'tooltip';}@@ -156,9 +164,7 @@ export interface WidgetRuntimeApi<State extends Record<string, unknown> = RecordinstanceId: WidgetInstanceId;typeId: WidgetTypeId;region: WorkbenchRegion;- state: State;- patchState: (values: Partial<State>) => void;- setState: (values: State) => void;+ state: WidgetRuntimeStateApi<State>;commands: WidgetCommandApi;hotkeys: WidgetHotkeyApi;menus: WidgetMenuApi;@@ -168,8 +174,30 @@ export interface WidgetRuntimeApi<State extends Record<string, unknown> = Recordworkbench: WidgetWorkbenchApi;}+export interface WidgetRuntimeStateApi<State extends Record<string, unknown> = Record<string, unknown>> {+ getSnapshot: () => Readonly<State>;+ useSelector: <Selected>(+ selector: (state: Readonly<State>) => Selected,+ isEqual?: (left: Selected, right: Selected) => boolean+ ) => Selected;+ patch: (values: Partial<State>) => void;+ set: (values: State) => void;+}++export interface WidgetContributionSource {+ instanceId: WidgetInstanceId;+ projectId: string;+ region: WorkbenchRegion;+ typeId: WidgetTypeId;+}+export interface WidgetCommandApi {execute: (commandId: string, ...args: unknown[]) => Promise<unknown>;+ executeForSource: (+ commandId: string,+ source: WidgetContributionSource | null,+ ...args: unknown[]+ ) => Promise<unknown>;register: (command: WidgetCommandContribution) => () => void;}@@ -177,6 +205,7 @@ export interface WidgetCommandContribution {id: string;title: string;handler: (...args: unknown[]) => unknown | Promise<unknown>;+ source?: WidgetContributionSource;}export interface WidgetHotkeyApi {@@ -190,7 +219,7 @@ export interface WidgetHotkeyContribution {title: string;description?: string;scope?: 'focused-region' | 'global' | 'instance' | 'widget';- source?: { instanceId: WidgetInstanceId; region: WorkbenchRegion; typeId: WidgetTypeId };+ source?: WidgetContributionSource;preventDefault?: boolean;allowInEditable?: boolean;}@@ -202,6 +231,7 @@ export interface WidgetMenuApi {export interface WidgetMenuContribution {id: string;items: Array<{ commandId: string; group?: string }>;+ source?: WidgetContributionSource;}export interface WidgetCommandPaletteApi {diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsxindex 41a73f70a8..81b28ac24b 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx@@ -2,7 +2,7 @@ import type {GraphBearingSurfaceContract,GraphContract,Project,- WidgetInstanceContract,+ WidgetInstanceRuntimeMeta,WidgetManifest,WidgetRuntimeApi,WorkbenchRegion,@@ -12,7 +12,7 @@ import { Icon, Menu, Portal, Text } from '@chakra-ui/react';import { IconButton } from '@workbench/components/ui';import { GraphPreviewDialog } from '@workbench/graph-preview';import { createGraphBearingSurface } from '@workbench/graphSurfaces';-import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { compileProjectGraph } from '@workbench/workflows/buildGraph';import { getInvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { GitBranchIcon, MoreHorizontalIcon, TargetIcon } from 'lucide-react';@@ -52,9 +52,9 @@ const GraphSurfaceMenuItems = ({surface: GraphBearingSurfaceContract;onPreview: () => void;}) => {- const activeProject = useActiveProject();+ const activeSourceId = useActiveProjectSelector((project) => project.invocation.sourceId);const dispatch = useWorkbenchDispatch();- const isActiveSource = activeProject.invocation.sourceId === surface.sourceId;+ const isActiveSource = activeSourceId === surface.sourceId;return (<Menu.ItemGroup>@@ -89,12 +89,15 @@ export const WidgetActionsMenu = ({region,runtime,}: {- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;manifest: WidgetManifest;region: WorkbenchRegion;runtime: WidgetRuntimeApi;}) => {- const activeProject = useActiveProject();+ const activeProject = useActiveProjectSelector(+ (project) => ({ projectGraph: project.projectGraph, widgetGraphs: project.widgetGraphs }),+ shallowEqual+ ) as Project;const [isPreviewOpen, setIsPreviewOpen] = useState(false);const surface = manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region) : null;const HeaderMenu = manifest.headerMenu;@@ -107,7 +110,7 @@ export const WidgetActionsMenu = ({// The project graph mirrors the editable document, so the preview can reuse// the editor's node positions instead of auto-layouting.const positionHints =- surface?.sourceId === 'project-graph'+ isPreviewOpen && surface?.sourceId === 'project-graph'? Object.fromEntries(activeProject.projectGraph.nodes.map((node) => [node.id, node.position])): undefined;@@ -131,7 +134,7 @@ export const WidgetActionsMenu = ({</Menu.Positioner></Portal></Menu.Root>- {surface ? (+ {surface && isPreviewOpen ? (<GraphPreviewDialoggraph={previewGraph}graphId={surface.graphId}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsxindex ccc7c8eea6..abdbfa00bc 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx@@ -1,6 +1,6 @@import type {WidgetInstanceId,- WidgetInstanceContract,+ WidgetInstanceRuntimeMeta,WidgetManifest,WidgetRegion,WidgetRuntimeApi,@@ -134,6 +134,7 @@ export const WidgetPanelFrame = ({overflow="hidden"minW="0"data-hotkey-widget-instance-id={instanceId}+ data-hotkey-widget-region={region}data-hotkey-widget-type-id={typeId}{...focusRegionProps}{...(isBottom ? { h: `${displaySizePx}px`, w: 'full' } : { h: 'full', w: `${displaySizePx}px` })}@@ -172,7 +173,7 @@ export const WidgetHeader = ({runtime,}: {actions?: ReactNode;- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;manifest: WidgetManifest;region: WorkbenchRegion;runtime: WidgetRuntimeApi;diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsxindex 678e5c0747..e0dc0983ce 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx@@ -1,25 +1,63 @@-import type { RegisteredWidget, WidgetInstanceContract, WidgetRuntimeApi, WidgetViewProps } from '@workbench/types';+import type {+ RegisteredWidget,+ WidgetInstanceContract,+ WidgetInstanceRuntimeMeta,+ WidgetRuntimeApi,+ WidgetViewProps,+} from '@workbench/types';import { Box, Flex, Text } from '@chakra-ui/react';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';+import { memo, useMemo } from 'react';import { useWidgetRuntime } from './createWidgetRuntime';import { WidgetFailureBoundary } from './WidgetFailureBoundary';import { WidgetHeader, WidgetPanelFrame } from './WidgetFrames';+import { areProjectWidgetRenderInstancesEqual } from './widgetRenderInstance';interface WidgetRendererProps extends Omit<WidgetViewProps, 'manifest' | 'runtime'> {instance: WidgetInstanceContract;widget: RegisteredWidget;}+interface WidgetRendererByIdProps extends Omit<WidgetViewProps, 'instance' | 'manifest' | 'runtime'> {+ instanceId: string;+ widget: RegisteredWidget;+}++export const WidgetRendererById = ({ instanceId, widget, ...props }: WidgetRendererByIdProps) => {+ const selection = useActiveProjectSelector(+ (project) => ({ instance: project.widgetInstances[instanceId], projectId: project.id }),+ areProjectWidgetRenderInstancesEqual+ );++ return selection.instance ? <WidgetRenderer instance={selection.instance} widget={widget} {...props} /> : null;+};+export const WidgetRenderer = ({ instance, presentation, region, widget }: WidgetRendererProps) => {const dispatch = useWorkbenchDispatch();const { getWidgetById, getWidgetsForRegion } = useWorkbenchWidgetRegistry();const project = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const View = widget.manifest.view;- const runtime = useWidgetRuntime({ dispatch, getWidgetById, getWidgetsForRegion, instance, project, region });+ const instanceMeta: WidgetInstanceRuntimeMeta = useMemo(+ () => ({+ createdAt: instance.createdAt,+ id: instance.id,+ title: instance.title,+ typeId: instance.typeId,+ }),+ [instance.createdAt, instance.id, instance.title, instance.typeId]+ );+ const runtime = useWidgetRuntime({+ dispatch,+ getWidgetById,+ getWidgetsForRegion,+ instance: instanceMeta,+ project,+ region,+ });if (!View) {return null;@@ -27,7 +65,7 @@ export const WidgetRenderer = ({ instance, presentation, region, widget }: Widgeconst content = (<View- instance={instance}+ instance={instanceMeta}manifest={widget.manifest}presentation={presentation}region={region}@@ -38,7 +76,7 @@ export const WidgetRenderer = ({ instance, presentation, region, widget }: Widgereturn (<WidgetShellFramecontent={content}- instance={instance}+ instance={instanceMeta}presentation={presentation}region={region}runtime={runtime}@@ -56,7 +94,7 @@ const WidgetShellFrame = ({widget,}: {content: React.ReactNode;- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;@@ -86,6 +124,7 @@ const WidgetShellFrame = ({<Flexbg="bg.inset"data-hotkey-widget-instance-id={instance.id}+ data-hotkey-widget-region={region}data-hotkey-widget-type-id={instance.typeId}direction="column"h="full"@@ -107,7 +146,7 @@ const RenderFailureSlot = ({widget,}: {children: React.ReactNode;- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;widget: RegisteredWidget;}) => {if (!widget.manifest.failurePolicy.isolateRenderFailure) {@@ -121,19 +160,44 @@ const RenderFailureSlot = ({);};-const HeaderSlot = ({+const areWidgetChromeInstancesEqual = (left: WidgetInstanceRuntimeMeta, right: WidgetInstanceRuntimeMeta): boolean =>+ left.id === right.id && left.typeId === right.typeId && left.title === right.title;++const areSlotPropsEqual = (+ left: {+ instance: WidgetInstanceRuntimeMeta;+ presentation: WidgetViewProps['presentation'];+ region: WidgetViewProps['region'];+ runtime: WidgetRuntimeApi;+ widget: RegisteredWidget;+ },+ right: {+ instance: WidgetInstanceRuntimeMeta;+ presentation: WidgetViewProps['presentation'];+ region: WidgetViewProps['region'];+ runtime: WidgetRuntimeApi;+ widget: RegisteredWidget;+ }+): boolean =>+ left.presentation === right.presentation &&+ left.region === right.region &&+ left.widget === right.widget &&+ left.runtime === right.runtime &&+ areWidgetChromeInstancesEqual(left.instance, right.instance);++const HeaderSlot = memo(function HeaderSlot({instance,presentation,region,runtime,widget,}: {- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;widget: RegisteredWidget;-}) => {+}) {if (widget.manifest.chrome?.header === 'hidden') {return null;}@@ -161,7 +225,7 @@ const HeaderSlot = ({/></Box>);-};+}, areSlotPropsEqual);const PanelBodySlot = ({ children }: { children: React.ReactNode }) => (<Flex direction="column" flex="1" minH="0" minW="0" overflowX="hidden" overflowY="auto">@@ -169,19 +233,19 @@ const PanelBodySlot = ({ children }: { children: React.ReactNode }) => (</Flex>);-const FooterSlot = ({+const FooterSlot = memo(function FooterSlot({instance,presentation,region,runtime,widget,}: {- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;presentation: WidgetViewProps['presentation'];region: WidgetViewProps['region'];runtime: WidgetRuntimeApi;widget: RegisteredWidget;-}) => {+}) {const Footer = widget.manifest.footer;if (!Footer) {@@ -200,7 +264,7 @@ const FooterSlot = ({/></Box>);-};+}, areSlotPropsEqual);export const MissingWidgetFrame = ({ label, region }: { label: string; region: 'bottom' | 'left' | 'right' }) => (<WidgetPanelFrame region={region}>diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.tsindex 61abcd2fe6..a2f8090855 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts@@ -10,7 +10,7 @@ import type { WorkbenchAction } from '@workbench/workbenchState';import { describe, expect, it, vi } from 'vitest';-import { createWidgetRuntime } from './createWidgetRuntime';+import { cloneWidgetRuntimeState, createWidgetRuntime, getProjectWidgetRuntimeState } from './createWidgetRuntime';const TestIcon = () => null;const TestView = () => null;@@ -51,6 +51,13 @@ const createDispatch = () => {return { actions, dispatch };};+const createStateApi = () => ({+ getSnapshot: () => ({ current: true }),+ patch: vi.fn(),+ set: vi.fn(),+ useSelector: vi.fn(),+});+const createRegistry =(widgetsByRegion: Partial<Record<WidgetRegion, RegisteredWidget[]>>) =>(region: WidgetRegion): RegisteredWidget[] =>@@ -58,7 +65,8 @@ const createRegistry =const createPlacementProject = (overrides: Partial<Pick<Project, 'widgetInstances' | 'widgetRegions'>> = {}-): Pick<Project, 'widgetInstances' | 'widgetRegions'> => ({+): Pick<Project, 'widgetInstances' | 'widgetRegions'> & { projectId: string } => ({+ projectId: 'project-1',widgetInstances: {alpha: createInstance('alpha'),beta: createInstance('beta', 'beta'),@@ -74,8 +82,23 @@ const createPlacementProject = (});describe('createWidgetRuntime', () => {- it('dispatches patchState and setState to the current widget instance', () => {+ it('deep clones runtime state snapshots', () => {+ const values = { nested: { mutable: 'before' }, tags: ['before'] };+ const snapshot = cloneWidgetRuntimeState(values);++ values.nested.mutable = 'after';+ values.tags[0] = 'after';++ expect(snapshot).toEqual({ nested: { mutable: 'before' }, tags: ['before'] });+ });++ it('returns an empty runtime state snapshot when the scoped project is missing', () => {+ expect(getProjectWidgetRuntimeState([], 'missing-project', 'generate')).toEqual({});+ });++ it('exposes widget state reads and writes through the state namespace', () => {const { actions, dispatch } = createDispatch();+ const state = createStateApi();const runtime = createWidgetRuntime({dispatch,getWidgetById: () => undefined,@@ -83,15 +106,16 @@ describe('createWidgetRuntime', () => {instance: createInstance(),project: createPlacementProject(),region: 'right',+ state,});- runtime.patchState({ next: true });- runtime.setState({ replaced: true });+ runtime.state.patch({ next: true });+ runtime.state.set({ replaced: true });- expect(actions).toEqual([- { instanceId: 'alpha', type: 'patchWidgetInstanceValues', values: { next: true } },- { instanceId: 'alpha', type: 'setWidgetInstanceValues', values: { replaced: true } },- ]);+ expect(actions).toEqual([]);+ expect(state.getSnapshot()).toEqual({ current: true });+ expect(state.patch).toHaveBeenCalledWith({ next: true });+ expect(state.set).toHaveBeenCalledWith({ replaced: true });});it('opens widgets through canonical validation and seeded initial values', () => {@@ -114,6 +138,7 @@ describe('createWidgetRuntime', () => {instance: createInstance(),project: createPlacementProject(),region: 'right',+ state: createStateApi(),});expect(runtime.workbench.openWidget('panel-widget', { preferredRegions: ['right'] })).toEqual({@@ -138,6 +163,7 @@ describe('createWidgetRuntime', () => {{createNew: undefined,initialValues: { seeded: true },+ projectId: 'project-1',region: 'right',type: 'openRegionWidget',widgetId: 'panel-widget',@@ -161,13 +187,14 @@ describe('createWidgetRuntime', () => {},}),region: 'bottom',+ state: createStateApi(),});expect(runtime.workbench.revealWidgetInstance('beta')).toEqual({ ok: true, region: 'bottom' });expect(runtime.workbench.closeWidgetInstance('beta')).toEqual({ ok: true, region: 'bottom' });expect(actions).toEqual([- { region: 'bottom', type: 'selectRegionWidget', widgetId: 'beta' },- { region: 'bottom', type: 'toggleRegionWidget', widgetId: 'beta' },+ { projectId: 'project-1', region: 'bottom', type: 'selectRegionWidget', widgetId: 'beta' },+ { projectId: 'project-1', region: 'bottom', type: 'toggleRegionWidget', widgetId: 'beta' },]);});@@ -180,10 +207,87 @@ describe('createWidgetRuntime', () => {instance: createInstance(),project: createPlacementProject(),region: 'right',+ state: createStateApi(),});expect(runtime.workbench.revealWidgetInstance('beta')).toEqual({ ok: false, reason: 'unsupported' });expect(runtime.workbench.closeWidgetInstance('beta')).toEqual({ ok: false, reason: 'unsupported' });expect(actions).toEqual([]);});++ it('executes commands registered by the current widget source', async () => {+ const { dispatch } = createDispatch();+ const alphaRuntime = createWidgetRuntime({+ dispatch,+ getWidgetById: () => undefined,+ getWidgetsForRegion: createRegistry({}),+ instance: createInstance('alpha', 'test-widget'),+ project: createPlacementProject(),+ region: 'right',+ state: createStateApi(),+ });+ const betaRuntime = createWidgetRuntime({+ dispatch,+ getWidgetById: () => undefined,+ getWidgetsForRegion: createRegistry({}),+ instance: createInstance('beta', 'test-widget'),+ project: createPlacementProject(),+ region: 'right',+ state: createStateApi(),+ });+ const disposeAlpha = alphaRuntime.commands.register({+ handler: () => 'alpha',+ id: 'test-widget.shared-command',+ title: 'Shared command',+ });+ const disposeBeta = betaRuntime.commands.register({+ handler: () => 'beta',+ id: 'test-widget.shared-command',+ title: 'Shared command',+ });++ await expect(alphaRuntime.commands.execute('test-widget.shared-command')).resolves.toBe('alpha');+ await expect(betaRuntime.commands.execute('test-widget.shared-command')).resolves.toBe('beta');++ disposeAlpha();+ disposeBeta();+ });++ it('does not execute commands registered by the same widget instance in another project', async () => {+ const { dispatch } = createDispatch();+ const projectOneRuntime = createWidgetRuntime({+ dispatch,+ getWidgetById: () => undefined,+ getWidgetsForRegion: createRegistry({}),+ instance: createInstance('alpha', 'test-widget'),+ project: createPlacementProject({}),+ region: 'right',+ state: createStateApi(),+ });+ const projectTwoRuntime = createWidgetRuntime({+ dispatch,+ getWidgetById: () => undefined,+ getWidgetsForRegion: createRegistry({}),+ instance: createInstance('alpha', 'test-widget'),+ project: { ...createPlacementProject({}), projectId: 'project-2' },+ region: 'right',+ state: createStateApi(),+ });+ const disposeOne = projectOneRuntime.commands.register({+ handler: () => 'project-1',+ id: 'test-widget.project-command',+ title: 'Project command',+ });+ const disposeTwo = projectTwoRuntime.commands.register({+ handler: () => 'project-2',+ id: 'test-widget.project-command',+ title: 'Project command',+ });++ await expect(projectOneRuntime.commands.execute('test-widget.project-command')).resolves.toBe('project-1');+ await expect(projectTwoRuntime.commands.execute('test-widget.project-command')).resolves.toBe('project-2');++ disposeOne();+ disposeTwo();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.tsindex cb85dee190..f874615e72 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts@@ -1,9 +1,12 @@import type {+ Project,WidgetHotkeyApi,OpenWorkbenchWidgetOptions,RegisteredWidget,- WidgetInstanceContract,+ WidgetContributionSource,+ WidgetInstanceRuntimeMeta,WidgetRegion,+ WidgetRuntimeStateApi,WidgetRuntimeApi,WidgetTypeId,WorkbenchRegion,@@ -12,7 +15,7 @@ import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands'import type { WorkbenchAction } from '@workbench/workbenchState';import {- commandApi,+ commandApi as sharedCommandApi,commandPaletteApi,hotkeyApi,menuApi,@@ -20,12 +23,52 @@ import {toolbarApi,} from '@workbench/extensions/extensionApi';import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';+import { useProjectWidgetInstanceValuesSelector, useWorkbenchStore } from '@workbench/WorkbenchContext';import { useMemo, type Dispatch } from 'react';const WIDGET_REGIONS = new Set<WidgetRegion>(['bottom', 'center', 'left', 'right']);const isWidgetRegion = (region: WorkbenchRegion): region is WidgetRegion => WIDGET_REGIONS.has(region as WidgetRegion);+const cloneWidgetRuntimeValue = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(cloneWidgetRuntimeValue);+ }++ if (value instanceof Map) {+ return new Map(Array.from(value, ([key, item]) => [key, cloneWidgetRuntimeValue(item)]));+ }++ if (value instanceof Set) {+ return new Set(Array.from(value, cloneWidgetRuntimeValue));+ }++ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, cloneWidgetRuntimeValue(item)])+ );+ }++ return value;+};++export const cloneWidgetRuntimeState = <State extends Record<string, unknown>>(state: State): State => {+ try {+ return structuredClone(state) as State;+ } catch {+ return cloneWidgetRuntimeValue(state) as State;+ }+};++export const getProjectWidgetRuntimeState = <State extends Record<string, unknown>>(+ projects: readonly Project[],+ projectId: string,+ instanceId: string+): State =>+ cloneWidgetRuntimeState(+ (projects.find((project) => project.id === projectId)?.widgetInstances[instanceId]?.state.values ?? {}) as State+ );+export const createWidgetRuntime = ({dispatch,getWidgetsForRegion,@@ -33,34 +76,49 @@ export const createWidgetRuntime = ({instance,project,region,+ state,}: {dispatch: Dispatch<WorkbenchAction>;getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;project: WidgetPlacementProject;region: WorkbenchRegion;+ state: WidgetRuntimeStateApi;}): WidgetRuntimeApi => {+ const sourceProjectId = project.projectId ?? '';+ const source: WidgetContributionSource = {+ instanceId: instance.id,+ projectId: sourceProjectId,+ region,+ typeId: instance.typeId,+ };+ const commands = {+ execute: (commandId, ...args) => sharedCommandApi.executeForSource(commandId, source, ...args),+ executeForSource: sharedCommandApi.executeForSource,+ register: (command) => sharedCommandApi.register({ ...command, source }),+ } satisfies WidgetRuntimeApi['commands'];const hotkeys: WidgetHotkeyApi = {register: (hotkey) =>hotkeyApi.register({...hotkey,scope: hotkey.scope ?? 'widget',- source: { instanceId: instance.id, region, typeId: instance.typeId },+ source,}),};+ const menus = {+ register: (menu) => menuApi.register({ ...menu, source }),+ } satisfies WidgetRuntimeApi['menus'];return {- commands: commandApi,+ commands,hotkeys,instanceId: instance.id,- menus: menuApi,+ menus,palette: commandPaletteApi,- patchState: (values) => dispatch({ instanceId: instance.id, type: 'patchWidgetInstanceValues', values }),region,search: searchApi,- setState: (values) => dispatch({ instanceId: instance.id, type: 'setWidgetInstanceValues', values }),- state: instance.state.values,+ state,toolbars: toolbarApi,typeId: instance.typeId,workbench: {@@ -72,7 +130,7 @@ export const createWidgetRuntime = ({return closeWidgetPlacement({ dispatch, getWidgetById, instanceId, project, region });},openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) =>- openWidgetPlacement({ dispatch, getWidgetsForRegion, options, typeId }),+ openWidgetPlacement({ dispatch, getWidgetsForRegion, options, projectId: project.projectId, typeId }),revealWidgetInstance: (instanceId) => {if (!isWidgetRegion(region)) {return { ok: false, reason: 'unsupported' };@@ -95,11 +153,41 @@ export const useWidgetRuntime = ({dispatch: Dispatch<WorkbenchAction>;getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];- instance: WidgetInstanceContract;+ instance: WidgetInstanceRuntimeMeta;project: WidgetPlacementProject;region: WorkbenchRegion;-}): WidgetRuntimeApi =>- useMemo(- () => createWidgetRuntime({ dispatch, getWidgetById, getWidgetsForRegion, instance, project, region }),- [dispatch, getWidgetById, getWidgetsForRegion, instance, project, region]+}): WidgetRuntimeApi => {+ const store = useWorkbenchStore();+ const projectId = project.projectId ?? store.getSnapshot().activeProject.id;+ const state = useMemo<WidgetRuntimeStateApi>(+ () => ({+ getSnapshot: () => getProjectWidgetRuntimeState(store.getState().projects, projectId, instance.id),+ patch: (values) =>+ dispatch({+ instanceId: instance.id,+ projectId,+ type: 'patchWidgetInstanceValues',+ values: cloneWidgetRuntimeState(values),+ }),+ set: (values) =>+ dispatch({+ instanceId: instance.id,+ projectId,+ type: 'setWidgetInstanceValues',+ values: cloneWidgetRuntimeState(values),+ }),+ useSelector<Selected>(+ selector: (state: Record<string, unknown>) => Selected,+ isEqual?: (left: Selected, right: Selected) => boolean+ ): Selected {+ return useProjectWidgetInstanceValuesSelector(projectId, instance.id, selector, isEqual);+ },+ }),+ [dispatch, instance.id, projectId, store]+ );++ return useMemo(+ () => createWidgetRuntime({ dispatch, getWidgetById, getWidgetsForRegion, instance, project, region, state }),+ [dispatch, getWidgetById, getWidgetsForRegion, instance, project, region, state]);+};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/index.tsindex 1f0ae44298..c0536106a3 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts@@ -6,5 +6,5 @@ export { FieldPlaceholder, StatusWidgetChip, WidgetHeader, WidgetPanelFrame } frexport { WidgetInstanceContextMenu, type WidgetInstanceContextMenuTarget } from './WidgetInstanceContextMenu';export { WidgetRegionDropOverlay } from './WidgetRegionDropOverlay';export { WidgetStrip } from './WidgetStrip';-export { MissingWidgetFrame, WidgetRenderer } from './WidgetRenderer';+export { MissingWidgetFrame, WidgetRenderer, WidgetRendererById } from './WidgetRenderer';export { useWidgetSortable } from './useWidgetSortable';diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.tsnew file mode 100644index 0000000000..9ea057e5b8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.test.ts@@ -0,0 +1,24 @@+import type { WidgetInstanceContract } from '@workbench/types';++import { describe, expect, it } from 'vitest';++import { areProjectWidgetRenderInstancesEqual } from './widgetRenderInstance';++const instance: WidgetInstanceContract = {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'generate',+ state: { id: 'generate', label: 'Generate', values: {}, version: 1 },+ title: 'Generate',+ typeId: 'generate',+};++describe('areProjectWidgetRenderInstancesEqual', () => {+ it('treats same instance metadata in different projects as different render inputs', () => {+ expect(+ areProjectWidgetRenderInstancesEqual(+ { instance, projectId: 'project-a' },+ { instance: { ...instance }, projectId: 'project-b' }+ )+ ).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.tsnew file mode 100644index 0000000000..4e4b613a77--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/widgetRenderInstance.ts@@ -0,0 +1,23 @@+import type { WidgetInstanceContract } from '@workbench/types';++export interface ProjectWidgetRenderInstance {+ instance: WidgetInstanceContract | undefined;+ projectId: string;+}++export const areWidgetRenderInstancesEqual = (+ left: WidgetInstanceContract | undefined,+ right: WidgetInstanceContract | undefined+): boolean =>+ left === right ||+ (left !== undefined &&+ right !== undefined &&+ left.id === right.id &&+ left.typeId === right.typeId &&+ left.title === right.title &&+ left.createdAt === right.createdAt);++export const areProjectWidgetRenderInstancesEqual = (+ left: ProjectWidgetRenderInstance,+ right: ProjectWidgetRenderInstance+): boolean => left.projectId === right.projectId && areWidgetRenderInstancesEqual(left.instance, right.instance);diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.tsindex 3a6627123d..926e1e4707 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts@@ -107,6 +107,22 @@ describe('widget placement commands', () => {expect(actions).toMatchObject([{ createNew: true, region: 'right', type: 'openRegionWidget', widgetId: 'queue' }]);});+ it('does not create a new instance for singleton widgets even when requested', () => {+ const actions: WorkbenchAction[] = [];+ const widget = createWidget({ allowMultiple: false, id: 'queue', labelText: 'Queue' });++ openWidgetPlacement({+ dispatch: (action) => actions.push(action),+ getWidgetsForRegion: createRegistry({ right: [widget] }),+ options: { createNew: true, preferredRegions: ['right'] },+ typeId: 'queue',+ });++ expect(actions).toMatchObject([+ { createNew: undefined, region: 'right', type: 'openRegionWidget', widgetId: 'queue' },+ ]);+ });+it('rejects invalid regions and unrenderable placements', () => {const actions: WorkbenchAction[] = [];const dispatch = (action: WorkbenchAction): void => {diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.tsindex da0bba24a0..f12e9b62b4 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts@@ -14,6 +14,7 @@ import type { WidgetPlacementMeta } from './widgetRegionViewModel';import type { WorkbenchAction } from './workbenchState';export interface WidgetPlacementProject {+ projectId?: string;widgetInstances: WidgetPlacementMeta;widgetRegions: Record<WidgetRegion, Pick<WidgetRegionState, 'activeInstanceId' | 'instanceIds'>>;}@@ -71,10 +72,12 @@ export const openWidgetPlacement = ({dispatch,getWidgetsForRegion,options,+ projectId,typeId,}: {dispatch: Dispatch<WorkbenchAction>;getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];+ projectId?: string;typeId: WidgetTypeId;options?: OpenWorkbenchWidgetOptions;}): WidgetPlacementCommandResult => {@@ -85,8 +88,9 @@ export const openWidgetPlacement = ({}dispatch({- createNew: options?.createNew,+ createNew: target.widget.manifest.allowMultiple ? options?.createNew : undefined,initialValues: target.widget.manifest.state?.createInitial(),+ projectId,region: target.region,type: 'openRegionWidget',widgetId: typeId,@@ -137,7 +141,7 @@ export const closeWidgetPlacement = ({}}- dispatch({ region, type: 'toggleRegionWidget', widgetId: instanceId });+ dispatch({ projectId: project.projectId, region, type: 'toggleRegionWidget', widgetId: instanceId });return { ok: true, region };};@@ -161,7 +165,7 @@ export const revealWidgetPlacement = ({return { ok: false, reason: 'unsupported' };}- dispatch({ region, type: 'selectRegionWidget', widgetId: instanceId });+ dispatch({ projectId: project.projectId, region, type: 'selectRegionWidget', widgetId: instanceId });return { ok: true, region };};diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.tsindex e4f4e27002..0bda7b4666 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts@@ -25,8 +25,9 @@ export const getWidgetPlacementMeta = (};export const getWidgetPlacementProject = (- project: Pick<Project, 'widgetInstances' | 'widgetRegions'>+ project: Pick<Project, 'id' | 'widgetInstances' | 'widgetRegions'>): WidgetPlacementProject => ({+ projectId: project.id,widgetInstances: getWidgetPlacementMeta(project),widgetRegions: project.widgetRegions,});@@ -52,6 +53,7 @@ export const areWidgetPlacementMetaEqual = (left: WidgetPlacementMeta, right: Wi};export const areWidgetPlacementProjectsEqual = (left: WidgetPlacementProject, right: WidgetPlacementProject): boolean =>+ left.projectId === right.projectId &&areWidgetPlacementMetaEqual(left.widgetInstances, right.widgetInstances) &&(Object.keys(left.widgetRegions) as WidgetRegion[]).every((region) => {const leftRegion = left.widgetRegions[region];diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.tsindex 79c8acb20b..752f32e79c 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts@@ -146,11 +146,13 @@ export const isRequiredCenterView = (item: WidgetRegionItem, enabledCenterViewCoreturn isView && item.isEnabled && enabledCenterViewCount === 1;};-export const isCompactBottomItem = (item: WidgetRegionItem): item is PlacedWidgetRegionItem =>- item.isEnabled && item.status === 'enabled';+export const isCompactBottomItem = <Instance extends WidgetPlacementInstanceMeta>(+ item: WidgetRegionItem<Instance>+): item is PlacedWidgetRegionItem<Instance> => item.isEnabled && item.status === 'enabled';-export const isExpandableBottomItem = (item: WidgetRegionItem): boolean =>- item.widget.manifest.bottomPanel !== 'tooltip';+export const isExpandableBottomItem = <Instance extends WidgetPlacementInstanceMeta>(+ item: WidgetRegionItem<Instance>+): boolean => item.widget.manifest.bottomPanel !== 'tooltip';export const canRemoveItem = (item: WidgetRegionItem, viewModel: WidgetRegionViewModel): boolean => {if (viewModel.region !== 'center') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 0bdeef3417..9e34221199 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -1,16 +1,16 @@import type { WidgetViewProps } from '@workbench/types';import { Box, Flex } from '@chakra-ui/react';-import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { useEffect, useEffectEvent } from 'react';import { CanvasDocumentFrame, CanvasPlaneImage, EmptyCanvasFrame, ToolScrubber } from './CanvasDocumentFrame';import { CanvasStagingControls, EmptyStagingControls } from './CanvasStagingControls';export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {- const activeProject = useActiveProject();+ const canvas = useActiveProjectSelector((project) => project.canvas);const dispatch = useWorkbenchDispatch();- const { document, stagingArea } = activeProject.canvas;+ const { document, stagingArea } = canvas;const { layers } = document;const selectedCandidate = stagingArea.pendingImages[stagingArea.selectedImageIndex];const selectedImage = stagingArea.isVisible ? selectedCandidate : undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsxindex 8adddb7bcb..b600f440dd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx@@ -7,8 +7,7 @@ import { useWorkbenchSelector } from '@workbench/WorkbenchContext';import { BugIcon, ClipboardListIcon } from 'lucide-react';export const DiagnosticsWidgetView = ({ presentation, region }: WidgetViewProps) => {- const errorLog = useWorkbenchSelector((snapshot) => snapshot.state.errorLog);- const errorCount = errorLog.length;+ const errorCount = useWorkbenchSelector((snapshot) => snapshot.state.errorLog.length);const label = errorCount === 0 ? 'Clean' : `${errorCount} issue${errorCount === 1 ? '' : 's'}`;if (region === 'bottom' && presentation !== 'expanded') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsxindex 490f90cc3c..136d11558b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx@@ -1,15 +1,23 @@-import type { WidgetViewProps } from '@workbench/types';+import type { GeneratedImageContract, WidgetViewProps } from '@workbench/types';-import { getGallerySettings } from '@workbench/gallery/settings';+import { getGallerySettings, type GallerySettings } from '@workbench/gallery/settings';import { useImageActions } from '@workbench/image-actions';import { StatusWidgetChip } from '@workbench/widget-frame';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { createGenerateFormValuesSelector } from '@workbench/widgets/generate/generateFormViewModel';+import {+ useActiveProjectId,+ useActiveProjectName,+ useActiveProjectSelector,+ useWidgetValuesSelector,+ useWorkbenchDispatch,+} from '@workbench/WorkbenchContext';+import { areArraysEqual, createStableSelector } from '@workbench/workbenchSelectors';import { ImageIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useRef } from 'react';import { GalleryPanelContent } from './GalleryPanelContent';import {+ getGalleryCompareImage,getGalleryPage,getGalleryProjectBoardId,getGalleryImagesRefreshToken,@@ -17,6 +25,7 @@ import {getGalleryRefreshToken,getGallerySearchTerm,getGallerySelectedBoardId,+ getGallerySelectedImageNames,getGalleryStateView,getGalleryTotalImages,getGalleryView,@@ -25,10 +34,83 @@ import { GalleryWidgetContext, type GalleryWidgetContextValue } from './GalleryWimport { useGalleryActions } from './useGalleryActions';import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';+interface GalleryWidgetSelectedValues extends Record<string, unknown>, GallerySettings {+ compareImage: GeneratedImageContract | null;+ galleryImagesRefreshToken: string;+ galleryPage: number;+ galleryRefreshToken: string;+ galleryTotalImages: number | null;+ galleryView: ReturnType<typeof getGalleryView>;+ projectBoardId: string | null;+ recentImages: GeneratedImageContract[] | undefined;+ searchTerm: string;+ selectedBoardId: string;+ selectedImageName: string | null;+ selectedImageNames: string[];+}++const areGallerySettingsEqual = (left: GallerySettings, right: GallerySettings): boolean =>+ left.boardOrderBy === right.boardOrderBy &&+ left.boardOrderDir === right.boardOrderDir &&+ left.imageDensityPercent === right.imageDensityPercent &&+ left.imageOrderDir === right.imageOrderDir &&+ left.paginationMode === right.paginationMode &&+ left.showArchivedBoards === right.showArchivedBoards &&+ left.showDateBoards === right.showDateBoards &&+ left.showImageDimensions === right.showImageDimensions &&+ left.starredFirst === right.starredFirst &&+ left.thumbnailFit === right.thumbnailFit;++const areGalleryWidgetSelectedValuesEqual = (+ left: GalleryWidgetSelectedValues,+ right: GalleryWidgetSelectedValues+): boolean =>+ left.compareImage === right.compareImage &&+ left.galleryImagesRefreshToken === right.galleryImagesRefreshToken &&+ left.galleryPage === right.galleryPage &&+ left.galleryRefreshToken === right.galleryRefreshToken &&+ left.galleryTotalImages === right.galleryTotalImages &&+ left.galleryView === right.galleryView &&+ left.projectBoardId === right.projectBoardId &&+ left.recentImages === right.recentImages &&+ left.searchTerm === right.searchTerm &&+ left.selectedBoardId === right.selectedBoardId &&+ left.selectedImageName === right.selectedImageName &&+ areArraysEqual(left.selectedImageNames, right.selectedImageNames) &&+ areGallerySettingsEqual(left, right);++const selectGalleryWidgetValues = createStableSelector(+ (values: Record<string, unknown>): GalleryWidgetSelectedValues => {+ const settings = getGallerySettings(values);++ return {+ ...settings,+ compareImage: getGalleryCompareImage(values),+ galleryImagesRefreshToken: getGalleryImagesRefreshToken(values),+ galleryPage: getGalleryPage(values),+ galleryRefreshToken: getGalleryRefreshToken(values),+ galleryTotalImages: getGalleryTotalImages(values),+ galleryView: getGalleryView(values),+ projectBoardId: getGalleryProjectBoardId(values),+ recentImages: Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : undefined,+ searchTerm: getGallerySearchTerm(values),+ selectedBoardId: getGallerySelectedBoardId(values, []),+ selectedImageName: typeof values.selectedImageName === 'string' ? values.selectedImageName : null,+ selectedImageNames: getGallerySelectedImageNames(values),+ };+ },+ areGalleryWidgetSelectedValuesEqual+);++const selectGenerateRecallValues = createGenerateFormValuesSelector();+export const GalleryWidgetView = ({ presentation, region, runtime }: WidgetViewProps) => {- const activeProject = useActiveProject();const dispatch = useWorkbenchDispatch();- const galleryValues = getProjectWidgetValues(activeProject, 'gallery');+ const projectId = useActiveProjectId();+ const galleryValues = useWidgetValuesSelector('gallery', selectGalleryWidgetValues);+ const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);+ const projectName = useActiveProjectName();+ const queueItems = useActiveProjectSelector((project) => project.queue.items);const galleryView = getGalleryView(galleryValues);const searchTerm = getGallerySearchTerm(galleryValues);const recentImagesKey = getGalleryRecentImagesKey(galleryValues);@@ -51,13 +133,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: WidgetViewP});const { loadMore, patchImages, total } = data;const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);- const gallery = getGalleryStateView(- galleryValues,- data.boards,- data.images,- data.isLoadingImages,- activeProject.queue.items- );+ const gallery = getGalleryStateView(galleryValues, data.boards, data.images, data.isLoadingImages, queueItems);const onStarredChange = useCallback((imageNames: string[], starred: boolean) => {patchImages((images) =>@@ -105,21 +181,22 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: WidgetViewPconst imageActions = useImageActions({boards: data.boards,dispatch,- generateValues: getProjectWidgetValues(activeProject, 'generate'),+ generateValues,onImagesDeleted,onStarredChange,+ projectId,});const actions = useGalleryActions({boards: data.boards,dispatch,loadMore,projectBoardId: getGalleryProjectBoardId(galleryValues),- projectName: activeProject.name,+ projectName,selectedBoardId,});const contextValue = useMemo<GalleryWidgetContextValue>(- () => ({ actions, gallery, imageActions, projectName: activeProject.name, runtime }),- [actions, activeProject.name, gallery, imageActions, runtime]+ () => ({ actions, gallery, imageActions, projectName, runtime }),+ [actions, gallery, imageActions, projectName, runtime]);const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsxindex a157f95ab3..3cf46e9778 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx@@ -14,6 +14,7 @@ interface GenerateAdvancedFieldsProps {settings: GenerateSettings;selectedModel: GenerateModelConfig | undefined;onCommit: (patch: Partial<GenerateSettings>) => void;+ onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}const SeamlessSwitch = ({@@ -34,7 +35,12 @@ const SeamlessSwitch = ({</Switch.Root>);-export const GenerateAdvancedFields = ({ onCommit, selectedModel, settings }: GenerateAdvancedFieldsProps) => {+export const GenerateAdvancedFields = ({+ onCommit,+ onCommitImmediate,+ selectedModel,+ settings,+}: GenerateAdvancedFieldsProps) => {const modelBase = selectedModel?.base;const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const policy = getGenerationUiPolicy(selectedModel, settings);@@ -89,12 +95,12 @@ export const GenerateAdvancedFields = ({ onCommit, selectedModel, settings }: Gesize="xs"placeholder="Model default"value={settings.vae?.key ?? null}- onChange={(model) => onCommit({ vae: isVaeModelConfig(model) ? model : null })}+ onChange={(model) => onCommitImmediate({ vae: isVaeModelConfig(model) ? model : null })}/><ModelDefaultButtondisabled={!settings.vae}label="Use model default VAE"- onClick={() => onCommit({ vae: null })}+ onClick={() => onCommitImmediate({ vae: null })}/></HStack></Field>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsxindex e479dff411..9d880b1854 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateConceptsSection.tsx@@ -15,14 +15,20 @@ import { ModelSelect } from '@workbench/models/components';import { Trash2Icon } from 'lucide-react';import { useMemo } from 'react';+import type { GenerateSettingsUpdate } from './generateDebounce';++import { useRegisterGenerateDraftFlusher } from './generateDraftRegistry';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { ModelDefaultButton } from './shared/ModelDefaultButton';+import { useDebouncedDraftValue } from './useDebouncedDraftValue';interface GenerateConceptsSectionProps {settings: GenerateSettings;loraModels: LoraModelConfig[];+ projectId: string;selectedModel: GenerateModelConfig | undefined;- onCommit: (patch: Partial<GenerateSettings>) => void;+ onCommit: (update: GenerateSettingsUpdate) => void;+ onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}const LORA_WEIGHT_MARKS = [@@ -31,6 +37,7 @@ const LORA_WEIGHT_MARKS = [{ label: '1', value: 1 },{ label: '2', value: 2 },];+const LORA_WEIGHT_DEBOUNCE_MS = 250;const isCompatibleLora = (lora: GenerateLora, selectedModel: GenerateModelConfig | undefined): boolean =>Boolean(selectedModel && isLoraCompatibleWithModel(lora.model, selectedModel));@@ -38,6 +45,8 @@ const isCompatibleLora = (lora: GenerateLora, selectedModel: GenerateModelConfigexport const GenerateConceptsSection = ({loraModels,onCommit,+ onCommitImmediate,+ projectId,selectedModel,settings,}: GenerateConceptsSectionProps) => {@@ -52,19 +61,29 @@ export const GenerateConceptsSection = ({return;}- onCommit({+ onCommitImmediate({loras: [...loras, { isEnabled: true, model, weight: getDefaultLoraWeight(model) }],});};const updateLora = (modelKey: string, patch: Partial<Pick<GenerateLora, 'isEnabled' | 'weight'>>) => {- onCommit({- loras: loras.map((lora) => (lora.model.key === modelKey ? { ...lora, ...patch } : lora)),+ onCommit((settings) => {+ const latestLoras = syncGenerateLorasWithModels(settings.loras, loraModels);+ const hasLora = latestLoras.some((lora) => lora.model.key === modelKey);++ if (!hasLora) {+ return settings;+ }++ return {+ ...settings,+ loras: latestLoras.map((lora) => (lora.model.key === modelKey ? { ...lora, ...patch } : lora)),+ };});};const removeLora = (modelKey: string) => {- onCommit({ loras: loras.filter((lora) => lora.model.key !== modelKey) });+ onCommitImmediate({ loras: loras.filter((lora) => lora.model.key !== modelKey) });};const badges =@@ -106,6 +125,7 @@ export const GenerateConceptsSection = ({key={lora.model.key}isCompatible={isCompatibleLora(lora, selectedModel)}lora={lora}+ projectId={projectId}onRemove={() => removeLora(lora.model.key)}onToggle={(isEnabled) => updateLora(lora.model.key, { isEnabled })}onWeightChange={(weight) => updateLora(lora.model.key, { weight })}@@ -122,17 +142,31 @@ const LoraRow = ({isCompatible,lora,onRemove,+ projectId,onToggle,onWeightChange,}: {isCompatible: boolean;lora: GenerateLora;onRemove: () => void;+ projectId: string;onToggle: (isEnabled: boolean) => void;onWeightChange: (weight: number) => void;}) => {const isActive = lora.isEnabled && isCompatible;const defaultWeight = getDefaultLoraWeight(lora.model);+ const {+ draftValue: draftWeight,+ flushDraftValue,+ setDraftValue: setWeight,+ } = useDebouncedDraftValue({+ delayMs: LORA_WEIGHT_DEBOUNCE_MS,+ onCommit: onWeightChange,+ resetKey: projectId,+ value: lora.weight,+ });++ useRegisterGenerateDraftFlusher(flushDraftValue);return (<Stack@@ -204,12 +238,12 @@ const LoraRow = ({min={DEFAULT_LORA_WEIGHT_CONFIG.sliderMin}minW="0"step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}- value={[lora.weight]}+ value={[draftWeight]}onValueChange={({ value }) => {const nextWeight = value[0];if (Number.isFinite(nextWeight)) {- onWeightChange(nextWeight as number);+ setWeight(nextWeight as number);}}}>@@ -227,21 +261,21 @@ const LoraRow = ({min={DEFAULT_LORA_WEIGHT_CONFIG.numberInputMin}size="xs"step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}- value={String(lora.weight)}+ value={String(draftWeight)}w="20"disabled={!isActive}onValueChange={({ valueAsNumber }) => {if (Number.isFinite(valueAsNumber)) {- onWeightChange(valueAsNumber);+ setWeight(valueAsNumber);}}}><InputGroupendElement={<ModelDefaultButton- disabled={!isActive || lora.weight === defaultWeight}+ disabled={!isActive || draftWeight === defaultWeight}label="Use concept default weight"- onClick={() => onWeightChange(defaultWeight)}+ onClick={() => setWeight(defaultWeight)}/>}endElementProps={{ pointerEvents: 'auto' }}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsxindex 9f75ec348e..18e028897e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx@@ -25,7 +25,7 @@ import {MIN_DIMENSION,} from '@workbench/generation/settings';import { ArrowLeftRightIcon, LockIcon, LockOpenIcon, RulerDimensionLineIcon, ScalingIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { AspectRatioPreview } from './shared/AspectRatioPreview';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';@@ -33,6 +33,7 @@ import { ModelDefaultButton } from './shared/ModelDefaultButton';interface GenerateDimensionFieldsProps {settings: GenerateSettings;+ projectId: string;selectedModel: GenerateModelConfig | undefined;onCommit: (patch: Partial<GenerateSettings>) => void;}@@ -51,7 +52,12 @@ const getActiveRatio = (settings: GenerateSettings): number =>const getAspectRatioOptionRatio = (id: AspectRatioId, fallbackRatio: number): number =>id === 'Free' ? fallbackRatio : ASPECT_RATIO_MAP[id].ratio;-export const GenerateDimensionFields = ({ onCommit, selectedModel, settings }: GenerateDimensionFieldsProps) => {+export const GenerateDimensionFields = ({+ onCommit,+ projectId,+ selectedModel,+ settings,+}: GenerateDimensionFieldsProps) => {const [draftDimensions, setDraftDimensions] = useState<Dimensions | null>(null);const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const dimensions = getGenerationDimensions(selectedModel);@@ -60,6 +66,7 @@ export const GenerateDimensionFields = ({ onCommit, selectedModel, settings }: Gconst displayDimensions = draftDimensions ?? { height: settings.height, width: settings.width };const onCommitRef = useRef(onCommit);const pendingDimensionsRef = useRef<Dimensions | null>(null);+ const projectIdRef = useRef(projectId);const previousSettingsDimensionsRef = useRef<Dimensions>({ height: settings.height, width: settings.width });const dimensionRatio = displayDimensions.height > 0 ? displayDimensions.width / displayDimensions.height : 1;const aspectRatioOptions = useMemo<AspectRatioOption[]>(@@ -90,6 +97,17 @@ export const GenerateDimensionFields = ({ onCommit, selectedModel, settings }: GonCommitRef.current(dimensions);}, []);+ useLayoutEffect(() => {+ if (projectIdRef.current === projectId) {+ return;+ }++ projectIdRef.current = projectId;+ pendingDimensionsRef.current = null;+ previousSettingsDimensionsRef.current = { height: settings.height, width: settings.width };+ setDraftDimensions(null);+ }, [projectId, settings.height, settings.width]);+useEffect(() => {const previousSettingsDimensions = previousSettingsDimensionsRef.current;previousSettingsDimensionsRef.current = { height: settings.height, width: settings.width };@@ -135,9 +153,7 @@ export const GenerateDimensionFields = ({ onCommit, selectedModel, settings }: Greturn;}- const dimensions = getNextDimensions(key, value, false);-- setDraftDimensions(dimensions);+ setDraftDimensions(getNextDimensions(key, value, false));};const commitDimension =diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsxindex 2cb5fab4e9..efea36e75a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx@@ -6,23 +6,38 @@ import type {} from '@workbench/generation/types';import { Stack, Text } from '@chakra-ui/react';+import { useEffect, useLayoutEffect, useRef, useState } from 'react';import { GenerateAdvancedFields } from './GenerateAdvancedFields';import { GenerateComponentsSection } from './GenerateComponentsSection';import { GenerateConceptsSection } from './GenerateConceptsSection';+import {+ applyGenerateSettingsPatch,+ applyGenerateSettingsUpdate,+ getChangedGenerateSettingsPatch,+ type GenerateSettingsUpdate,+ mergeGenerateSettingsUpdate,+ type PendingGenerateSettingsUpdate,+} from './generateDebounce';import { GenerateDimensionFields } from './GenerateDimensionFields';+import { useRegisterGenerateDraftFlusher } from './generateDraftRegistry';+import { getSettingsWithLatestPromptFields } from './generateFormViewModel';import { GenerateModelFields } from './GenerateModelFields';import { GeneratePromptFields } from './promptFields';+const GENERATE_INPUT_DEBOUNCE_MS = 250;+interface GenerateSettingsFormProps {isLoadingModels: boolean;loadError: string | null;settings: GenerateSettings;loraModels: LoraModelConfig[];+ projectId: string;selectedModel: GenerateModelConfig | undefined;supportedModels: GenerateModelConfig[];vaeModels: VaeModelConfig[];onCommitSettings: (nextSettings: GenerateSettings) => void;+ onPatchSettings: (patch: Partial<GenerateSettings>) => void;}export const GenerateSettingsForm = ({@@ -30,39 +45,228 @@ export const GenerateSettingsForm = ({loadError,loraModels,onCommitSettings,+ onPatchSettings,+ projectId,selectedModel,settings,supportedModels,vaeModels,}: GenerateSettingsFormProps) => {- const commit = (patch: Partial<GenerateSettings>) => {- onCommitSettings({ ...settings, ...patch });+ const [draftSettings, setDraftSettings] = useState(settings);+ const draftSettingsRef = useRef(settings);+ const latestSettingsRef = useRef(settings);+ const pendingUpdateRef = useRef<PendingGenerateSettingsUpdate>(null);+ const projectIdRef = useRef(projectId);+ const timeoutRef = useRef<number | null>(null);+ const onCommitSettingsRef = useRef(onCommitSettings);+ const onPatchSettingsRef = useRef(onPatchSettings);++ onCommitSettingsRef.current = onCommitSettings;+ onPatchSettingsRef.current = onPatchSettings;++ const setDraft = (nextSettings: GenerateSettings) => {+ draftSettingsRef.current = nextSettings;+ setDraftSettings(nextSettings);+ };++ const clearPendingUpdate = () => {+ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ pendingUpdateRef.current = null;+ };++ useLayoutEffect(() => {+ if (projectIdRef.current !== projectId) {+ projectIdRef.current = projectId;+ clearPendingUpdate();+ latestSettingsRef.current = settings;+ setDraft(settings);+ return;+ }++ latestSettingsRef.current = settings;+ setDraft(applyGenerateSettingsUpdate(settings, pendingUpdateRef.current));+ }, [projectId, settings]);++ const flushPendingUpdate = (shouldUpdateDraft = true) => {+ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ const updateToCommit = pendingUpdateRef.current;++ pendingUpdateRef.current = null;++ if (updateToCommit) {+ const previousSettings = latestSettingsRef.current;+ const settingsToCommit = applyGenerateSettingsUpdate(latestSettingsRef.current, updateToCommit);++ latestSettingsRef.current = settingsToCommit;++ if (shouldUpdateDraft) {+ setDraft(settingsToCommit);+ }++ onPatchSettingsRef.current(getChangedGenerateSettingsPatch(previousSettings, settingsToCommit));+ }+ };++ useRegisterGenerateDraftFlusher(flushPendingUpdate);++ useEffect(+ () => () => {+ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ }++ flushPendingUpdate(false);+ },+ []+ );++ const scheduleCommitUpdate = (update: GenerateSettingsUpdate) => {+ pendingUpdateRef.current = mergeGenerateSettingsUpdate(pendingUpdateRef.current, update);++ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ }++ timeoutRef.current = window.setTimeout(() => {+ timeoutRef.current = null;+ flushPendingUpdate();+ }, GENERATE_INPUT_DEBOUNCE_MS);+ };++ const commit = (update: GenerateSettingsUpdate) => {+ const nextSettings = applyGenerateSettingsUpdate(+ draftSettingsRef.current,+ mergeGenerateSettingsUpdate(null, update)+ );++ setDraft(nextSettings);+ scheduleCommitUpdate(update);+ };++ const commitDebouncedDraftUpdate = (update: GenerateSettingsUpdate) => {+ const pendingUpdate = mergeGenerateSettingsUpdate(pendingUpdateRef.current, update);+ const previousSettings = latestSettingsRef.current;+ const nextSettings = applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdate);++ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ pendingUpdateRef.current = null;+ latestSettingsRef.current = nextSettings;+ setDraft(nextSettings);+ onPatchSettingsRef.current(getChangedGenerateSettingsPatch(previousSettings, nextSettings));+ };++ const commitPromptDraftPatch = (patch: Partial<GenerateSettings>) => {+ const pendingUpdate = mergeGenerateSettingsUpdate(pendingUpdateRef.current, patch);+ const previousSettings = latestSettingsRef.current;+ const nextSettings = applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdate);++ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ pendingUpdateRef.current = null;+ latestSettingsRef.current = nextSettings;+ onPatchSettingsRef.current(getChangedGenerateSettingsPatch(previousSettings, nextSettings));+ };++ const commitSettingsImmediately = (nextSettings: GenerateSettings) => {+ const previousSettings = latestSettingsRef.current;+ const settingsToCommit = getSettingsWithLatestPromptFields(+ nextSettings,+ applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdateRef.current)+ );++ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ pendingUpdateRef.current = null;+ latestSettingsRef.current = settingsToCommit;+ setDraft(settingsToCommit);++ if (!Object.is(previousSettings, settingsToCommit)) {+ onCommitSettings(settingsToCommit);+ }+ };++ const commitPatchImmediately = (patch: Partial<GenerateSettings>) => {+ const previousSettings = latestSettingsRef.current;+ const nextSettings = applyGenerateSettingsPatch(+ applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdateRef.current),+ patch+ );++ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }++ pendingUpdateRef.current = null;+ latestSettingsRef.current = nextSettings;+ setDraft(nextSettings);+ onPatchSettingsRef.current(getChangedGenerateSettingsPatch(previousSettings, nextSettings));};return (<Stack gap="1" px={1}>- <GeneratePromptFields selectedModel={selectedModel} settings={settings} onCommit={commit} />+ <GeneratePromptFields+ projectId={projectId}+ selectedModel={selectedModel}+ settings={draftSettings}+ onCommit={commitPromptDraftPatch}+ onCommitImmediate={commitPatchImmediately}+ />- <GenerateDimensionFields selectedModel={selectedModel} settings={settings} onCommit={commit} />+ <GenerateDimensionFields+ projectId={projectId}+ selectedModel={selectedModel}+ settings={draftSettings}+ onCommit={commit}+ /><GenerateModelFieldsselectedModel={selectedModel}- settings={settings}+ settings={draftSettings}vaeModels={vaeModels}onCommit={commit}- onCommitSettings={onCommitSettings}+ onCommitSettings={commitSettingsImmediately}/><GenerateConceptsSectionloraModels={loraModels}+ projectId={projectId}selectedModel={selectedModel}- settings={settings}- onCommit={commit}+ settings={draftSettings}+ onCommit={commitDebouncedDraftUpdate}+ onCommitImmediate={commitPatchImmediately}/>- <GenerateComponentsSection selectedModel={selectedModel} settings={settings} onCommit={commit} />+ <GenerateComponentsSection+ selectedModel={selectedModel}+ settings={draftSettings}+ onCommit={commitPatchImmediately}+ />- <GenerateAdvancedFields selectedModel={selectedModel} settings={settings} onCommit={commit} />+ <GenerateAdvancedFields+ selectedModel={selectedModel}+ settings={draftSettings}+ onCommit={commit}+ onCommitImmediate={commitPatchImmediately}+ />{isLoadingModels ? (<Text color="fg.subtle" fontSize="2xs">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsxindex 39cecbfc2c..5f53f15bbc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx@@ -17,11 +17,12 @@ import {normalizeGenerateWidgetValues,syncGenerateWidgetValuesWithModels,} from '@workbench/generation/settings';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { useEffect, useMemo } from 'react';+import { areProjectGenerateFormValuesEqual, getGenerateFormCommitPatch } from './generateFormViewModel';import { GenerateSettingsForm } from './GenerateSettingsForm';const getSettingsWithAutoComponentSource = (@@ -39,9 +40,16 @@ const getSettingsWithAutoComponentSource = (};export const GenerateWidgetView = () => {- const storedValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));+ const storedSelection = useActiveProjectSelector(+ (project) => ({ projectId: project.id, values: getProjectWidgetValues(project, 'generate') }),+ areProjectGenerateFormValuesEqual+ );+ const projectId = storedSelection.projectId;+ const storedValues = storedSelection.values;const dispatch = useWorkbenchDispatch();- const { error, models, status } = useModelsSnapshot();+ const error = useModelsSelector((snapshot) => snapshot.error);+ const models = useModelsSelector((snapshot) => snapshot.models);+ const status = useModelsSelector((snapshot) => snapshot.status);useEffect(() => {ensureModelsLoaded();@@ -83,8 +91,12 @@ export const GenerateWidgetView = () => {return;}- dispatch({ type: 'setGenerateSettings', values: { ...nextSettings, model } });- }, [dispatch, models, selectedModel, settings, storedValues, supportedModels]);+ dispatch({+ projectId,+ type: 'patchGenerateSettings',+ values: getGenerateFormCommitPatch({ ...nextSettings, model }),+ });+ }, [dispatch, models, projectId, selectedModel, settings, storedValues, supportedModels]);const commitSettings = (nextSettings: GenerateSettings) => {const model = supportedModels.find((candidate) => candidate.key === nextSettings.modelKey);@@ -94,21 +106,28 @@ export const GenerateWidgetView = () => {}dispatch({- type: 'setGenerateSettings',- values: { ...getSettingsWithAutoComponentSource(nextSettings, model, models), model },+ projectId,+ type: 'patchGenerateSettings',+ values: getGenerateFormCommitPatch({ ...getSettingsWithAutoComponentSource(nextSettings, model, models), model }),});};+ const patchSettings = (values: Partial<GenerateSettings>) => {+ dispatch({ projectId, type: 'patchGenerateSettings', values });+ };+return (<GenerateSettingsFormisLoadingModels={status === 'idle' || status === 'loading'}loadError={error}loraModels={loraModels}+ projectId={projectId}selectedModel={selectedModel}settings={settings}supportedModels={supportedModels}vaeModels={vaeModels}onCommitSettings={commitSettings}+ onPatchSettings={patchSettings}/>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.tsnew file mode 100644index 0000000000..7c492804ef--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDebounce.ts@@ -0,0 +1,53 @@+import type { GenerateSettings } from '@workbench/generation/types';++export type GenerateSettingsUpdate = Partial<GenerateSettings> | ((settings: GenerateSettings) => GenerateSettings);++export type PendingGenerateSettingsUpdate = ((settings: GenerateSettings) => GenerateSettings) | null;++export const applyGenerateSettingsPatch = (+ settings: GenerateSettings,+ patch: Partial<GenerateSettings> | null+): GenerateSettings => (patch ? { ...settings, ...patch } : settings);++const getGenerateSettingsUpdater = (+ update: GenerateSettingsUpdate+): ((settings: GenerateSettings) => GenerateSettings) => {+ if (typeof update === 'function') {+ return update;+ }++ return (settings) => applyGenerateSettingsPatch(settings, update);+};++export const mergeGenerateSettingsUpdate = (+ pendingUpdate: PendingGenerateSettingsUpdate,+ update: GenerateSettingsUpdate+): PendingGenerateSettingsUpdate => {+ const updater = getGenerateSettingsUpdater(update);++ if (!pendingUpdate) {+ return updater;+ }++ return (settings) => updater(pendingUpdate(settings));+};++export const applyGenerateSettingsUpdate = (+ settings: GenerateSettings,+ update: PendingGenerateSettingsUpdate+): GenerateSettings => (update ? update(settings) : settings);++export const getChangedGenerateSettingsPatch = (+ current: GenerateSettings,+ next: GenerateSettings+): Partial<GenerateSettings> => {+ const patch: Partial<GenerateSettings> = {};++ for (const key of Object.keys(next) as Array<keyof GenerateSettings>) {+ if (!Object.is(current[key], next[key])) {+ patch[key] = next[key] as never;+ }+ }++ return patch;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.tsnew file mode 100644index 0000000000..320703c4aa--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateDraftRegistry.ts@@ -0,0 +1,29 @@+import { useEffect, useRef } from 'react';++type DraftFlusher = () => void;++const draftFlushers = new Set<DraftFlusher>();++export const flushGenerateDrafts = (): void => {+ const flushers = Array.from(draftFlushers);++ for (const flushDraft of flushers) {+ flushDraft();+ }+};++export const useRegisterGenerateDraftFlusher = (flushDraft: DraftFlusher): void => {+ const flushDraftRef = useRef(flushDraft);++ flushDraftRef.current = flushDraft;++ useEffect(() => {+ const registeredFlushDraft = () => flushDraftRef.current();++ draftFlushers.add(registeredFlushDraft);++ return () => {+ draftFlushers.delete(registeredFlushDraft);+ };+ }, []);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.tsnew file mode 100644index 0000000000..d54754930b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.test.ts@@ -0,0 +1,114 @@+import type { GenerateSettings } from '@workbench/generation/types';++import { describe, expect, it } from 'vitest';++import {+ areGenerateFormValuesEqual,+ areProjectGenerateFormValuesEqual,+ getGenerateFormCommitPatch,+ getSettingsWithLatestPromptFields,+} from './generateFormViewModel';++const createSettings = (overrides: Partial<GenerateSettings> = {}): GenerateSettings =>+ ({+ aspectRatioId: '1:1',+ aspectRatioIsLocked: false,+ aspectRatioValue: 1,+ batchCount: 1,+ cfgRescaleMultiplier: 0,+ cfgScale: 7,+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ clipSkip: 0,+ colorCompensation: false,+ componentSourceModel: null,+ height: 1024,+ loras: [],+ modelKey: 'model-a',+ negativePrompt: 'old negative',+ negativePromptEnabled: true,+ negativePromptHeightPx: 56,+ positivePrompt: 'old positive',+ positivePromptHeightPx: 96,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ scheduler: 'euler_a',+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: 123,+ shouldRandomizeSeed: false,+ steps: 30,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: 'fp32',+ width: 1024,+ ...overrides,+ }) as GenerateSettings;++describe('getSettingsWithLatestPromptFields', () => {+ it('preserves latest prompt fields when committing a full settings object', () => {+ const staleFullSettings = createSettings({ cfgScale: 9, modelKey: 'model-b', positivePrompt: 'stale positive' });+ const latestSettings = createSettings({+ negativePrompt: 'latest negative',+ negativePromptEnabled: false,+ negativePromptHeightPx: 72,+ positivePrompt: 'latest positive',+ positivePromptHeightPx: 144,+ });++ expect(getSettingsWithLatestPromptFields(staleFullSettings, latestSettings)).toMatchObject({+ cfgScale: 9,+ modelKey: 'model-b',+ negativePrompt: 'latest negative',+ negativePromptEnabled: false,+ negativePromptHeightPx: 72,+ positivePrompt: 'latest positive',+ positivePromptHeightPx: 144,+ });+ });+});++describe('areGenerateFormValuesEqual', () => {+ it('ignores values owned by prompt fields and topbar batch count', () => {+ expect(+ areGenerateFormValuesEqual(+ { batchCount: 1, positivePrompt: 'first', steps: 30 },+ { batchCount: 4, positivePrompt: 'second', steps: 30 }+ )+ ).toBe(true);+ });++ it('detects changes rendered by the form', () => {+ expect(areGenerateFormValuesEqual({ batchCount: 1, steps: 30 }, { batchCount: 1, steps: 40 })).toBe(false);+ });+});++describe('areProjectGenerateFormValuesEqual', () => {+ it('treats a project switch as a value change even when only ignored form fields differ', () => {+ expect(+ areProjectGenerateFormValuesEqual(+ { projectId: 'project-a', values: { positivePrompt: 'project a', steps: 30 } },+ { projectId: 'project-b', values: { positivePrompt: 'project b', steps: 30 } }+ )+ ).toBe(false);+ });++ it('still ignores prompt-owned and topbar-owned values within the same project', () => {+ expect(+ areProjectGenerateFormValuesEqual(+ { projectId: 'project-a', values: { batchCount: 1, positivePrompt: 'first', steps: 30 } },+ { projectId: 'project-a', values: { batchCount: 4, positivePrompt: 'second', steps: 30 } }+ )+ ).toBe(true);+ });+});++describe('getGenerateFormCommitPatch', () => {+ it('omits topbar-owned batch count from full form commits', () => {+ const patch = getGenerateFormCommitPatch(createSettings({ batchCount: 8, positivePrompt: 'keep prompt' }));++ expect(patch.batchCount).toBeUndefined();+ expect(patch.positivePrompt).toBe('keep prompt');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.tsnew file mode 100644index 0000000000..ea858e4b81--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateFormViewModel.ts@@ -0,0 +1,74 @@+import type { GenerateSettings, GenerateWidgetValues } from '@workbench/generation/types';++import { createStableSelector } from '@workbench/workbenchSelectors';++const PROMPT_FORM_KEYS = [+ 'negativePrompt',+ 'negativePromptEnabled',+ 'negativePromptHeightPx',+ 'positivePrompt',+ 'positivePromptHeightPx',+] as const satisfies readonly (keyof GenerateSettings)[];+const EXTERNAL_GENERATE_FORM_KEYS = [+ ...PROMPT_FORM_KEYS,+ 'batchCount',+] as const satisfies readonly (keyof GenerateSettings)[];+const EXTERNAL_GENERATE_FORM_KEY_SET = new Set<string>(EXTERNAL_GENERATE_FORM_KEYS);++export const areGenerateFormValuesEqual = (left: Record<string, unknown>, right: Record<string, unknown>): boolean => {+ if (left === right) {+ return true;+ }++ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);++ for (const key of keys) {+ if (EXTERNAL_GENERATE_FORM_KEY_SET.has(key)) {+ continue;+ }++ if (!Object.is(left[key], right[key])) {+ return false;+ }+ }++ return true;+};++export interface ProjectGenerateFormValuesSelection {+ projectId: string;+ values: Record<string, unknown>;+}++export const areProjectGenerateFormValuesEqual = (+ left: ProjectGenerateFormValuesSelection,+ right: ProjectGenerateFormValuesSelection+): boolean => left.projectId === right.projectId && areGenerateFormValuesEqual(left.values, right.values);++export const createGenerateFormValuesSelector = () =>+ createStableSelector((values: Record<string, unknown>) => values, areGenerateFormValuesEqual);++export const getSettingsWithLatestPromptFields = (+ settings: GenerateSettings,+ latestSettings: GenerateSettings+): GenerateSettings => {+ let nextSettings = settings;++ for (const key of PROMPT_FORM_KEYS) {+ if (!Object.is(nextSettings[key], latestSettings[key])) {+ nextSettings = { ...nextSettings, [key]: latestSettings[key] };+ }+ }++ return nextSettings;+};++export const getGenerateFormCommitPatch = (+ settings: GenerateSettings & Partial<Pick<GenerateWidgetValues, 'model'>>+): Partial<GenerateWidgetValues> => {+ const patch: Partial<GenerateWidgetValues> = { ...settings };++ delete patch.batchCount;++ return patch;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsxindex 5857ed8fda..eb204ffe5b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx@@ -3,26 +3,58 @@ import type { PromptHistoryItem } from '@workbench/types';import { Stack } from '@chakra-ui/react';import { getPromptPolicy } from '@workbench/generation/baseGenerationPolicies';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWidgetValuesSelector } from '@workbench/WorkbenchContext';import { NegativePromptField } from './NegativePromptField';import { PositivePromptField } from './PositivePromptField';interface GeneratePromptFieldsProps {settings: GenerateSettings;+ projectId: string;selectedModel: GenerateModelConfig | undefined;onCommit: (patch: Partial<GenerateSettings>) => void;+ onCommitImmediate: (patch: Partial<GenerateSettings>) => void;}-export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: GeneratePromptFieldsProps) => {+interface GeneratePromptValues {+ negativePrompt: string;+ negativePromptEnabled: boolean;+ negativePromptHeightPx: number;+ positivePrompt: string;+ positivePromptHeightPx: number;+}++const getPromptValues = (values: Record<string, unknown>): GeneratePromptValues => ({+ negativePrompt: typeof values.negativePrompt === 'string' ? values.negativePrompt : '',+ negativePromptEnabled: values.negativePromptEnabled !== false,+ negativePromptHeightPx: typeof values.negativePromptHeightPx === 'number' ? values.negativePromptHeightPx : 56,+ positivePrompt: typeof values.positivePrompt === 'string' ? values.positivePrompt : '',+ positivePromptHeightPx: typeof values.positivePromptHeightPx === 'number' ? values.positivePromptHeightPx : 96,+});++const arePromptValuesEqual = (left: GeneratePromptValues, right: GeneratePromptValues): boolean =>+ left.positivePrompt === right.positivePrompt &&+ left.negativePrompt === right.negativePrompt &&+ left.positivePromptHeightPx === right.positivePromptHeightPx &&+ left.negativePromptHeightPx === right.negativePromptHeightPx &&+ left.negativePromptEnabled === right.negativePromptEnabled;++export const GeneratePromptFields = ({+ onCommit,+ onCommitImmediate,+ projectId,+ selectedModel,+ settings,+}: GeneratePromptFieldsProps) => {const showSyntaxHighlighting = useActiveProjectSelector((project) => project.settings.showPromptSyntaxHighlighting);+ const promptValues = useWidgetValuesSelector('generate', getPromptValues, arePromptValuesEqual);const promptPolicy = getPromptPolicy(selectedModel, settings);const usePromptHistoryItem = (prompt: PromptHistoryItem) => {- onCommit(+ onCommitImmediate(promptPolicy.negativeVisible? {negativePrompt: prompt.negativePrompt ?? '',- negativePromptEnabled: prompt.negativePrompt ? true : settings.negativePromptEnabled,+ negativePromptEnabled: prompt.negativePrompt ? true : promptValues.negativePromptEnabled,positivePrompt: prompt.positivePrompt,}: { positivePrompt: prompt.positivePrompt }@@ -32,27 +64,29 @@ export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: Genereturn (<Stack gap="1" py="2"><PositivePromptField- heightPx={settings.positivePromptHeightPx}- value={settings.positivePrompt}+ heightPx={promptValues.positivePromptHeightPx}+ value={promptValues.positivePrompt}loras={settings.loras}+ projectId={projectId}selectedModel={selectedModel}showSyntaxHighlighting={showSyntaxHighlighting}onChange={(positivePrompt) => onCommit({ positivePrompt })}- onResizeEnd={(positivePromptHeightPx) => onCommit({ positivePromptHeightPx })}+ onResizeEnd={(positivePromptHeightPx) => onCommitImmediate({ positivePromptHeightPx })}onUsePrompt={usePromptHistoryItem}/>{promptPolicy.negativeVisible ? (<NegativePromptField- heightPx={settings.negativePromptHeightPx}- isEnabled={settings.negativePromptEnabled}+ heightPx={promptValues.negativePromptHeightPx}+ isEnabled={promptValues.negativePromptEnabled}loras={settings.loras}+ projectId={projectId}selectedModel={selectedModel}helpText={promptPolicy.negativeHelpText}showSyntaxHighlighting={showSyntaxHighlighting}- value={settings.negativePrompt}- onEnabledChange={(negativePromptEnabled) => onCommit({ negativePromptEnabled })}+ value={promptValues.negativePrompt}+ onEnabledChange={(negativePromptEnabled) => onCommitImmediate({ negativePromptEnabled })}onChange={(negativePrompt) => onCommit({ negativePrompt })}- onResizeEnd={(negativePromptHeightPx) => onCommit({ negativePromptHeightPx })}+ onResizeEnd={(negativePromptHeightPx) => onCommitImmediate({ negativePromptHeightPx })}/>) : null}</Stack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsxindex b8a6f97559..f46e43146e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx@@ -3,18 +3,24 @@ import type { ChangeEvent, KeyboardEvent } from 'react';import { HStack, Switch } from '@chakra-ui/react';import { Field } from '@workbench/components/ui';+import { useRegisterGenerateDraftFlusher } from '@workbench/widgets/generate/generateDraftRegistry';+import { useDebouncedDraftValue } from '@workbench/widgets/generate/useDebouncedDraftValue';import { useRef, useState } from 'react';import { AddPromptTriggerButton, PromptTriggerPopover } from './PositivePromptActions';import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';import { insertPromptText, type PromptTextRange } from './promptFocus';+import { resetPromptHistoryNavigation } from './promptHistoryNavigation';import { PromptTextarea } from './PromptTextarea';+const PROMPT_INPUT_DEBOUNCE_MS = 250;+interface NegativePromptFieldProps {heightPx: number;helpText?: string;isEnabled: boolean;loras: GenerateLora[];+ projectId: string;selectedModel: GenerateModelConfig | undefined;showSyntaxHighlighting: boolean;value: string;@@ -36,12 +42,26 @@ export const NegativePromptField = ({onChange,onEnabledChange,onResizeEnd,+ projectId,selectedModel,showSyntaxHighlighting,value,}: NegativePromptFieldProps) => {const textareaRef = useRef<HTMLTextAreaElement | null>(null);const [triggerPickerState, setTriggerPickerState] = useState<PromptTriggerPickerState | null>(null);+ const { draftValue, flushDraftValue, setDraftValue } = useDebouncedDraftValue({+ delayMs: PROMPT_INPUT_DEBOUNCE_MS,+ onCommit: onChange,+ resetKey: projectId,+ value,+ });++ useRegisterGenerateDraftFlusher(flushDraftValue);++ const commitPromptChange = (nextValue: string) => {+ resetPromptHistoryNavigation();+ setDraftValue(nextValue);+ };const openPromptTriggerPicker = (anchorElement: HTMLElement, range?: PromptTextRange) => {const rect = anchorElement.getBoundingClientRect();@@ -68,11 +88,11 @@ export const NegativePromptField = ({const selectPromptTrigger = (trigger: string) => {insertPromptText({- onChange,+ onChange: commitPromptChange,range: triggerPickerState?.range,textarea: textareaRef.current,text: trigger,- value,+ value: draftValue,});closePromptTriggerPicker();};@@ -114,19 +134,21 @@ export const NegativePromptField = ({textareaRef={(element) => {textareaRef.current = element;}}- value={value}- onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}+ value={draftValue}+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => commitPromptChange(event.currentTarget.value)}onKeyDown={handlePromptKeyDown}onResizeEnd={onResizeEnd}/>- <PromptTriggerPopover- loras={loras}- open={triggerPickerState !== null}- positioning={{ getAnchorRect: () => triggerPickerState?.anchorRect ?? null }}- selectedModel={selectedModel}- onClose={closePromptTriggerPicker}- onSelect={selectPromptTrigger}- />+ {triggerPickerState ? (+ <PromptTriggerPopover+ loras={loras}+ open+ positioning={{ getAnchorRect: () => triggerPickerState.anchorRect }}+ selectedModel={selectedModel}+ onClose={closePromptTriggerPicker}+ onSelect={selectPromptTrigger}+ />+ ) : null}</>) : null}</Field>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsxindex 33e3e3e0a3..12350e6d85 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx@@ -10,8 +10,13 @@ import { filterPromptHistory } from '@workbench/generation/promptHistory';import { expandPrompt, imageToPrompt } from '@workbench/generation/promptUtilities';import { getSelectedGalleryImage } from '@workbench/image-actions';import { ModelSelect } from '@workbench/models/components/ModelSelect';-import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';-import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+import {+ shallowEqual,+ useActiveProjectId,+ useActiveProjectSelector,+ useWorkbenchDispatch,+} from '@workbench/WorkbenchContext';import {BookDashedIcon,CurlyBracesIcon,@@ -22,7 +27,7 @@ import {TrashIcon,Undo2Icon,} from 'lucide-react';-import { useEffect, useId, useState } from 'react';+import { useEffect, useId, useRef, useState } from 'react';const DISABLED_PROMPT_ACTIONS = [{ icon: BookDashedIcon, label: 'Prompt Template' },@@ -35,16 +40,18 @@ interface PositivePromptActionsProps {onUsePrompt: (prompt: PromptHistoryItem) => void;positivePrompt: string;selectedModel: GenerateModelConfig | undefined;+ projectId: string;onOpenPromptTriggerPicker: (anchorElement: HTMLElement) => void;- onPositivePromptChange: (prompt: string) => void;+ onPositivePromptChangeImmediate: (prompt: string) => void;}export const PositivePromptActions = ({isPromptTriggerPickerOpen,onOpenPromptTriggerPicker,- onPositivePromptChange,+ onPositivePromptChangeImmediate,onUsePrompt,positivePrompt,+ projectId,}: PositivePromptActionsProps) => (<HStack gap="0.5"><AddPromptTriggerButton isOpen={isPromptTriggerPickerOpen} onOpenPromptTriggerPicker={onOpenPromptTriggerPicker} />@@ -55,8 +62,12 @@ export const PositivePromptActions = ({</IconButton></Tooltip>))}- <ExpandPromptButton onPositivePromptChange={onPositivePromptChange} positivePrompt={positivePrompt} />- <ImageToPromptButton onPositivePromptChange={onPositivePromptChange} />+ <ExpandPromptButton+ positivePrompt={positivePrompt}+ projectId={projectId}+ onPositivePromptChange={onPositivePromptChangeImmediate}+ />+ <ImageToPromptButton projectId={projectId} onPositivePromptChange={onPositivePromptChangeImmediate} /><PositivePromptHistoryButton onUsePrompt={onUsePrompt} /></HStack>);@@ -161,7 +172,7 @@ export const PromptTriggerPopover = ({onClose: () => void;onSelect: (trigger: string) => void;}) => {- const { models } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);const [searchTerm, setSearchTerm] = useState('');const options = getPromptTriggerOptions({ loras, models, selectedModel });const filteredOptions = options.filter((option) => {@@ -263,9 +274,16 @@ export const PromptTriggerPopover = ({const ExpandPromptButton = ({onPositivePromptChange,positivePrompt,-}: Pick<PositivePromptActionsProps, 'onPositivePromptChange' | 'positivePrompt'>) => {+ projectId,+}: {+ positivePrompt: string;+ projectId: string;+ onPositivePromptChange: (prompt: string) => void;+}) => {const dispatch = useWorkbenchDispatch();- const { models } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);+ const activeProjectId = useActiveProjectId();+ const activeProjectIdRef = useRef(activeProjectId);const triggerId = useId();const [isOpen, setIsOpen] = useState(false);const [isLoading, setIsLoading] = useState(false);@@ -273,6 +291,8 @@ const ExpandPromptButton = ({const textLlmModels = models.filter((model) => model.type === 'text_llm');const selectedModel = selectedModelKey ? textLlmModels.find((model) => model.key === selectedModelKey) : null;+ activeProjectIdRef.current = activeProjectId;+useEffect(() => {ensureModelsLoaded();}, []);@@ -287,7 +307,7 @@ const ExpandPromptButton = ({try {const result = await expandPrompt({ model_key: selectedModel.key, prompt: positivePrompt });- if (result.expanded_prompt) {+ if (result.expanded_prompt && activeProjectIdRef.current === projectId) {onPositivePromptChange(result.expanded_prompt);}@@ -365,10 +385,16 @@ const ExpandPromptButton = ({const ImageToPromptButton = ({onPositivePromptChange,-}: Pick<PositivePromptActionsProps, 'onPositivePromptChange'>) => {+ projectId,+}: {+ projectId: string;+ onPositivePromptChange: (prompt: string) => void;+}) => {const dispatch = useWorkbenchDispatch();- const { models } = useModelsSnapshot();+ const models = useModelsSelector((snapshot) => snapshot.models);const selectedImage = useActiveProjectSelector(getSelectedGalleryImage, shallowEqual);+ const activeProjectId = useActiveProjectId();+ const activeProjectIdRef = useRef(activeProjectId);const triggerId = useId();const [isOpen, setIsOpen] = useState(false);const [isLoading, setIsLoading] = useState(false);@@ -376,6 +402,8 @@ const ImageToPromptButton = ({const llavaModels = models.filter((model) => model.type === 'llava_onevision');const selectedModel = selectedModelKey ? llavaModels.find((model) => model.key === selectedModelKey) : null;+ activeProjectIdRef.current = activeProjectId;+useEffect(() => {ensureModelsLoaded();}, []);@@ -390,7 +418,7 @@ const ImageToPromptButton = ({try {const result = await imageToPrompt({ image_name: selectedImage.imageName, model_key: selectedModel.key });- if (result.prompt) {+ if (result.prompt && activeProjectIdRef.current === projectId) {onPositivePromptChange(result.prompt);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsxindex c396f82971..04bf899185 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx@@ -3,6 +3,8 @@ import type { PromptHistoryItem } from '@workbench/types';import type { ChangeEvent, KeyboardEvent } from 'react';import { Field } from '@workbench/components/ui';+import { useRegisterGenerateDraftFlusher } from '@workbench/widgets/generate/generateDraftRegistry';+import { useDebouncedDraftValue } from '@workbench/widgets/generate/useDebouncedDraftValue';import { useRef, useState } from 'react';import { PositivePromptActions, PromptTriggerPopover } from './PositivePromptActions';@@ -11,9 +13,12 @@ import { insertPromptText, type PromptTextRange, registerPositivePromptElement }import { resetPromptHistoryNavigation } from './promptHistoryNavigation';import { PromptTextarea } from './PromptTextarea';+const PROMPT_INPUT_DEBOUNCE_MS = 250;+interface PositivePromptFieldProps {heightPx: number;loras: GenerateLora[];+ projectId: string;selectedModel: GenerateModelConfig | undefined;showSyntaxHighlighting: boolean;value: string;@@ -33,16 +38,30 @@ export const PositivePromptField = ({onChange,onResizeEnd,onUsePrompt,+ projectId,selectedModel,showSyntaxHighlighting,value,}: PositivePromptFieldProps) => {const textareaRef = useRef<HTMLTextAreaElement | null>(null);const [triggerPickerState, setTriggerPickerState] = useState<PromptTriggerPickerState | null>(null);+ const { commitDraftValue, draftValue, flushDraftValue, replaceDraftValue, setDraftValue } = useDebouncedDraftValue({+ delayMs: PROMPT_INPUT_DEBOUNCE_MS,+ onCommit: onChange,+ resetKey: projectId,+ value,+ });++ useRegisterGenerateDraftFlusher(flushDraftValue);const commitPromptChange = (nextValue: string) => {resetPromptHistoryNavigation();- onChange(nextValue);+ setDraftValue(nextValue);+ };++ const commitPromptChangeImmediately = (nextValue: string) => {+ resetPromptHistoryNavigation();+ commitDraftValue(nextValue);};const openPromptTriggerPicker = (anchorElement: HTMLElement, range?: PromptTextRange) => {@@ -74,11 +93,16 @@ export const PositivePromptField = ({range: triggerPickerState?.range,textarea: textareaRef.current,text: trigger,- value,+ value: draftValue,});closePromptTriggerPicker();};+ const handleUsePrompt = (prompt: PromptHistoryItem) => {+ replaceDraftValue(prompt.positivePrompt);+ onUsePrompt(prompt);+ };+const handleTextareaRef = (element: HTMLTextAreaElement | null) => {textareaRef.current = element;registerPositivePromptElement(element);@@ -91,11 +115,12 @@ export const PositivePromptField = ({<PositivePromptActionsisPromptTriggerPickerOpen={triggerPickerState !== null}loras={loras}- positivePrompt={value}+ positivePrompt={draftValue}+ projectId={projectId}selectedModel={selectedModel}onOpenPromptTriggerPicker={(anchorElement) => openPromptTriggerPicker(anchorElement)}- onPositivePromptChange={commitPromptChange}- onUsePrompt={onUsePrompt}+ onPositivePromptChangeImmediate={commitPromptChangeImmediately}+ onUsePrompt={handleUsePrompt}/>}>@@ -110,19 +135,21 @@ export const PositivePromptField = ({fontFamily="mono"showSyntaxHighlighting={showSyntaxHighlighting}textareaRef={handleTextareaRef}- value={value}+ value={draftValue}onChange={(event: ChangeEvent<HTMLTextAreaElement>) => commitPromptChange(event.currentTarget.value)}onKeyDown={handlePromptKeyDown}onResizeEnd={onResizeEnd}/>- <PromptTriggerPopover- loras={loras}- open={triggerPickerState !== null}- positioning={{ getAnchorRect: () => triggerPickerState?.anchorRect ?? null }}- selectedModel={selectedModel}- onClose={closePromptTriggerPicker}- onSelect={selectPromptTrigger}- />+ {triggerPickerState ? (+ <PromptTriggerPopover+ loras={loras}+ open+ positioning={{ getAnchorRect: () => triggerPickerState.anchorRect }}+ selectedModel={selectedModel}+ onClose={closePromptTriggerPicker}+ onSelect={selectPromptTrigger}+ />+ ) : null}</Field>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsxindex fb2b8ccdb1..09e4803e7d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx@@ -120,7 +120,6 @@ export const PromptTextarea = ({const underlay = shouldHighlight ? (<Boxaria-hidden="true"- bg="bg.emphasized"borderColor="transparent"borderRadius="md"borderWidth="1px"diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.tsindex 2eec6c55d1..c86b6d76d1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts@@ -11,6 +11,7 @@ import { getProjectWidgetValues } from '@workbench/widgetState';import { isPositivePromptFocused } from './promptFocus';type NavigationState = {+ projectId: string;historyIndex: number;stashedPrompts: {negativePrompt: string;@@ -65,7 +66,7 @@ const applyPromptHistoryIndex = ({values.negativePromptEnabled = prompt.negativePrompt ? true : settings.negativePromptEnabled;}- dispatch({ type: 'patchWidgetValues', values, widgetId: 'generate' });+ dispatch({ projectId: project.id, type: 'patchWidgetValues', values, widgetId: 'generate' });};export const navigatePromptHistory = ({@@ -79,6 +80,10 @@ export const navigatePromptHistory = ({models: readonly ModelConfig[] | undefined;project: Project;}): void => {+ if (navigationState?.projectId !== project.id) {+ navigationState = null;+ }+if (!isPositivePromptFocused() || project.promptHistory.length === 0) {return;}@@ -93,6 +98,7 @@ export const navigatePromptHistory = ({if (!navigationState) {navigationState = {historyIndex: 0,+ projectId: project.id,stashedPrompts: {negativePrompt: settings.negativePrompt,negativePromptEnabled: settings.negativePromptEnabled,@@ -115,6 +121,7 @@ export const navigatePromptHistory = ({if (nextHistoryIndex < 0) {dispatch({+ projectId: project.id,type: 'patchWidgetValues',values: navigationState.stashedPrompts,widgetId: 'generate',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/useDebouncedDraftValue.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/useDebouncedDraftValue.tsnew file mode 100644index 0000000000..d2cb4bcc61--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/useDebouncedDraftValue.ts@@ -0,0 +1,143 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react';++interface UseDebouncedDraftValueOptions<Value> {+ value: Value;+ delayMs: number;+ onCommit: (value: Value) => void;+ isEqual?: (left: Value, right: Value) => boolean;+ flushOnUnmount?: boolean;+ resetKey?: string;+}++interface DebouncedDraftValue<Value> {+ draftValue: Value;+ setDraftValue: (value: Value) => void;+ commitDraftValue: (value: Value) => void;+ replaceDraftValue: (value: Value) => void;+ flushDraftValue: () => void;+ hasPendingDraft: () => boolean;+}++export const useDebouncedDraftValue = <Value>({+ delayMs,+ flushOnUnmount = true,+ isEqual = Object.is,+ onCommit,+ resetKey,+ value,+}: UseDebouncedDraftValueOptions<Value>): DebouncedDraftValue<Value> => {+ const [draftValue, setDraftValueState] = useState(value);+ const draftValueRef = useRef(value);+ const sourceValueRef = useRef(value);+ const resetKeyRef = useRef(resetKey);+ const hasPendingDraftRef = useRef(false);+ const pendingDraftRef = useRef<Value | null>(null);+ const timeoutRef = useRef<number | null>(null);+ const flushOnUnmountRef = useRef(flushOnUnmount);+ const onCommitRef = useRef(onCommit);++ flushOnUnmountRef.current = flushOnUnmount;+ onCommitRef.current = onCommit;++ const setDraft = (nextValue: Value) => {+ draftValueRef.current = nextValue;+ setDraftValueState(nextValue);+ };++ const clearPendingCommit = () => {+ if (timeoutRef.current !== null) {+ window.clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }+ };++ const clearPendingDraft = () => {+ clearPendingCommit();+ hasPendingDraftRef.current = false;+ pendingDraftRef.current = null;+ };++ const flushDraftValue = () => {+ if (!hasPendingDraftRef.current) {+ return;+ }++ const valueToCommit = pendingDraftRef.current as Value;++ clearPendingDraft();+ onCommitRef.current(valueToCommit);+ };++ useLayoutEffect(() => {+ if (resetKeyRef.current !== resetKey) {+ resetKeyRef.current = resetKey;+ clearPendingDraft();+ sourceValueRef.current = value;+ setDraft(value);+ return;+ }++ if (isEqual(sourceValueRef.current, value)) {+ return;+ }++ sourceValueRef.current = value;++ if (!hasPendingDraftRef.current) {+ setDraft(value);+ return;+ }++ if (isEqual(pendingDraftRef.current as Value, value)) {+ clearPendingDraft();+ setDraft(value);+ return;+ }++ clearPendingDraft();+ setDraft(value);+ }, [isEqual, resetKey, value]);++ useEffect(+ () => () => {+ clearPendingCommit();++ if (flushOnUnmountRef.current) {+ flushDraftValue();+ return;+ }++ clearPendingDraft();+ },+ []+ );++ const setDraftValue = (nextValue: Value) => {+ setDraft(nextValue);+ hasPendingDraftRef.current = true;+ pendingDraftRef.current = nextValue;+ clearPendingCommit();++ timeoutRef.current = window.setTimeout(flushDraftValue, delayMs);+ };++ const commitDraftValue = (nextValue: Value) => {+ clearPendingDraft();+ setDraft(nextValue);+ onCommitRef.current(nextValue);+ };++ const replaceDraftValue = (nextValue: Value) => {+ clearPendingDraft();+ setDraft(nextValue);+ };++ return {+ commitDraftValue,+ draftValue,+ flushDraftValue,+ hasPendingDraft: () => hasPendingDraftRef.current,+ replaceDraftValue,+ setDraftValue,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex bcee41a696..6570e32091 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -1,11 +1,26 @@import { Box, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { Panel } from '@workbench/components/ui';-import { useActiveProject } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { LayersIcon } from 'lucide-react';export const LayersWidgetView = () => {- const activeProject = useActiveProject();- const layers = activeProject.canvas.document.layers;+ const { eventsCount, graphHistoryCount, layers, redoCount, stagedImageCount, undoCount } = useActiveProjectSelector(+ (project) => ({+ eventsCount: project.events.length,+ graphHistoryCount: project.graphHistory.length,+ layers: project.canvas.document.layers,+ redoCount: project.undoRedo.future.length,+ stagedImageCount: project.canvas.stagingArea.pendingImageIds.length,+ undoCount: project.undoRedo.past.length,+ }),+ (left, right) =>+ left.eventsCount === right.eventsCount &&+ left.graphHistoryCount === right.graphHistoryCount &&+ left.layers === right.layers &&+ left.redoCount === right.redoCount &&+ left.stagedImageCount === right.stagedImageCount &&+ left.undoCount === right.undoCount+ );return (<>@@ -24,7 +39,7 @@ export const LayersWidgetView = () => {><Icon as={LayersIcon} boxSize="6" /><Text fontSize="2xs" textAlign="center">- {layers.length} layers, {activeProject.canvas.stagingArea.pendingImageIds.length} staged images.+ {layers.length} layers, {stagedImageCount} staged images.</Text></Flex><Panel gap="2" p="2">@@ -67,13 +82,13 @@ export const LayersWidgetView = () => {Project Contracts</Text><Text color="fg.subtle" fontSize="2xs">- Graph history: {activeProject.graphHistory.length}+ Graph history: {graphHistoryCount}</Text><Text color="fg.subtle" fontSize="2xs">- Events: {activeProject.events.length}+ Events: {eventsCount}</Text><Text color="fg.subtle" fontSize="2xs">- Undo: {activeProject.undoRedo.past.length} / Redo: {activeProject.undoRedo.future.length}+ Undo: {undoCount} / Redo: {redoCount}</Text></Panel></>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsxindex 4feb343b0f..5ef4fd026d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx@@ -18,10 +18,12 @@ const kindIcon = {} satisfies Record<WorkbenchNotificationKind, LucideIcon>;export const NotificationsWidgetView = ({ presentation, region }: WidgetViewProps) => {- const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);- const unreadCount = notifications.filter((notification) => !notification.isRead).length;- const errorCount = notifications.filter((notification) => notification.kind === 'error').length;- const label = unreadCount > 0 ? `${unreadCount} new` : `${notifications.length} total`;+ const { errorCount, totalCount, unreadCount } = useWorkbenchSelector((snapshot) => ({+ errorCount: snapshot.state.notifications.filter((notification) => notification.kind === 'error').length,+ totalCount: snapshot.state.notifications.length,+ unreadCount: snapshot.state.notifications.filter((notification) => !notification.isRead).length,+ }));+ const label = unreadCount > 0 ? `${unreadCount} new` : `${totalCount} total`;const icon = errorCount > 0 ? TriangleAlertIcon : BellIcon;if (region === 'bottom' && presentation !== 'expanded') {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.tsnew file mode 100644index 0000000000..456a9b3ad9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { getPreviewBoardsRequestKey } from './PreviewWidgetView';++describe('getPreviewBoardsRequestKey', () => {+ it('requests boards for local generated images, not only backend gallery images', () => {+ expect(+ getPreviewBoardsRequestKey({ hasSelectedImage: true, isBackendImage: false, refreshToken: 'refresh-1' })+ ).toBe('refresh-1');+ });++ it('does not request boards without a selected image', () => {+ expect(+ getPreviewBoardsRequestKey({ hasSelectedImage: false, isBackendImage: false, refreshToken: 'refresh-1' })+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex bdcfd63aad..fbf650c9a9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -16,9 +16,16 @@ import {getGalleryCompareImage,getGalleryImagesRefreshToken,getGalleryRecentImagesKey,+ getGalleryRefreshToken,} from '@workbench/widgets/gallery/galleryStateView';+import { createGenerateFormValuesSelector } from '@workbench/widgets/generate/generateFormViewModel';import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import {+ useActiveProjectId,+ useActiveProjectSelector,+ useWidgetValuesSelector,+ useWorkbenchDispatch,+} from '@workbench/WorkbenchContext';import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react';@@ -89,6 +96,15 @@ const getBoardName = (boards: GalleryBoard[], boardId: string): string =>const shouldLoadBackendBoard = (image: PreviewImage): boolean => image.sourceQueueItemId === 'backend-gallery';+export const getPreviewBoardsRequestKey = ({+ hasSelectedImage,+ refreshToken,+}: {+ hasSelectedImage: boolean;+ isBackendImage: boolean;+ refreshToken: string;+}): string | null => (hasSelectedImage ? refreshToken : null);+const previewGridCss = {backgroundImage: 'radial-gradient(circle, currentColor 1px, transparent 1.5px)',backgroundPosition: 'center',@@ -96,9 +112,11 @@ const previewGridCss = {backgroundSize: '24px 24px',} as const;+const selectGenerateRecallValues = createGenerateFormValuesSelector();+export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));- const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));+ const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector((project) => project.settings);@@ -114,6 +132,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const hasSelectedImage = selectedImage !== null;const isBackendImage = selectedImage ? shouldLoadBackendBoard(selectedImage) : false;const { imageOrderDir, starredFirst } = getGallerySettings(galleryValues);+ const boardRefreshToken = getGalleryRefreshToken(galleryValues);const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);const recentImagesKey = getGalleryRecentImagesKey(galleryValues);const [boards, setBoards] = useState<GalleryBoard[]>(fallbackBoards);@@ -130,6 +149,37 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {selectedImageRef.current = selectedImage;boardImagesRef.current = boardImages;+ const boardsRequestKey = getPreviewBoardsRequestKey({+ hasSelectedImage,+ isBackendImage,+ refreshToken: boardRefreshToken,+ });++ useEffect(() => {+ if (boardsRequestKey === null) {+ setBoards(fallbackBoards);+ return;+ }++ let isStale = false;++ listGalleryBoards()+ .then((nextBoards) => {+ if (!isStale) {+ setBoards(nextBoards);+ }+ })+ .catch(() => {+ if (!isStale) {+ setBoards(fallbackBoards);+ }+ });++ return () => {+ isStale = true;+ };+ }, [boardsRequestKey]);+// Deliberately NOT keyed on the selected image object or the gallery's// board selection/sort: the board context only refetches when the image's// own board, the view, the image ordering, or backend contents change.@@ -149,24 +199,20 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {let isStale = false;setIsLoadingBoard(true);- Promise.all([- listGalleryBoards().catch(() => fallbackBoards),- listGalleryImages({- boardId: imageBoardId,- galleryView: selectedGalleryView,- orderDir: imageOrderDir,- searchTerm: '',- starredFirst,- }).catch(() => ({ images: [] as GalleryImage[], total: 0 })),- ])- .then(([nextBoards, nextImagesPage]) => {+ listGalleryImages({+ boardId: imageBoardId,+ galleryView: selectedGalleryView,+ orderDir: imageOrderDir,+ searchTerm: '',+ starredFirst,+ })+ .then((nextImagesPage) => {if (isStale) {return;}const fallbackImage = selectedImageRef.current;- setBoards(nextBoards);setBoardImages(nextImagesPage.images.length ? nextImagesPage.images : fallbackImage ? [fallbackImage] : []);}).catch((error: unknown) => {@@ -241,11 +287,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {},[dispatch]);+ const projectId = useActiveProjectId();const imageActions = useImageActions({boards,dispatch,generateValues,onImagesDeleted,+ projectId,});const contextMenuImage = useMemo<GalleryImage | null>(() => {if (!selectedImage) {@@ -275,12 +323,17 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {dispatch({ image: selectedImage, type: 'setGalleryCompareImage' });return;}++ if (commandId === 'viewer.deleteImage' && selectedImage) {+ void imageActions.deleteImages([selectedImage.imageName]);+ }});useEffect(() => {const hotkeys = [['viewer.toggleViewer', 'Toggle preview', ['z']],['viewer.swapImages', 'Swap comparison images', ['c']],+ ['viewer.deleteImage', 'Delete preview image', ['delete', 'backspace']],] as const;const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [runtime.commands.register({ handler: () => executeViewerHotkey(id), id, title }),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsxindex 0f8227ff05..e59f7bc074 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx@@ -2,10 +2,16 @@ import type { Project } from '@workbench/types';import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';import { Button, IconButton, ConfirmDialog, Field, FieldLabel, Panel } from '@workbench/components/ui';-import { useProjectSync } from '@workbench/projects/syncStore';+import { useProjectSyncSelector } from '@workbench/projects/syncStore';import { useProjectActions } from '@workbench/projects/useProjectActions';import { useNotify } from '@workbench/useNotify';-import { useActiveProject, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { flushGenerateDrafts } from '@workbench/widgets/generate/generateDraftRegistry';+import {+ shallowEqual,+ useActiveProjectSelector,+ useWorkbenchDispatch,+ useWorkbenchSelector,+} from '@workbench/WorkbenchContext';import { ArrowRightIcon, CopyIcon, History as HistoryIcon, Trash2Icon } from 'lucide-react';import { useState, type ReactNode } from 'react';@@ -16,7 +22,19 @@ import { useState, type ReactNode } from 'react';* any of its members.*/export const ProjectWidgetView = () => {- const activeProject = useActiveProject();+ const activeProject = useActiveProjectSelector(+ (project) => ({+ events: project.events,+ graphHistory: project.graphHistory,+ id: project.id,+ name: project.name,+ projectGraph: project.projectGraph,+ queue: project.queue,+ recoveredAt: project.recoveredAt,+ recoveryOf: project.recoveryOf,+ }),+ shallowEqual+ );return (<Stack gap="5" p="3">@@ -27,7 +45,12 @@ export const ProjectWidgetView = () => {);};-const NameSection = ({ project }: { project: Project }) => {+type ProjectPanelViewModel = Pick<+ Project,+ 'events' | 'graphHistory' | 'id' | 'name' | 'projectGraph' | 'queue' | 'recoveredAt' | 'recoveryOf'+>;++const NameSection = ({ project }: { project: ProjectPanelViewModel }) => {const dispatch = useWorkbenchDispatch();const commitName = (value: string) => {@@ -56,7 +79,7 @@ const NameSection = ({ project }: { project: Project }) => {};/** The id whose recovery family this project belongs to. */-const getRecoveryRootId = (project: Project): string => project.recoveryOf ?? project.id;+const getRecoveryRootId = (project: Pick<Project, 'id' | 'recoveryOf'>): string => project.recoveryOf ?? project.id;const formatTimestamp = (timestamp: string | undefined): string => {if (!timestamp) {@@ -68,7 +91,7 @@ const formatTimestamp = (timestamp: string | undefined): string => {return Number.isNaN(date.getTime()) ? 'Unknown time' : date.toLocaleString();};-const RecoverySection = ({ project }: { project: Project }) => {+const RecoverySection = ({ project }: { project: ProjectPanelViewModel }) => {const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);const dispatch = useWorkbenchDispatch();const { deleteProject } = useProjectActions();@@ -105,7 +128,10 @@ const RecoverySection = ({ project }: { project: Project }) => {size="2xs"variant="outline"w="full"- onClick={() => dispatch({ projectId: original.id, type: 'switchProject' })}+ onClick={() => {+ flushGenerateDrafts();+ dispatch({ projectId: original.id, type: 'switchProject' });+ }}><ArrowRightIcon />Open original "{original.name}"@@ -128,7 +154,10 @@ const RecoverySection = ({ project }: { project: Project }) => {color="fg.muted"size="2xs"variant="ghost"- onClick={() => dispatch({ projectId: recovery.id, type: 'switchProject' })}+ onClick={() => {+ flushGenerateDrafts();+ dispatch({ projectId: recovery.id, type: 'switchProject' });+ }}><ArrowRightIcon /></IconButton>@@ -160,12 +189,11 @@ const RecoverySection = ({ project }: { project: Project }) => {);};-const DetailsSection = ({ project }: { project: Project }) => {+const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);const lastSavedAt = useWorkbenchSelector((snapshot) => snapshot.state.autosave.lastSavedAt);- const sync = useProjectSync();+ const projectSync = useProjectSyncSelector((snapshot) => snapshot.projects[project.id]);const notify = useNotify();- const projectSync = sync.projects[project.id];const syncLabel =backendConnectionStatus !== 'connected'diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsxindex 148bb0ec2f..a3fe9ba6ee 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx@@ -8,9 +8,12 @@ import { StatusWidgetChip } from '@workbench/widget-frame';import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { ListOrderedIcon } from 'lucide-react';+import { areQueueRowsEqual, createQueueRowsSelector, getPendingQueueCount } from './queueViewModel';++const selectQueueRows = createQueueRowsSelector();+export const QueueWidgetView = ({ presentation, region }: WidgetViewProps) => {- const queueItems = useActiveProjectSelector((project) => project.queue.items);- const pendingQueueCount = queueItems.filter((item) => item.status === 'pending' || item.status === 'running').length;+ const pendingQueueCount = useActiveProjectSelector((project) => getPendingQueueCount(project.queue.items));if (region === 'bottom' && presentation !== 'expanded') {return <StatusWidgetChip icon={ListOrderedIcon}>{pendingQueueCount} queued</StatusWidgetChip>;@@ -52,11 +55,8 @@ const QueueItemLiveProgress = ({ queueItemId }: { queueItemId: string }) => {};const QueueContents = () => {- const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);+ const queueRows = useWorkbenchSelector((snapshot) => selectQueueRows(snapshot.state.projects), areQueueRowsEqual);const dispatch = useWorkbenchDispatch();- const queueRows = projects.flatMap((project) =>- project.queue.items.map((item) => ({ item, projectId: project.id, projectName: project.name }))- );return (<Stack gap="2" p="2">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.tsnew file mode 100644index 0000000000..da6805152b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/queueViewModel.ts@@ -0,0 +1,94 @@+import type { Project, QueueItem } from '@workbench/types';++import { createStableSelector } from '@workbench/workbenchSelectors';++export interface QueueRow {+ item: QueueItem;+ projectId: string;+ projectName: string;+}++export interface QueueActionState {+ cancellableCount: number;+ currentItemId: string | null;+ hasPendingQueueWork: boolean;+ hasRunningItem: boolean;+}++export const areQueueRowsEqual = (left: readonly QueueRow[], right: readonly QueueRow[]): boolean =>+ left.length === right.length &&+ left.every((row, index) => {+ const other = right[index];++ return (+ other !== undefined &&+ row.item === other.item &&+ row.projectId === other.projectId &&+ row.projectName === other.projectName+ );+ });++export const createQueueRowsSelector = () =>+ createStableSelector(+ (projects: readonly Project[]): QueueRow[] =>+ projects.flatMap((project) =>+ project.queue.items.map((item) => ({ item, projectId: project.id, projectName: project.name }))+ ),+ areQueueRowsEqual+ );++export const getPendingQueueCount = (items: readonly QueueItem[]): number =>+ items.reduce((count, item) => (item.status === 'pending' || item.status === 'running' ? count + 1 : count), 0);++export const hasPendingWorkflowQueueItem = (items: readonly QueueItem[]): boolean =>+ items.some(+ (item) => item.snapshot.sourceId === 'project-graph' && (item.status === 'running' || item.status === 'pending')+ );++const isCancellableQueueItem = (item: QueueItem): boolean =>+ item.cancellable && (item.status === 'pending' || item.status === 'running');++const compareQueueSubmittedAt = (left: QueueItem, right: QueueItem): number => {+ const leftTime = Date.parse(left.snapshot.submittedAt);+ const rightTime = Date.parse(right.snapshot.submittedAt);++ return (Number.isFinite(leftTime) ? leftTime : 0) - (Number.isFinite(rightTime) ? rightTime : 0);+};++const getCurrentQueueActionItem = (queueItems: readonly QueueItem[]): QueueItem | null => {+ const runningItem = queueItems.filter(isCancellableQueueItem).find((item) => item.status === 'running');++ if (runningItem) {+ return runningItem;+ }++ return queueItems.filter(isCancellableQueueItem).sort(compareQueueSubmittedAt)[0] ?? null;+};++const getOpenBackendSlotCount = (item: QueueItem): number => {+ if (!item.backendItemIds?.length) {+ return item.status === 'pending' || item.status === 'running' ? 1 : 0;+ }++ const terminalBackendItemIds = new Set([+ ...(item.completedBackendItemIds ?? []),+ ...(item.cancelledBackendItemIds ?? []),+ ]);++ return item.backendItemIds.filter((backendItemId) => !terminalBackendItemIds.has(backendItemId)).length;+};++export const getQueueActionState = (queueItems: readonly QueueItem[]): QueueActionState => {+ const currentItem = getCurrentQueueActionItem(queueItems);++ return {+ cancellableCount: queueItems.filter(isCancellableQueueItem).length,+ currentItemId: currentItem?.id ?? null,+ hasPendingQueueWork: queueItems.some((item) =>+ item.id === currentItem?.id+ ? item.status === 'running' && getOpenBackendSlotCount(item) > 1+ : item.status === 'pending'+ ),+ hasRunningItem: queueItems.some((item) => isCancellableQueueItem(item) && item.status === 'running'),+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsxindex 6c3d41806a..7dbc854fcd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx@@ -4,7 +4,7 @@ import type { InvocationTemplate, XYPosition } from '@workbench/workflows/types'import { HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { IconButton, ConfirmDialog, Tooltip } from '@workbench/components/ui';import { useNotify } from '@workbench/useNotify';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchStore } from '@workbench/WorkbenchContext';import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from '@workbench/workflows/connectors';import {buildConnectorNode,@@ -82,7 +82,7 @@ export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {/** Entries contributed to the shared widget actions menu. */export const WorkflowMenuItems = (_props: WidgetViewProps) => {- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);+ const store = useWorkbenchStore();const dispatch = useWorkbenchDispatch();const notify = useNotify();@@ -105,13 +105,13 @@ export const WorkflowMenuItems = (_props: WidgetViewProps) => {<Menu.Item value="import" onClick={requestWorkflowImport}>Import workflow JSON…</Menu.Item>- <Menu.Item value="export" onClick={() => downloadWorkflowJson(projectGraph)}>+ <Menu.Item value="export" onClick={() => downloadWorkflowJson(store.getSnapshot().activeProject.projectGraph)}>Export workflow JSON</Menu.Item><Menu.Itemvalue="copy"onClick={() => {- copyWorkflowJson(projectGraph)+ copyWorkflowJson(store.getSnapshot().activeProject.projectGraph).then(() => notify.success('Workflow JSON copied')).catch(() => notify.error('Failed to copy workflow JSON'));}}@@ -207,14 +207,12 @@ export const WorkflowDialogHost = () => {const dispatch = useWorkbenchDispatch();const notify = useNotify();const fileInputRef = useRef<HTMLInputElement | null>(null);- const {- addNodeConnection,- addNodePosition,- importRequestCount,- isAddNodeOpen,- isLibraryOpen,- isNewWorkflowConfirmOpen,- } = workflowUiStore.useSnapshot();+ const addNodeConnection = workflowUiStore.useSelector((snapshot) => snapshot.addNodeConnection);+ const addNodePosition = workflowUiStore.useSelector((snapshot) => snapshot.addNodePosition);+ const importRequestCount = workflowUiStore.useSelector((snapshot) => snapshot.importRequestCount);+ const isAddNodeOpen = workflowUiStore.useSelector((snapshot) => snapshot.isAddNodeOpen);+ const isLibraryOpen = workflowUiStore.useSelector((snapshot) => snapshot.isLibraryOpen);+ const isNewWorkflowConfirmOpen = workflowUiStore.useSelector((snapshot) => snapshot.isNewWorkflowConfirmOpen);const lastImportRequestRef = useRef(importRequestCount);useEffect(() => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsxindex f49dc5032b..fb79567d83 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx@@ -1,6 +1,7 @@import type { WidgetViewProps } from '@workbench/types';import { Box, HStack, Icon, Text } from '@chakra-ui/react';+import { hasPendingWorkflowQueueItem } from '@workbench/widgets/queue/queueViewModel';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { WorkflowIcon } from 'lucide-react';@@ -16,11 +17,8 @@ import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';*/const WorkflowStatusBarItem = () => {- const queueItems = useActiveProjectSelector((project) => project.queue.items);const workflowName = useActiveProjectSelector((project) => project.projectGraph.name);- const isRunning = queueItems.some(- (item) => item.snapshot.sourceId === 'project-graph' && (item.status === 'running' || item.status === 'pending')- );+ const isRunning = useActiveProjectSelector((project) => hasPendingWorkflowQueueItem(project.queue.items));return (<HStack gap="1" maxW="14rem" minW="0" px="2">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsxindex be930faf08..829bf06992 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx@@ -5,7 +5,7 @@ import { Badge, Box, Dialog, HStack, Icon, Input, Portal, ScrollArea, Stack, Teximport { useVirtualizer } from '@tanstack/react-virtual';import { IconButton, Tooltip } from '@workbench/components/ui';import { registerHotkeyModalLayer } from '@workbench/hotkeys';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';import { ChevronDownIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, HammerIcon } from 'lucide-react';import {@@ -266,7 +266,9 @@ const AddNodeDialogContent = ({onAddNote: () => void;onOpenChange: (isOpen: boolean) => void;}) => {- const { error, status, templates } = useInvocationTemplatesSnapshot();+ const error = useInvocationTemplatesSelector((snapshot) => snapshot.error);+ const status = useInvocationTemplatesSelector((snapshot) => snapshot.status);+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const [searchTerm, setSearchTerm] = useState('');const [expandedCategories, setExpandedCategories] = useState<Set<string>>(() => new Set());const [activeIndex, setActiveIndex] = useState<number | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsxindex 8e2c735457..ae11ed7ab8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/InvocationFlowNode.tsx@@ -24,7 +24,7 @@ import {isWorkflowFieldValueDefault,isModelFieldType,} from '@workbench/workflows/fields';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';import {ChevronDownIcon,@@ -145,7 +145,7 @@ const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | nullconst NodeTitle = ({ node }: { node: WorkflowInvocationNode }) => {const dispatch = useWorkbenchDispatch();- const { templates } = useInvocationTemplatesSnapshot();+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const [draftLabel, setDraftLabel] = useState<string | null>(null);const title = node.data.label || templates[node.data.type]?.title || node.data.type;@@ -576,7 +576,7 @@ const HiddenHandles = ({const InvocationFlowNodeComponent = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {const dispatch = useWorkbenchDispatch();- const { templates } = useInvocationTemplatesSnapshot();+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const isZoomedOut = useIsZoomedOut();const node = data.documentNode;const template = templates[node.data.type];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxindex d2c8d9515e..a2cab31978 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx@@ -4,13 +4,13 @@ import type { XYPosition } from '@workbench/workflows/types';import { Box, Flex, Stack, Text } from '@chakra-ui/react';import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@workbench/graph-preview';import '@xyflow/react/dist/style.css';-import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { useNotify } from '@workbench/useNotify';import { setAddNodeOpen } from '@workbench/widgets/workflow/workflowUiStore';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { getProjectGraphReadiness } from '@workbench/workflows/buildGraph';import { buildConnectorNode, createWorkflowId } from '@workbench/workflows/document';-import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@workbench/workflows/templates';import {getWorkflowSourceFieldType,getWorkflowTargetFieldType,@@ -124,9 +124,20 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {workflowShowMinimap,workflowSnapToGrid,workflowValidateConnections,- } = useWorkbenchPreferences();- const templatesSnapshot = useInvocationTemplatesSnapshot();- const invocationTemplates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : undefined;+ } = useWorkbenchPreferenceSelector(+ (preferences) => ({+ reduceMotion: preferences.reduceMotion,+ themeId: preferences.themeId,+ workflowEdgeStyle: preferences.workflowEdgeStyle,+ workflowShowMinimap: preferences.workflowShowMinimap,+ workflowSnapToGrid: preferences.workflowSnapToGrid,+ workflowValidateConnections: preferences.workflowValidateConnections,+ }),+ shallowEqual+ );+ const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);+ const invocationTemplates = templatesStatus === 'loaded' ? templates : undefined;const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() =>toFlowNodes(projectGraph, [], invocationTemplates)@@ -138,7 +149,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const [tool, setTool] = useState<EditorTool>('pan');const [nodeOpacity, setNodeOpacity] = useState(1);const [contextMenu, setContextMenu] = useState<WorkflowContextMenuState | null>(null);- const { selectedNodeIds, selectionRequest } = workflowSelectionStore.useSnapshot();+ const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);+ const selectionRequest = workflowSelectionStore.useSelector((snapshot) => snapshot.selectionRequest);const isSnapHeld = useModifierHeld('Control');const hasClipboardNodes = useHasClipboardNodes();const backgroundId = useId().replace(/:/g, '');@@ -432,11 +444,11 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {targetNodeId: connection.target,},projectGraph,- templatesSnapshot.templates+ templates) === null);},- [projectGraph, templatesSnapshot.templates, workflowValidateConnections]+ [projectGraph, templates, workflowValidateConnections]);const onConnect = useCallback(@@ -488,7 +500,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}if (handle.type === 'source') {- const sourceType = getWorkflowSourceFieldType(projectGraph, templatesSnapshot.templates, nodeId, handleId);+ const sourceType = getWorkflowSourceFieldType(projectGraph, templates, nodeId, handleId);if (sourceType === undefined) {return;@@ -504,7 +516,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}if (handle.type === 'target') {- const targetType = getWorkflowTargetFieldType(projectGraph, templatesSnapshot.templates, nodeId, handleId);+ const targetType = getWorkflowTargetFieldType(projectGraph, templates, nodeId, handleId);if (targetType === undefined) {return;@@ -518,7 +530,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {});}},- [flowInstance, projectGraph, templatesSnapshot.templates]+ [flowInstance, projectGraph, templates]);const onNodeContextMenu = useCallback((event: ReactMouseEvent, node: WorkflowFlowNode) => {@@ -750,7 +762,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const ReadinessBanner = () => {const projectGraph = useActiveProjectSelector((project) => project.projectGraph);- const templatesSnapshot = useInvocationTemplatesSnapshot();+ const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);+ const templatesSnapshot = useMemo(+ () => ({ error: null, status: templatesStatus, templates }),+ [templatesStatus, templates]+ );const readiness = useMemo(() => getProjectGraphReadiness(projectGraph, templatesSnapshot),[projectGraph, templatesSnapshot]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.tsindex 03d928b49f..fb85dc4f72 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/clipboard.ts@@ -38,7 +38,7 @@ export const copyNodesToClipboard = (document: ProjectGraphState, nodeIds: strinexport const hasClipboardNodes = (): boolean => clipboardStore.getSnapshot().nodes.length > 0;-export const useHasClipboardNodes = (): boolean => clipboardStore.useSnapshot().nodes.length > 0;+export const useHasClipboardNodes = (): boolean => clipboardStore.useSelector((snapshot) => snapshot.nodes.length > 0);const materializeElements = (payload: WorkflowClipboardSnapshot,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsxindex 313693f95a..9ec1e40536 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx@@ -1,5 +1,6 @@import type {ContainerFormElement,+ InvocationTemplates,NodeFieldFormElement,ProjectGraphState,WorkflowFormElement,@@ -14,7 +15,7 @@ import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { getResolvedWorkflowEdges } from '@workbench/workflows/connectors';import { getFormChildren } from '@workbench/workflows/document';import { getWorkflowFieldInvalidReason } from '@workbench/workflows/fields';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector, type InvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { isInvocationNode } from '@workbench/workflows/types';import {Columns2Icon,@@ -490,11 +491,12 @@ const AddElementMenu = () => {const getInvalidNodeFieldElementIds = (projectGraph: ProjectGraphState,- templatesSnapshot: ReturnType<typeof useInvocationTemplatesSnapshot>+ templatesStatus: InvocationTemplatesSnapshot['status'],+ templates: InvocationTemplates): Set<string> => {const invalidElementIds = new Set<string>();- if (templatesSnapshot.status !== 'loaded') {+ if (templatesStatus !== 'loaded') {return invalidElementIds;}@@ -517,7 +519,7 @@ const getInvalidNodeFieldElementIds = (continue;}- const template = templatesSnapshot.templates[node.data.type]?.inputs[fieldName];+ const template = templates[node.data.type]?.inputs[fieldName];if (!template) {invalidElementIds.add(element.id);@@ -535,8 +537,10 @@ const getInvalidNodeFieldElementIds = (};export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {- const templatesSnapshot = useInvocationTemplatesSnapshot();- const { hoveredNodeId, selectedNodeIds } = workflowSelectionStore.useSnapshot();+ const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);+ const hoveredNodeId = workflowSelectionStore.useSelector((snapshot) => snapshot.hoveredNodeId);+ const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);const [draggingElementId, setDraggingElementId] = useState<string | null>(null);const dndContextValue = useMemo<BuilderDndContextValue>(() => ({ draggingElementId, setDraggingElementId }),@@ -544,8 +548,8 @@ export const FormBuilderTab = ({ projectGraph }: { projectGraph: ProjectGraphSta);const selectedNodeIdSet = useMemo(() => new Set(selectedNodeIds), [selectedNodeIds]);const invalidElementIds = useMemo(- () => getInvalidNodeFieldElementIds(projectGraph, templatesSnapshot),- [projectGraph, templatesSnapshot]+ () => getInvalidNodeFieldElementIds(projectGraph, templatesStatus, templates),+ [projectGraph, templatesStatus, templates]);const rootChildren = getFormChildren(projectGraph.form);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsxindex 99121fc0d6..8e734f5e6b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx@@ -11,7 +11,7 @@ import {isDirectInputField,isWorkflowFieldValueDefault,} from '@workbench/workflows/fields';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { isInvocationNode } from '@workbench/workflows/types';import { RotateCcwIcon } from 'lucide-react';import { useState, type ChangeEvent } from 'react';@@ -23,7 +23,7 @@ import { useState, type ChangeEvent } from 'react';*//** Resolves a form element's node, field instance, and input template against the document. */export const useNodeFieldBinding = (element: NodeFieldFormElement, projectGraph: ProjectGraphState) => {- const { templates } = useInvocationTemplatesSnapshot();+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const { fieldName, nodeId } = element.data.fieldIdentifier;const node = projectGraph.nodes.find((candidate) => candidate.id === nodeId);const invocationNode = node && isInvocationNode(node) ? node : null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsxindex b2c0803dcb..1be2ccb992 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx@@ -11,7 +11,7 @@ import { JsonPreview, Scrollable, Tabs } from '@workbench/components/ui';import { workflowSelectionStore } from '@workbench/widgets/workflow/editor/selectionStore';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';-import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';/*** Edit-mode inspector for the editor's selected node, with the legacy tab@@ -94,7 +94,7 @@ const OutputsTab = ({ template }: { template: InvocationTemplate | undefined }));const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab }) => {- const { templates } = useInvocationTemplatesSnapshot();+ const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);if (node.type === 'notes' || node.type === 'current_image' || node.type === 'connector') {const typeLabel =@@ -130,7 +130,7 @@ const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab })export const NodeInspector = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {const workflowWidgetValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'workflow'));const dispatch = useWorkbenchDispatch();- const { selectedNodeIds } = workflowSelectionStore.useSnapshot();+ const selectedNodeIds = workflowSelectionStore.useSelector((snapshot) => snapshot.selectedNodeIds);const tab = getInspectorTab(workflowWidgetValues);const selectedNode = projectGraph.nodes.find((node) => node.id === selectedNodeIds[0]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsxindex 8c503c480c..8c276808e3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx@@ -1,7 +1,6 @@import { Flex, HStack, Icon, SegmentGroup, Splitter } from '@chakra-ui/react';import { Scrollable, Tabs } from '@workbench/components/ui';-import { getProjectWidgetValues } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWidgetValuesSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { ensureInvocationTemplatesLoaded } from '@workbench/workflows/templates';import { EyeIcon, PencilIcon } from 'lucide-react';import { useEffect } from 'react';@@ -29,6 +28,12 @@ const SPLITTER_PANELS = [{ id: 'inspector', minSize: 12 },];+export interface WorkflowPanelState {+ editTab: EditTab;+ inspectorSizePct: number;+ mode: PanelMode;+}+const getPanelMode = (values: Record<string, unknown>): PanelMode => (values.panelMode === 'edit' ? 'edit' : 'view');const getEditTab = (values: Record<string, unknown>): EditTab =>@@ -39,6 +44,15 @@ const getInspectorSizePct = (values: Record<string, unknown>): number =>? Math.min(75, Math.max(12, values.inspectorSizePct)): DEFAULT_INSPECTOR_SIZE_PCT;+export const getWorkflowPanelState = (values: Record<string, unknown>): WorkflowPanelState => ({+ editTab: getEditTab(values),+ inspectorSizePct: getInspectorSizePct(values),+ mode: getPanelMode(values),+});++export const areWorkflowPanelStatesEqual = (left: WorkflowPanelState, right: WorkflowPanelState): boolean =>+ left.mode === right.mode && left.editTab === right.editTab && left.inspectorSizePct === right.inspectorSizePct;+const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode: PanelMode) => void }) => {type PanelModeItem = {label: string;@@ -80,11 +94,12 @@ const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode:};export const WorkflowLinearPanel = () => {- const projectGraph = useActiveProjectSelector((project) => project.projectGraph);- const widgetValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'workflow'));+ const { editTab, inspectorSizePct, mode } = useWidgetValuesSelector(+ 'workflow',+ getWorkflowPanelState,+ areWorkflowPanelStatesEqual+ );const dispatch = useWorkbenchDispatch();- const mode = getPanelMode(widgetValues);- const editTab = getEditTab(widgetValues);useEffect(() => {ensureInvocationTemplatesLoaded();@@ -120,44 +135,68 @@ export const WorkflowLinearPanel = () => {) : null}</HStack>{mode === 'view' ? (- <Scrollable flex="1" label="Workflow panel content" minH="0">- <LinearFormView projectGraph={projectGraph} />- </Scrollable>+ <WorkflowLinearViewContent />) : (- <Splitter.Root- defaultSize={[100 - getInspectorSizePct(widgetValues), getInspectorSizePct(widgetValues)]}- flex="1"- gap="0"- minH="0"- orientation="vertical"- panels={SPLITTER_PANELS}- onResizeEnd={(details) => {- const inspectorSizePct = details.size[1];-- if (typeof inspectorSizePct === 'number') {- patchValues({ inspectorSizePct });- }- }}- >- <Splitter.Panel id="content" minH="0" minW="0" overflow="hidden">- {editTab === 'json' ? (- <WorkflowJsonTab projectGraph={projectGraph} />- ) : (- <Scrollable flex="1" h="full" label="Workflow panel content" minH="0" minW="0" w="full">- {editTab === 'form' ? (- <FormBuilderTab projectGraph={projectGraph} />- ) : (- <WorkflowDetailsTab metadata={projectGraph} />- )}- </Scrollable>- )}- </Splitter.Panel>- <Splitter.ResizeTrigger aria-label="Resize node inspector" id="content:inspector" />- <Splitter.Panel id="inspector" minH="0" overflow="hidden">- <NodeInspector projectGraph={projectGraph} />- </Splitter.Panel>- </Splitter.Root>+ <WorkflowLinearEditContent editTab={editTab} inspectorSizePct={inspectorSizePct} patchValues={patchValues} />)}</Flex>);};++const WorkflowLinearViewContent = () => {+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);++ return (+ <Scrollable flex="1" label="Workflow panel content" minH="0">+ <LinearFormView projectGraph={projectGraph} />+ </Scrollable>+ );+};++const WorkflowLinearEditContent = ({+ editTab,+ inspectorSizePct,+ patchValues,+}: {+ editTab: EditTab;+ inspectorSizePct: number;+ patchValues: (values: Record<string, unknown>) => void;+}) => {+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);++ return (+ <Splitter.Root+ defaultSize={[100 - inspectorSizePct, inspectorSizePct]}+ flex="1"+ gap="0"+ minH="0"+ orientation="vertical"+ panels={SPLITTER_PANELS}+ onResizeEnd={(details) => {+ const inspectorSizePct = details.size[1];++ if (typeof inspectorSizePct === 'number') {+ patchValues({ inspectorSizePct });+ }+ }}+ >+ <Splitter.Panel id="content" minH="0" minW="0" overflow="hidden">+ {editTab === 'json' ? (+ <WorkflowJsonTab projectGraph={projectGraph} />+ ) : (+ <Scrollable flex="1" h="full" label="Workflow panel content" minH="0" minW="0" w="full">+ {editTab === 'form' ? (+ <FormBuilderTab projectGraph={projectGraph} />+ ) : (+ <WorkflowDetailsTab metadata={projectGraph} />+ )}+ </Scrollable>+ )}+ </Splitter.Panel>+ <Splitter.ResizeTrigger aria-label="Resize node inspector" id="content:inspector" />+ <Splitter.Panel id="inspector" minH="0" overflow="hidden">+ <NodeInspector projectGraph={projectGraph} />+ </Splitter.Panel>+ </Splitter.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.tsindex 9f891ab535..f6b4f65fe8 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.test.ts@@ -1,65 +1,89 @@import { describe, expect, it } from 'vitest';-import { getAutosaveScheduleDecision } from './workbenchAutosave';+import { getAutosaveScheduleDecision, isAutosaveCompletionCurrent } from './workbenchAutosave';describe('getAutosaveScheduleDecision', () => {it('does not schedule already-saved or already-scheduled state', () => {expect(getAutosaveScheduleDecision({- failedStateKey: null,- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-a',- scheduledStateKey: null,+ failedPersistedRevision: null,+ lastSavedPersistedRevision: 1,+ persistedRevision: 1,+ scheduledPersistedRevision: null,})- ).toEqual({ failedStateKey: null, shouldSchedule: false });+ ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });expect(getAutosaveScheduleDecision({- failedStateKey: null,- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-b',- scheduledStateKey: 'project-b',+ failedPersistedRevision: null,+ lastSavedPersistedRevision: 1,+ persistedRevision: 2,+ scheduledPersistedRevision: 2,})- ).toEqual({ failedStateKey: null, shouldSchedule: false });+ ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });});it('holds a failed state key until a new durable edit happens', () => {expect(getAutosaveScheduleDecision({- failedStateKey: 'project-b',- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-b',- scheduledStateKey: null,+ failedPersistedRevision: 2,+ lastSavedPersistedRevision: 1,+ persistedRevision: 2,+ scheduledPersistedRevision: null,})- ).toEqual({ failedStateKey: 'project-b', shouldSchedule: false });+ ).toEqual({ failedPersistedRevision: 2, shouldSchedule: false });expect(getAutosaveScheduleDecision({- failedStateKey: 'project-b',- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-c',- scheduledStateKey: null,+ failedPersistedRevision: 2,+ lastSavedPersistedRevision: 1,+ persistedRevision: 3,+ scheduledPersistedRevision: null,})- ).toEqual({ failedStateKey: null, shouldSchedule: true });+ ).toEqual({ failedPersistedRevision: null, shouldSchedule: true });});it('clears a failed state key after returning to the last saved state', () => {expect(getAutosaveScheduleDecision({- failedStateKey: 'project-b',- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-a',- scheduledStateKey: null,+ failedPersistedRevision: 2,+ lastSavedPersistedRevision: 1,+ persistedRevision: 1,+ scheduledPersistedRevision: null,})- ).toEqual({ failedStateKey: null, shouldSchedule: false });+ ).toEqual({ failedPersistedRevision: null, shouldSchedule: false });expect(getAutosaveScheduleDecision({- failedStateKey: null,- lastSavedStateKey: 'project-a',- persistedStateKey: 'project-b',- scheduledStateKey: null,+ failedPersistedRevision: null,+ lastSavedPersistedRevision: 1,+ persistedRevision: 2,+ scheduledPersistedRevision: null,})- ).toEqual({ failedStateKey: null, shouldSchedule: true });+ ).toEqual({ failedPersistedRevision: null, shouldSchedule: true });+ });+});++describe('isAutosaveCompletionCurrent', () => {+ it('rejects stale save completions after a newer durable revision exists', () => {+ expect(+ isAutosaveCompletionCurrent({+ completedPersistedRevision: 2,+ completedStateKey: 'state-2',+ currentPersistedRevision: 3,+ currentStateKey: 'state-3',+ })+ ).toBe(false);+ });++ it('accepts save completions for the current durable revision and state key', () => {+ expect(+ isAutosaveCompletionCurrent({+ completedPersistedRevision: 2,+ completedStateKey: 'state-2',+ currentPersistedRevision: 2,+ currentStateKey: 'state-2',+ })+ ).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.tsindex 4009239ff0..907e053dea 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchAutosave.ts@@ -1,32 +1,55 @@+import type { WorkbenchState } from './types';++export const getPersistedStateKey = (state: WorkbenchState): string =>+ JSON.stringify({+ account: state.account,+ activeProjectId: state.activeProjectId,+ errorLog: state.errorLog,+ projects: state.projects,+ widgetFailures: state.widgetFailures,+ });+interface AutosaveScheduleDecisionInput {- failedStateKey: string | null;- lastSavedStateKey: string;- persistedStateKey: string;- scheduledStateKey: string | null;+ failedPersistedRevision: number | null;+ lastSavedPersistedRevision: number;+ persistedRevision: number;+ scheduledPersistedRevision: number | null;}interface AutosaveScheduleDecision {- failedStateKey: string | null;+ failedPersistedRevision: number | null;shouldSchedule: boolean;}export const getAutosaveScheduleDecision = ({- failedStateKey,- lastSavedStateKey,- persistedStateKey,- scheduledStateKey,+ failedPersistedRevision,+ lastSavedPersistedRevision,+ persistedRevision,+ scheduledPersistedRevision,}: AutosaveScheduleDecisionInput): AutosaveScheduleDecision => {- if (persistedStateKey === lastSavedStateKey) {- return { failedStateKey: null, shouldSchedule: false };+ if (persistedRevision === lastSavedPersistedRevision) {+ return { failedPersistedRevision: null, shouldSchedule: false };}- if (persistedStateKey === scheduledStateKey) {- return { failedStateKey, shouldSchedule: false };+ if (persistedRevision === scheduledPersistedRevision) {+ return { failedPersistedRevision, shouldSchedule: false };}- if (persistedStateKey === failedStateKey) {- return { failedStateKey, shouldSchedule: false };+ if (persistedRevision === failedPersistedRevision) {+ return { failedPersistedRevision, shouldSchedule: false };}- return { failedStateKey: null, shouldSchedule: true };+ return { failedPersistedRevision: null, shouldSchedule: true };};++export const isAutosaveCompletionCurrent = ({+ completedPersistedRevision,+ completedStateKey,+ currentPersistedRevision,+ currentStateKey,+}: {+ completedPersistedRevision: number;+ completedStateKey: string;+ currentPersistedRevision: number;+ currentStateKey: string;+}): boolean => completedPersistedRevision === currentPersistedRevision && completedStateKey === currentStateKey;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.tsnew file mode 100644index 0000000000..f4e5692ec6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workbenchSelectors.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { createSelectorCache, createStableSelector } from './workbenchSelectors';++describe('createSelectorCache', () => {+ it('uses shallow equality by default for derived objects', () => {+ const cache = createSelectorCache((snapshot: { count: number; label: string }) => ({ count: snapshot.count }));++ const first = cache.read({ count: 1, label: 'idle' });+ const second = cache.read({ count: 1, label: 'loading' });+ const third = cache.read({ count: 2, label: 'loading' });++ expect(second).toBe(first);+ expect(third).not.toBe(first);+ expect(third).toEqual({ count: 2 });+ });++ it('compares Set contents by default', () => {+ const cache = createSelectorCache((snapshot: { ids: string[] }) => new Set(snapshot.ids));++ const first = cache.read({ ids: ['a', 'b'] });+ const second = cache.read({ ids: ['a', 'b'] });+ const third = cache.read({ ids: ['a', 'c'] });++ expect(second).toBe(first);+ expect(third).not.toBe(first);+ });+});++describe('createStableSelector', () => {+ it('reuses the previous result when derived values are equal', () => {+ const selector = createStableSelector(+ (value: { ids: string[] }) => value.ids.map((id) => id.toUpperCase()),+ (left, right) => left.length === right.length && left.every((id, index) => id === right[index])+ );++ const first = selector({ ids: ['a', 'b'] });+ const second = selector({ ids: ['a', 'b'] });+ const third = selector({ ids: ['a', 'c'] });++ expect(second).toBe(first);+ expect(third).not.toBe(first);+ expect(third).toEqual(['A', 'C']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchSelectors.ts b/invokeai/frontend/webv2/src/workbench/workbenchSelectors.tsnew file mode 100644index 0000000000..35c7ae2fc4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workbenchSelectors.ts@@ -0,0 +1,105 @@+import { useRef, useSyncExternalStore } from 'react';++export type EqualityFn<T> = (left: T, right: T) => boolean;++export interface SelectorCache<Snapshot, Selected> {+ read: (snapshot: Snapshot) => Selected;+ setSelector: (selector: (snapshot: Snapshot) => Selected, isEqual: EqualityFn<Selected>) => void;+}++export const areArraysEqual = <Value>(left: readonly Value[], right: readonly Value[]): boolean =>+ left.length === right.length && left.every((value, index) => Object.is(value, right[index]));++export const shallowEqual = <T>(left: T, right: T): boolean => {+ if (Object.is(left, right)) {+ return true;+ }++ if (Array.isArray(left) && Array.isArray(right)) {+ return areArraysEqual(left, right);+ }++ if (left instanceof Set && right instanceof Set) {+ return left.size === right.size && Array.from(left).every((value) => right.has(value));+ }++ if (left instanceof Map && right instanceof Map) {+ return (+ left.size === right.size &&+ Array.from(left).every(([key, value]) => right.has(key) && Object.is(right.get(key), value))+ );+ }++ if (typeof left !== 'object' || left === null || typeof right !== 'object' || right === null) {+ return false;+ }++ const leftRecord = left as Record<PropertyKey, unknown>;+ const rightRecord = right as Record<PropertyKey, unknown>;+ const leftKeys = Reflect.ownKeys(leftRecord);++ if (leftKeys.length !== Reflect.ownKeys(rightRecord).length) {+ return false;+ }++ return leftKeys.every(+ (key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && Object.is(leftRecord[key], rightRecord[key])+ );+};++export const createSelectorCache = <Snapshot, Selected>(+ initialSelector: (snapshot: Snapshot) => Selected,+ initialIsEqual: EqualityFn<Selected> = shallowEqual+): SelectorCache<Snapshot, Selected> => {+ let hasSelection = false;+ let isEqual = initialIsEqual;+ let selection: Selected;+ let selector = initialSelector;++ return {+ read: (snapshot) => {+ const next = selector(snapshot);++ if (hasSelection && isEqual(selection, next)) {+ return selection;+ }++ hasSelection = true;+ selection = next;++ return next;+ },+ setSelector: (nextSelector, nextIsEqual) => {+ selector = nextSelector;+ isEqual = nextIsEqual;+ },+ };+};++export const useExternalStoreSelector = <Snapshot, Selected>(+ subscribe: (listener: () => void) => () => void,+ getSnapshot: () => Snapshot,+ selector: (snapshot: Snapshot) => Selected,+ isEqual: EqualityFn<Selected> = shallowEqual+): Selected => {+ const cacheRef = useRef<SelectorCache<Snapshot, Selected> | null>(null);++ if (cacheRef.current === null) {+ cacheRef.current = createSelectorCache(selector, isEqual);+ } else {+ cacheRef.current.setSelector(selector, isEqual);+ }++ const getSelectedSnapshot = (): Selected => cacheRef.current!.read(getSnapshot());++ return useSyncExternalStore(subscribe, getSelectedSnapshot, getSelectedSnapshot);+};++export const createStableSelector = <Input, Selected>(+ selector: (input: Input) => Selected,+ isEqual: EqualityFn<Selected> = shallowEqual+): ((input: Input) => Selected) => {+ const cache = createSelectorCache(selector, isEqual);++ return (input) => cache.read(input);+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 51b1d5ec83..0a1f357c40 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -198,6 +198,61 @@ describe('workbench widget region opening', () => {});});+describe('workbench widget state updates', () => {+ it('patches a missing undefined widget value key as a real state change', () => {+ const initial = createInitialWorkbenchState();+ const next = workbenchReducer(initial, {+ type: 'patchWidgetValues',+ values: { optionalValue: undefined },+ widgetId: 'diagnostics',+ });+ const values = getProjectWidgetValues(getActiveProject(next), 'diagnostics');++ expect(next).not.toBe(initial);+ expect(Object.prototype.hasOwnProperty.call(values, 'optionalValue')).toBe(true);+ });++ it('can patch a widget instance in a non-active project', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;++ expect(secondProjectId).not.toBe(firstProjectId);++ state = workbenchReducer(state, {+ instanceId: 'generate',+ projectId: firstProjectId,+ type: 'patchWidgetInstanceValues',+ values: { projectScoped: true },+ });++ expect(getProject(state, firstProjectId).widgetInstances.generate?.state.values.projectScoped).toBe(true);+ expect(getProject(state, secondProjectId).widgetInstances.generate?.state.values.projectScoped).toBeUndefined();+ });++ it('clones replacement widget instance values before storing them', () => {+ let state = createInitialWorkbenchState();+ const values: Record<string, unknown> = { mutable: 'before' };++ state = workbenchReducer(state, { instanceId: 'generate', type: 'setWidgetInstanceValues', values });+ values.mutable = 'after';++ expect(getActiveProject(state).widgetInstances.generate?.state.values.mutable).toBe('before');+ });++ it('clones patched widget instance values before storing them', () => {+ let state = createInitialWorkbenchState();+ const values: Record<string, unknown> = { nested: { mutable: 'before' } };++ state = workbenchReducer(state, { instanceId: 'generate', type: 'patchWidgetInstanceValues', values });+ (values.nested as { mutable: string }).mutable = 'after';++ expect(getActiveProject(state).widgetInstances.generate?.state.values.nested).toEqual({ mutable: 'before' });+ });+});+describe('workbench layout presets', () => {it('applies the Default preset as a full widget-region layout', () => {let state = createInitialWorkbenchState();@@ -910,6 +965,27 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: null, positivePrompt: 'a cat' }]);});+ it('patches Generate settings without replacing unchanged nested values', () => {+ const loraModel = { base: 'sdxl', key: 'lora-1', name: 'LoRA', type: 'lora' } as const;+ const state = primeGenerate(undefined, {+ loras: [{ isEnabled: true, model: loraModel, weight: 0.75 }],+ positivePrompt: 'before',+ });+ const beforeValues = getProjectWidgetValues(getActiveProject(state), 'generate') as unknown as GenerateWidgetValues;+ const nextState = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePrompt: 'after' },+ });+ const afterValues = getProjectWidgetValues(+ getActiveProject(nextState),+ 'generate'+ ) as unknown as GenerateWidgetValues;++ expect(afterValues.positivePrompt).toBe('after');+ expect(afterValues.model).toBe(beforeValues.model);+ expect(afterValues.loras).toBe(beforeValues.loras);+ });+it('deduplicates prompt history by prompt pair and moves the newest submission to the top', () => {let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });@@ -1202,6 +1278,54 @@ describe('workbench backend connection recovery', () => {expect(values.galleryImagesRefreshToken).not.toBe(previousValues.galleryImagesRefreshToken);});+ it('can refresh gallery images in a non-active project without touching the active project', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ const firstPreviousValues = getProjectWidgetValues(getProject(state, firstProjectId), 'gallery');+ const secondPreviousValues = getProjectWidgetValues(getProject(state, secondProjectId), 'gallery');++ state = workbenchReducer(state, { projectId: firstProjectId, type: 'touchGalleryImagesRefresh' });++ const firstValues = getProjectWidgetValues(getProject(state, firstProjectId), 'gallery');+ const secondValues = getProjectWidgetValues(getProject(state, secondProjectId), 'gallery');++ expect(firstValues.galleryImagesRefreshToken).not.toBe(firstPreviousValues.galleryImagesRefreshToken);+ expect(secondValues.galleryImagesRefreshToken).toBe(secondPreviousValues.galleryImagesRefreshToken);+ });++ it('can remove gallery images from a non-active project without touching the active project', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;+ const image = createImage('shared.png', 'backend-gallery');++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ projectId: firstProjectId,+ type: 'patchWidgetValues',+ values: { recentImages: [image], selectedImage: image, selectedImageName: image.imageName },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ projectId: secondProjectId,+ type: 'patchWidgetValues',+ values: { recentImages: [image], selectedImage: image, selectedImageName: image.imageName },+ widgetId: 'gallery',+ });++ state = workbenchReducer(state, {+ imageNames: [image.imageName],+ projectId: firstProjectId,+ type: 'removeGalleryImages',+ });++ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery').recentImages).toEqual([]);+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery').recentImages).toEqual([image]);+ });+it('does not hydrate stale persisted backend connection state', () => {const initial = createInitialWorkbenchState();const persisted = {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 6cfe933156..9423451106 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -97,9 +97,10 @@ type WorkbenchAction =widgetId: WidgetTypeId;createNew?: boolean;initialValues?: Record<string, unknown>;+ projectId?: string;}- | { type: 'selectRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId }- | { type: 'toggleRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId }+ | { type: 'selectRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId; projectId?: string }+ | { type: 'toggleRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId; projectId?: string }| {type: 'moveWidgetInstance';instanceId: WidgetInstanceId;@@ -115,14 +116,25 @@ type WorkbenchAction =}| { type: 'setRegionWidgetCollapsed'; region: WidgetRegion; isCollapsed: boolean }| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }- | { type: 'setGenerateSettings'; values: GenerateWidgetValues }- | { type: 'setGenerateBatchCount'; batchCount: number }- | { type: 'addPromptToHistory'; prompt: PromptHistoryItem }- | { type: 'removePromptFromHistory'; prompt: PromptHistoryItem }- | { type: 'clearPromptHistory' }- | { type: 'patchWidgetValues'; widgetId: WidgetTypeId; values: Record<string, unknown> }- | { type: 'patchWidgetInstanceValues'; instanceId: WidgetInstanceId; values: Record<string, unknown> }- | { type: 'setWidgetInstanceValues'; instanceId: WidgetInstanceId; values: Record<string, unknown> }+ | { type: 'setGenerateSettings'; values: GenerateWidgetValues; projectId?: string }+ | { type: 'patchGenerateSettings'; values: Partial<GenerateWidgetValues>; projectId?: string }+ | { type: 'setGenerateBatchCount'; batchCount: number; projectId?: string }+ | { type: 'addPromptToHistory'; prompt: PromptHistoryItem; projectId?: string }+ | { type: 'removePromptFromHistory'; prompt: PromptHistoryItem; projectId?: string }+ | { type: 'clearPromptHistory'; projectId?: string }+ | { type: 'patchWidgetValues'; widgetId: WidgetTypeId; values: Record<string, unknown>; projectId?: string }+ | {+ type: 'patchWidgetInstanceValues';+ instanceId: WidgetInstanceId;+ values: Record<string, unknown>;+ projectId?: string;+ }+ | {+ type: 'setWidgetInstanceValues';+ instanceId: WidgetInstanceId;+ values: Record<string, unknown>;+ projectId?: string;+ }| { type: 'applyProjectGraphAction'; action: ProjectGraphAction }| { type: 'replaceProjectGraph'; document: ProjectGraphState; label: string }| { type: 'saveProjectGraphSnapshot' }@@ -158,20 +170,20 @@ type WorkbenchAction =| { type: 'discardAllStagedImages' }| { type: 'toggleCanvasStagingVisibility' }| { type: 'toggleCanvasStagingThumbnailsVisibility' }- | { type: 'selectGalleryImage'; image: GeneratedImageContract }- | { type: 'toggleGalleryImageInSelection'; image: GeneratedImageContract }- | { type: 'setGalleryMultiSelection'; imageNames: string[]; primaryImage: GeneratedImageContract }- | { type: 'setGalleryCompareImage'; image: GeneratedImageContract | null }- | { type: 'selectGalleryBoard'; boardId: string }- | { type: 'setGalleryView'; galleryView: 'images' | 'assets' }- | { type: 'setGallerySearchTerm'; searchTerm: string }- | { type: 'updateGallerySettings'; settings: Partial<GallerySettings> }- | { type: 'setGalleryPage'; page: number }- | { type: 'setGalleryPageInfo'; totalImages: number }- | { type: 'touchGalleryRefresh' }- | { type: 'touchGalleryImagesRefresh' }- | { type: 'removeGalleryImages'; imageNames: string[] }- | { type: 'setGalleryProjectBoardId'; boardId: string }+ | { type: 'selectGalleryImage'; image: GeneratedImageContract; projectId?: string }+ | { type: 'toggleGalleryImageInSelection'; image: GeneratedImageContract; projectId?: string }+ | { type: 'setGalleryMultiSelection'; imageNames: string[]; primaryImage: GeneratedImageContract; projectId?: string }+ | { type: 'setGalleryCompareImage'; image: GeneratedImageContract | null; projectId?: string }+ | { type: 'selectGalleryBoard'; boardId: string; projectId?: string }+ | { type: 'setGalleryView'; galleryView: 'images' | 'assets'; projectId?: string }+ | { type: 'setGallerySearchTerm'; searchTerm: string; projectId?: string }+ | { type: 'updateGallerySettings'; settings: Partial<GallerySettings>; projectId?: string }+ | { type: 'setGalleryPage'; page: number; projectId?: string }+ | { type: 'setGalleryPageInfo'; totalImages: number; projectId?: string }+ | { type: 'touchGalleryRefresh'; projectId?: string }+ | { type: 'touchGalleryImagesRefresh'; projectId?: string }+ | { type: 'removeGalleryImages'; imageNames: string[]; projectId?: string }+ | { type: 'setGalleryProjectBoardId'; boardId: string; projectId?: string }| { type: 'acceptStagedImage' }| { type: 'clearCanvasStaging' }| { type: 'cancelQueueItem'; queueItemId: string; projectId?: string }@@ -235,6 +247,39 @@ const addNotification = (state: WorkbenchState, notification: WorkbenchNotificatnotifications: [notification, ...state.notifications].slice(0, NOTIFICATION_LIMIT),});+const areRecordsShallowEqual = (left: Record<string, unknown>, right: Record<string, unknown>): boolean => {+ if (left === right) {+ return true;+ }++ const leftKeys = Object.keys(left);+ const rightKeys = Object.keys(right);++ return (+ leftKeys.length === rightKeys.length &&+ leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && Object.is(left[key], right[key]))+ );+};++const patchRecord = <RecordValue extends Record<string, unknown>>(+ current: RecordValue,+ patch: Partial<RecordValue>+): RecordValue => {+ let didChange = false;++ for (const [key, value] of Object.entries(patch)) {+ if (!Object.prototype.hasOwnProperty.call(current, key) || !Object.is(current[key], value)) {+ didChange = true;+ break;+ }+ }++ return didChange ? ({ ...current, ...patch } as RecordValue) : current;+};++const cloneRecord = <RecordValue extends Record<string, unknown>>(record: RecordValue): RecordValue =>+ structuredClone(record) as RecordValue;+const cloneGraph = (graph: GraphContract): GraphContract => ({...graph,backendGraph: graph.backendGraph@@ -428,6 +473,11 @@ const updateProjectWidgetState = (Object.values(project.widgetInstances).find((candidate) => candidate.typeId === widgetId);const instanceId = instance?.id ?? widgetId;const currentInstance = instance ?? createWidgetInstance(widgetId, instanceId);+ const nextState = getState(currentInstance.state);++ if (nextState === currentInstance.state) {+ return project;+ }return {...project,@@ -435,7 +485,7 @@ const updateProjectWidgetState = (...project.widgetInstances,[instanceId]: {...currentInstance,- state: getState(currentInstance.state),+ state: nextState,},},};@@ -446,10 +496,40 @@ const updateProjectWidgetValues = (widgetId: WidgetTypeId,getValues: (values: Record<string, unknown>) => Record<string, unknown>): Project =>- updateProjectWidgetState(project, widgetId, (widgetState) => ({- ...widgetState,- values: getValues(widgetState.values),- }));+ updateProjectWidgetState(project, widgetId, (widgetState) => {+ const values = getValues(widgetState.values);++ return values === widgetState.values ? widgetState : { ...widgetState, values };+ });++const updateProjectWidgetInstanceValues = (+ project: Project,+ instanceId: WidgetInstanceId,+ getValues: (values: Record<string, unknown>) => Record<string, unknown>+): Project => {+ const instance = project.widgetInstances[instanceId];++ if (!instance) {+ return project;+ }++ const values = getValues(instance.state.values);++ if (values === instance.state.values) {+ return project;+ }++ return {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ [instanceId]: {+ ...instance,+ state: { ...instance.state, values },+ },+ },+ };+};const cloneWidgetRegions = (widgetRegions: Record<WidgetRegion, WidgetRegionState>@@ -754,12 +834,24 @@ const getNextProjectIndex = (projects: Project[]): number => {export const createDraftProject = (projects: Project[]): Project =>createProject(getNextProjectIndex(projects), createId('project'));-const updateActiveProject = (state: WorkbenchState, getProject: (project: Project) => Project): WorkbenchState => ({- ...state,- projects: state.projects.map((project) =>- project.id === state.activeProjectId ? getProject(ensureProjectWidgetContracts(project)) : project- ),-});+const updateActiveProject = (state: WorkbenchState, getProject: (project: Project) => Project): WorkbenchState => {+ let didChange = false;+ const projects = state.projects.map((project) => {+ if (project.id !== state.activeProjectId) {+ return project;+ }++ const nextProject = getProject(project);++ if (nextProject !== project) {+ didChange = true;+ }++ return nextProject;+ });++ return didChange ? { ...state, projects } : state;+};const getNextInstanceId = (region: WidgetRegionState, instanceId: WidgetInstanceId): WidgetInstanceId | null => {if (region.activeInstanceId !== instanceId) {@@ -782,14 +874,26 @@ const updateActiveWidgetRegion = (state: WorkbenchState,region: WidgetRegion,getRegion: (regionState: WidgetRegionState) => WidgetRegionState-): WorkbenchState =>- updateActiveProject(state, (project) => ({- ...project,- widgetRegions: {- ...project.widgetRegions,- [region]: getRegion(project.widgetRegions[region]),- },- }));+): WorkbenchState => updateActiveProject(state, (project) => updateProjectWidgetRegion(project, region, getRegion));++const updateProjectWidgetRegion = (+ project: Project,+ region: WidgetRegion,+ getRegion: (regionState: WidgetRegionState) => WidgetRegionState+): Project => {+ const regionState = project.widgetRegions[region];+ const nextRegionState = getRegion(regionState);++ return nextRegionState === regionState+ ? project+ : {+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ [region]: nextRegionState,+ },+ };+};const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): ProjectLayoutState => ({...layout,@@ -1043,21 +1147,34 @@ const updateProjectById = (state: WorkbenchState,projectId: string,getProject: (project: Project) => Project-): WorkbenchState => ({- ...state,- projects: state.projects.map((project) =>- project.id === projectId ? getProject(ensureProjectWidgetContracts(project)) : project- ),-});+): WorkbenchState => {+ let didChange = false;+ const projects = state.projects.map((project) => {+ if (project.id !== projectId) {+ return project;+ }++ const nextProject = getProject(project);++ if (nextProject !== project) {+ didChange = true;+ }++ return nextProject;+ });++ return didChange ? { ...state, projects } : state;+};const updateGalleryValues = (state: WorkbenchState,- getValues: (values: Record<string, unknown>) => Record<string, unknown>+ getValues: (values: Record<string, unknown>) => Record<string, unknown>,+ projectId = state.activeProjectId): WorkbenchState => {- const activeProject = state.projects.find((project) => project.id === state.activeProjectId);- const values = activeProject ? getWidgetValues(activeProject, 'gallery') : null;+ const targetProject = state.projects.find((project) => project.id === projectId);+ const values = targetProject ? getWidgetValues(targetProject, 'gallery') : null;- if (!activeProject || !values) {+ if (!targetProject || !values) {return state;}@@ -1067,7 +1184,9 @@ const updateGalleryValues = (return state;}- return updateActiveProject(state, (project) => updateProjectWidgetValues(project, 'gallery', () => nextValues));+ return updateProjectById(state, projectId, (project) =>+ updateProjectWidgetValues(project, 'gallery', () => nextValues)+ );};const refreshProjectBackendData = (project: Project): Project => ({@@ -1078,12 +1197,24 @@ const refreshProjectBackendData = (project: Project): Project => ({})),});-const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => ({- ...project,- queue: {- items: project.queue.items.map((item) => (item.id === queueItemId ? getItem(item) : item)),- },-});+const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => {+ let didChange = false;+ const items = project.queue.items.map((item) => {+ if (item.id !== queueItemId) {+ return item;+ }++ const nextItem = getItem(item);++ if (nextItem !== item) {+ didChange = true;+ }++ return nextItem;+ });++ return didChange ? { ...project, queue: { items } } : project;+};const isCancellableQueueItem = (item: QueueItem): boolean =>item.cancellable && (item.status === 'pending' || item.status === 'running');@@ -1452,7 +1583,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}));}case 'openRegionWidget': {- return updateActiveProject(state, (project) => {+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {const region = project.widgetRegions[action.region];const existingInstanceInRegion = region.instanceIds.map((instanceId) => project.widgetInstances[instanceId])@@ -1489,7 +1620,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)});}case 'selectRegionWidget': {- return updateActiveProject(state, (project) => {+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {const region = project.widgetRegions[action.region];if (action.region === 'center') {@@ -1515,25 +1646,27 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)});}case 'toggleRegionWidget': {- return updateActiveWidgetRegion(state, action.region, (region) => {- const isEnabled = region.instanceIds.includes(action.widgetId);+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetRegion(project, action.region, (region) => {+ const isEnabled = region.instanceIds.includes(action.widgetId);- if (action.region === 'center' && isEnabled && region.instanceIds.length === 1) {- return region;- }+ if (action.region === 'center' && isEnabled && region.instanceIds.length === 1) {+ return region;+ }- const instanceIds = isEnabled- ? region.instanceIds.filter((widgetId) => widgetId !== action.widgetId)- : [...region.instanceIds, action.widgetId];- const fallbackInstanceId = getNextInstanceId(region, action.widgetId);+ const instanceIds = isEnabled+ ? region.instanceIds.filter((widgetId) => widgetId !== action.widgetId)+ : [...region.instanceIds, action.widgetId];+ const fallbackInstanceId = getNextInstanceId(region, action.widgetId);- return {- ...region,- activeInstanceId: isEnabled && fallbackInstanceId ? fallbackInstanceId : action.widgetId,- instanceIds,- isCollapsed: action.region === 'center' ? false : instanceIds.length === 0 ? true : region.isCollapsed,- };- });+ return {+ ...region,+ activeInstanceId: isEnabled && fallbackInstanceId ? fallbackInstanceId : action.widgetId,+ instanceIds,+ isCollapsed: action.region === 'center' ? false : instanceIds.length === 0 ? true : region.isCollapsed,+ };+ })+ );}case 'moveWidgetInstance': {return updateActiveProject(state, (project) => {@@ -1579,89 +1712,75 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)return state;}- return updateActiveWidgetRegion(state, action.region, (region) => ({- ...region,- isCollapsed: action.isCollapsed,- }));+ return updateActiveWidgetRegion(state, action.region, (region) =>+ region.isCollapsed === action.isCollapsed ? region : { ...region, isCollapsed: action.isCollapsed }+ );}case 'setRegionWidgetSize': {- return updateActiveWidgetRegion(state, action.region, (region) => ({- ...region,- sizePx: clampPanelSize(action.region, action.sizePx),- }));+ const sizePx = clampPanelSize(action.region, action.sizePx);++ return updateActiveWidgetRegion(state, action.region, (region) =>+ region.sizePx === sizePx ? region : { ...region, sizePx }+ );}case 'setGenerateSettings': {- return updateActiveProject(state, (project) =>+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>updateProjectWidgetValues(project, 'generate', () => cloneGenerateWidgetValues(action.values)));}+ case 'patchGenerateSettings': {+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetValues(project, 'generate', (values) => patchRecord(values, action.values))+ );+ }case 'setGenerateBatchCount': {const batchCount = sanitizeBatchCount(action.batchCount);- return updateActiveProject(state, (project) =>- updateProjectWidgetValues(project, 'generate', (values) => ({ ...values, batchCount }))+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetValues(project, 'generate', (values) =>+ sanitizeBatchCount(values.batchCount) === batchCount ? values : { ...values, batchCount }+ ));}case 'addPromptToHistory': {- return updateActiveProject(state, (project) => ({+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => ({...project,promptHistory: addPromptHistoryItem(project.promptHistory, action.prompt),}));}case 'removePromptFromHistory': {- return updateActiveProject(state, (project) => ({+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => ({...project,promptHistory: removePromptHistoryItem(project.promptHistory, action.prompt),}));}case 'clearPromptHistory': {- return updateActiveProject(state, (project) => ({ ...project, promptHistory: [] }));+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => ({+ ...project,+ promptHistory: [],+ }));}case 'patchWidgetValues': {// Generic widget-owned UI state (panel modes, tabs, sizes). Not undoable.- return updateActiveProject(state, (project) =>- updateProjectWidgetValues(project, action.widgetId, (values) => ({ ...values, ...action.values }))+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetValues(project, action.widgetId, (values) => patchRecord(values, action.values)));}case 'patchWidgetInstanceValues': {- return updateActiveProject(state, (project) => {- const instance = project.widgetInstances[action.instanceId];-- if (!instance) {- return project;- }-- return {- ...project,- widgetInstances: {- ...project.widgetInstances,- [action.instanceId]: {- ...instance,- state: { ...instance.state, values: { ...instance.state.values, ...action.values } },- },- },- };- });+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetInstanceValues(project, action.instanceId, (values) =>+ patchRecord(values, cloneRecord(action.values))+ )+ );}case 'setWidgetInstanceValues': {- return updateActiveProject(state, (project) => {- const instance = project.widgetInstances[action.instanceId];-- if (!instance) {- return project;- }+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetInstanceValues(project, action.instanceId, (currentValues) => {+ const values = cloneRecord(action.values);- return {- ...project,- widgetInstances: {- ...project.widgetInstances,- [action.instanceId]: {- ...instance,- state: { ...instance.state, values: action.values },- },- },- };- });+ return areRecordsShallowEqual(currentValues, values) ? currentValues : values;+ })+ );}case 'applyProjectGraphAction': {return updateActiveProject(state, (project) => {@@ -1806,12 +1925,16 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}case 'markQueueItemBackendSubmitted': {return updateProjectById(state, action.projectId, (project) =>- updateQueueItem(project, action.queueItemId, (item) => ({- ...item,- backendBatchId: action.backendBatchId,- backendItemIds: action.backendItemIds,- status: item.status === 'cancelled' ? 'cancelled' : 'running',- }))+ updateQueueItem(project, action.queueItemId, (item) => {+ const status = item.status === 'cancelled' ? 'cancelled' : 'running';+ const hasSameBackendItemIds =+ item.backendItemIds?.length === action.backendItemIds.length &&+ item.backendItemIds.every((id, index) => id === action.backendItemIds[index]);++ return item.backendBatchId === action.backendBatchId && hasSameBackendItemIds && item.status === status+ ? item+ : { ...item, backendBatchId: action.backendBatchId, backendItemIds: action.backendItemIds, status };+ }));}case 'setQueueItemStatus': {@@ -1822,6 +1945,10 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)return state;}+ if (queueItem?.status === action.status && queueItem.error === action.error) {+ return state;+ }+const nextState = updateProjectById(state, action.projectId, (project) =>updateQueueItem(project, action.queueItemId, (item) => ({...item,@@ -1968,73 +2095,97 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)}));}case 'selectGalleryImage': {- return updateGalleryValues(state, (values) => ({- ...values,- selectedImage: action.image,- selectedImageName: action.image.imageName,- selectedImageNames: [action.image.imageName],- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ selectedImage: action.image,+ selectedImageName: action.image.imageName,+ selectedImageNames: [action.image.imageName],+ }),+ action.projectId+ );}case 'toggleGalleryImageInSelection': {- return updateGalleryValues(state, (values) => {- const imageName = action.image.imageName;- const selectedImageNames = getGallerySelectedImageNames(values);+ return updateGalleryValues(+ state,+ (values) => {+ const imageName = action.image.imageName;+ const selectedImageNames = getGallerySelectedImageNames(values);++ if (!selectedImageNames.includes(imageName)) {+ return {+ ...values,+ selectedImage: action.image,+ selectedImageName: imageName,+ selectedImageNames: [...selectedImageNames, imageName],+ };+ }++ const remainingImageNames = selectedImageNames.filter((name) => name !== imageName);+ const wasPrimary = values.selectedImageName === imageName;- if (!selectedImageNames.includes(imageName)) {return {...values,- selectedImage: action.image,- selectedImageName: imageName,- selectedImageNames: [...selectedImageNames, imageName],+ selectedImage: wasPrimary ? null : values.selectedImage,+ selectedImageName: wasPrimary+ ? (remainingImageNames[remainingImageNames.length - 1] ?? null)+ : values.selectedImageName,+ selectedImageNames: remainingImageNames,};- }-- const remainingImageNames = selectedImageNames.filter((name) => name !== imageName);- const wasPrimary = values.selectedImageName === imageName;-- return {- ...values,- selectedImage: wasPrimary ? null : values.selectedImage,- selectedImageName: wasPrimary- ? (remainingImageNames[remainingImageNames.length - 1] ?? null)- : values.selectedImageName,- selectedImageNames: remainingImageNames,- };- });+ },+ action.projectId+ );}case 'setGalleryMultiSelection': {- return updateGalleryValues(state, (values) => ({- ...values,- selectedImage: action.primaryImage,- selectedImageName: action.primaryImage.imageName,- selectedImageNames: action.imageNames,- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ selectedImage: action.primaryImage,+ selectedImageName: action.primaryImage.imageName,+ selectedImageNames: action.imageNames,+ }),+ action.projectId+ );}case 'setGalleryCompareImage': {- return updateGalleryValues(state, (values) => ({ ...values, compareImage: action.image }));+ return updateGalleryValues(state, (values) => ({ ...values, compareImage: action.image }), action.projectId);}case 'selectGalleryBoard': {- return updateGalleryValues(state, (values) => ({- ...values,- galleryPage: 0,- selectedBoardId: action.boardId,- selectedImageNames: [],- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryPage: 0,+ selectedBoardId: action.boardId,+ selectedImageNames: [],+ }),+ action.projectId+ );}case 'setGalleryView': {- return updateGalleryValues(state, (values) => ({- ...values,- galleryPage: 0,- galleryView: action.galleryView,- selectedImageNames: [],- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryPage: 0,+ galleryView: action.galleryView,+ selectedImageNames: [],+ }),+ action.projectId+ );}case 'setGallerySearchTerm': {- return updateGalleryValues(state, (values) => ({- ...values,- galleryPage: 0,- searchTerm: action.searchTerm,- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryPage: 0,+ searchTerm: action.searchTerm,+ }),+ action.projectId+ );}case 'updateGallerySettings': {const resetsQuery =@@ -2042,59 +2193,83 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)action.settings.starredFirst !== undefined ||action.settings.paginationMode !== undefined;- return updateGalleryValues(state, (values) => ({- ...values,- ...action.settings,- ...(resetsQuery ? { galleryPage: 0 } : {}),- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ ...action.settings,+ ...(resetsQuery ? { galleryPage: 0 } : {}),+ }),+ action.projectId+ );}case 'setGalleryPage': {- return updateGalleryValues(state, (values) => ({ ...values, galleryPage: Math.max(0, action.page) }));+ return updateGalleryValues(+ state,+ (values) => ({ ...values, galleryPage: Math.max(0, action.page) }),+ action.projectId+ );}case 'setGalleryPageInfo': {if (!Number.isFinite(action.totalImages)) {return state;}- return updateGalleryValues(state, (values) => {- const totalImages = Math.max(0, action.totalImages);+ return updateGalleryValues(+ state,+ (values) => {+ const totalImages = Math.max(0, action.totalImages);- return values.galleryTotalImages === totalImages ? values : { ...values, galleryTotalImages: totalImages };- });+ return values.galleryTotalImages === totalImages ? values : { ...values, galleryTotalImages: totalImages };+ },+ action.projectId+ );}case 'touchGalleryRefresh': {- return updateGalleryValues(state, (values) => ({- ...values,- galleryImagesRefreshToken: createId('gallery-images-refresh'),- galleryRefreshToken: createId('gallery-refresh'),- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryImagesRefreshToken: createId('gallery-images-refresh'),+ galleryRefreshToken: createId('gallery-refresh'),+ }),+ action.projectId+ );}case 'touchGalleryImagesRefresh': {- return updateGalleryValues(state, (values) => ({- ...values,- galleryImagesRefreshToken: createId('gallery-images-refresh'),- }));+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryImagesRefreshToken: createId('gallery-images-refresh'),+ }),+ action.projectId+ );}case 'removeGalleryImages': {const removedImageNames = new Set(action.imageNames);- return updateGalleryValues(state, (values) => {- const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;- const compareImage = values.compareImage as GeneratedImageContract | null | undefined;- const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;+ return updateGalleryValues(+ state,+ (values) => {+ const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;+ const compareImage = values.compareImage as GeneratedImageContract | null | undefined;+ const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;- return {- ...values,- compareImage: compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage,- recentImages: getGalleryImages(values).filter((image) => !removedImageNames.has(image.imageName)),- selectedImage: selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage,- selectedImageName: selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName,- selectedImageNames: getGallerySelectedImageNames(values).filter((name) => !removedImageNames.has(name)),- };- });+ return {+ ...values,+ compareImage: compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage,+ recentImages: getGalleryImages(values).filter((image) => !removedImageNames.has(image.imageName)),+ selectedImage: selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage,+ selectedImageName: selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName,+ selectedImageNames: getGallerySelectedImageNames(values).filter((name) => !removedImageNames.has(name)),+ };+ },+ action.projectId+ );}case 'setGalleryProjectBoardId': {- return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }));+ return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);}case 'toggleCanvasStagingVisibility': {return updateActiveProject(state, (project) => {@@ -2455,6 +2630,10 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)case 'setBackendConnectionStatus': {const timestamp = now();+ if (state.backendConnection.status === action.status && state.backendConnection.error === action.error) {+ return state;+ }+return {...state,backendConnection: {@@ -2475,10 +2654,15 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction));}case 'setActiveProjectSettings': {- return updateActiveProject(state, (project) => ({- ...project,- settings: normalizeProjectSettings({ ...project.settings, ...action.settings }),- }));+ return updateActiveProject(state, (project) => {+ const settings = normalizeProjectSettings({ ...project.settings, ...action.settings });++ return Object.entries(settings).every(([key, value]) =>+ Object.is(project.settings[key as keyof ProjectSettings], value)+ )+ ? project+ : { ...project, settings };+ });}}};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.tsindex 9824b27731..c208d8932d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts@@ -67,6 +67,7 @@ describe('createWorkbenchStore', () => {it('updates hydration metadata without changing durable workbench state', () => {const store = createWorkbenchStore();const initialState = store.getState();+ const initialPersistedRevision = store.getPersistedRevision();const listener = vi.fn();store.subscribe(listener);@@ -76,12 +77,34 @@ describe('createWorkbenchStore', () => {expect(listener).toHaveBeenCalledTimes(1);expect(store.getSnapshot().hasHydrated).toBe(true);expect(store.getState()).toBe(initialState);+ expect(store.getPersistedRevision()).toBe(initialPersistedRevision);store.setHasHydrated(true);expect(listener).toHaveBeenCalledTimes(1);});+ it('bumps persisted revision only for autosaved state changes', () => {+ const store = createWorkbenchStore();+ const initialPersistedRevision = store.getPersistedRevision();++ store.dispatch({ status: 'connected', type: 'setBackendConnectionStatus' });++ expect(store.getPersistedRevision()).toBe(initialPersistedRevision);++ store.dispatch({ kind: 'info', title: 'Global notice', type: 'recordNotice' });++ expect(store.getPersistedRevision()).toBe(initialPersistedRevision);++ store.dispatch({+ name: 'Persisted rename',+ projectId: store.getSnapshot().activeProject.id,+ type: 'renameProject',+ });++ expect(store.getPersistedRevision()).toBe(initialPersistedRevision + 1);+ });+it('stops notifying unsubscribed listeners', () => {const store = createWorkbenchStore();const listener = vi.fn();@@ -174,4 +197,71 @@ describe('createWorkbenchStore', () => {expect(widgetInstancesWatcher.changeCount).toBe(1);expect(placementWatcher.changeCount).toBe(0);});++ it('treats identical widget placement in a different project as a placement change', () => {+ const store = createWorkbenchStore();+ const placementWatcher = watchSelector(+ store,+ (snapshot) => getWidgetPlacementProject(snapshot.activeProject),+ areWidgetPlacementProjectsEqual+ );+ const firstProjectId = placementWatcher.current.projectId;++ store.dispatch({ type: 'createProject' });++ expect(placementWatcher.current.projectId).not.toBe(firstProjectId);+ expect(placementWatcher.changeCount).toBe(1);+ });++ it('does not notify subscribers for equivalent generate and project settings writes', () => {+ const store = createWorkbenchStore();+ const listener = vi.fn();++ store.subscribe(listener);++ store.dispatch({ batchCount: 1, type: 'setGenerateBatchCount' });+ store.dispatch({ settings: { useCpuNoise: true }, type: 'setActiveProjectSettings' });+ store.dispatch({ isCollapsed: false, region: 'left', type: 'setRegionWidgetCollapsed' });+ store.dispatch({+ region: 'left',+ sizePx: store.getSnapshot().activeProject.widgetRegions.left.sizePx,+ type: 'setRegionWidgetSize',+ });+ store.dispatch({ type: 'patchWidgetValues', values: {}, widgetId: 'generate' });+ store.dispatch({ status: 'connecting', type: 'setBackendConnectionStatus' });++ expect(listener).not.toHaveBeenCalled();+ });++ it('does not notify subscribers for equivalent queue status writes', () => {+ const store = createWorkbenchStore();+ const project = store.getSnapshot().activeProject;+ const listener = vi.fn();++ store.subscribe(listener);++ store.dispatch({+ projectId: project.id,+ queueItemId: 'missing-queue-item',+ status: 'pending',+ type: 'setQueueItemStatus',+ });++ expect(listener).not.toHaveBeenCalled();+ });++ it('keeps placement selectors stable across generate, queue, and settings changes', () => {+ const store = createWorkbenchStore();+ const placementWatcher = watchSelector(+ store,+ (snapshot) => getWidgetPlacementProject(snapshot.activeProject),+ areWidgetPlacementProjectsEqual+ );++ store.dispatch({ batchCount: 2, type: 'setGenerateBatchCount' });+ store.dispatch({ backendSupportsCancellation: true, type: 'submitInvocationSnapshot' });+ store.dispatch({ settings: { useCpuNoise: false }, type: 'setActiveProjectSettings' });++ expect(placementWatcher.changeCount).toBe(0);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 84232d713b..0ea52e0c74 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -2,6 +2,7 @@ import type { Dispatch } from 'react';import type { Project, WorkbenchState } from './types';+import { createExternalStore } from './externalStore';import { createInitialWorkbenchState, workbenchReducer, type WorkbenchAction } from './workbenchState';export interface WorkbenchSnapshot {@@ -12,6 +13,7 @@ export interface WorkbenchSnapshot {export interface WorkbenchStore {dispatch: Dispatch<WorkbenchAction>;+ getPersistedRevision: () => number;getSnapshot: () => WorkbenchSnapshot;getState: () => WorkbenchState;setHasHydrated: (hasHydrated: boolean) => void;@@ -27,43 +29,42 @@ const createSnapshot = (state: WorkbenchState, hasHydrated: boolean): WorkbenchSstate,});+const hasPersistedStateChanged = (previous: WorkbenchState, next: WorkbenchState): boolean =>+ !Object.is(previous.account, next.account) ||+ previous.activeProjectId !== next.activeProjectId ||+ !Object.is(previous.errorLog, next.errorLog) ||+ !Object.is(previous.projects, next.projects) ||+ !Object.is(previous.widgetFailures, next.widgetFailures);+export const createWorkbenchStore = (initialState = createInitialWorkbenchState()): WorkbenchStore => {let state = initialState;let hasHydrated = false;- let snapshot = createSnapshot(state, hasHydrated);- const listeners = new Set<() => void>();-- const emit = (): void => {- for (const listener of listeners) {- listener();- }- };+ let persistedRevision = 0;+ const snapshotStore = createExternalStore(createSnapshot(state, hasHydrated));const setSnapshotState = (nextState: WorkbenchState, nextHasHydrated = hasHydrated): void => {if (Object.is(nextState, state) && nextHasHydrated === hasHydrated) {return;}+ if (!Object.is(nextState, state) && hasPersistedStateChanged(state, nextState)) {+ persistedRevision += 1;+ }+state = nextState;hasHydrated = nextHasHydrated;- snapshot = createSnapshot(state, hasHydrated);- emit();+ snapshotStore.setSnapshot(createSnapshot(state, hasHydrated));};return {dispatch(action) {setSnapshotState(workbenchReducer(state, action));},- getSnapshot: () => snapshot,+ getPersistedRevision: () => persistedRevision,+ getSnapshot: snapshotStore.getSnapshot,getState: () => state,setHasHydrated: (nextHasHydrated) => setSnapshotState(state, nextHasHydrated),- subscribe(listener) {- listeners.add(listener);-- return () => {- listeners.delete(listener);- };- },+ subscribe: snapshotStore.subscribe,};};diff --git a/invokeai/frontend/webv2/src/workbench/workflows/templates.ts b/invokeai/frontend/webv2/src/workbench/workflows/templates.tsindex 7d0f28ae52..fbe8cc841c 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/templates.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/templates.ts@@ -380,5 +380,7 @@ export const ensureInvocationTemplatesLoaded = (): void => {export const useInvocationTemplatesSnapshot = (): InvocationTemplatesSnapshot => store.useSnapshot();+export const useInvocationTemplatesSelector = store.useSelector;+/** Imperative read for the workbench reducer and route validation. */export const getInvocationTemplatesSnapshot = (): InvocationTemplatesSnapshot => store.getSnapshot();