Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(webv2): migrate workbench UI to selectors

joshistoast61e9bc92d310
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
index 72c99fc61c..c4549df18b 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
@@ -10,7 +10,7 @@ import { normalizeGenerateSettings } from './generation/settings';
import { addImagesToGalleryBoard } from './gallery/api';
import { ensureInvocationTemplatesLoaded } from './workflows/templates';
import type { Project, QueueItem } from './types';
-import { useWorkbench } from './WorkbenchContext';
+import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } from './WorkbenchContext';
import type { WorkbenchAction } from './workbenchState';
const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {
@@ -139,7 +139,9 @@ const submitQueueItem = (
* inside the WorkbenchProvider; renders nothing.
*/
export const WorkbenchRuntime = () => {
- const { state, dispatch, hasHydrated } = useWorkbench();
+ const state = useWorkbenchSelector((snapshot) => snapshot.state);
+ const dispatch = useWorkbenchDispatch();
+ const hasHydrated = useWorkbenchHasHydrated();
const coordinatorRef = useRef<QueueCoordinator | null>(null);
const startedQueueItemIdsRef = useRef(new Set<string>());
const cancelledQueueItemIdsRef = useRef(new Set<string>());
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx
index 9eeecf3b09..2655043f88 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchSessionController.tsx
@@ -2,7 +2,7 @@ import { useNavigate } from '@tanstack/react-router';
import { useEffect, useRef } from 'react';
import { hydrateProjectFromServer } from './projects/syncedPersistence';
-import { useWorkbench } from './WorkbenchContext';
+import { useWorkbenchDispatch, useWorkbenchHasHydrated, useWorkbenchSelector } from './WorkbenchContext';
import type { WorkbenchSearch } from './projects/session';
/**
@@ -18,7 +18,9 @@ import type { WorkbenchSearch } from './projects/session';
* library and opens it if not.
*/
export const WorkbenchSessionController = ({ search }: { search: WorkbenchSearch }) => {
- const { state, dispatch, hasHydrated } = useWorkbench();
+ const state = useWorkbenchSelector((snapshot) => snapshot.state);
+ const dispatch = useWorkbenchDispatch();
+ const hasHydrated = useWorkbenchHasHydrated();
const navigate = useNavigate();
const latestStateRef = useRef(state);
// The mount-time param was already handled by the boot load options.
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchShell.tsx
index b9791481d1..6a8e582e8e 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchShell.tsx
@@ -11,7 +11,7 @@ import { WidgetBar, type WidgetBarItem } from './components/WidgetBar';
import { FocusRegionProvider } from './focusRegions';
import { WorkbenchWidgetRegistryProvider } from './WorkbenchWidgetRegistryContext';
import { getWidgetsForRegion, widgetRegistrationFailures } from './widgetRegistry';
-import { useWorkbench } from './WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch } from './WorkbenchContext';
import type { WidgetId, WidgetRegion } from './types';
const getWidgetBarItems = (region: WidgetRegion, enabledWidgetIds: WidgetId[]): WidgetBarItem[] =>
@@ -34,7 +34,8 @@ const getWidgetBarItems = (region: WidgetRegion, enabledWidgetIds: WidgetId[]):
* whose column template had to stay in lockstep with conditional children.
*/
export const WorkbenchShell = () => {
- const { activeProject, dispatch } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
const { panels } = activeProject.layout;
const leftRegion = activeProject.widgetRegions.left;
const rightRegion = activeProject.widgetRegions.right;
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx
index ca727310fe..f933f64235 100644
--- a/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx
@@ -6,7 +6,7 @@ import { ChevronDownIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide
import { MenuContent } from '../../components/ui/Menu';
import { SettingsButton } from '../../settings/SettingsDialog';
import { useOptionalOpenWorkbenchWidget } from '../../useOpenWorkbenchWidget';
-import { useOptionalWorkbench } from '../../WorkbenchContext';
+import { useOptionalWorkbenchStore } from '../../WorkbenchContext';
import { logoutSession, useAuthSession } from '../session';
import { ProfileDialog } from './ProfileDialog';
@@ -17,7 +17,7 @@ import { ProfileDialog } from './ProfileDialog';
*/
export const AccountMenu = () => {
const session = useAuthSession();
- const workbench = useOptionalWorkbench();
+ const hasWorkbench = useOptionalWorkbenchStore() !== null;
const openWorkbenchWidget = useOptionalOpenWorkbenchWidget();
const navigate = useNavigate();
const [isProfileOpen, setIsProfileOpen] = useState(false);
@@ -30,7 +30,7 @@ export const AccountMenu = () => {
const label = user.display_name?.trim() || user.email;
const openUserManagement = () => {
- if (!workbench?.activeProject) {
+ if (!hasWorkbench) {
return;
}
@@ -93,7 +93,7 @@ export const AccountMenu = () => {
<Icon as={UserRoundCogIcon} boxSize="3.5" />
Account settings
</Menu.Item>
- {user.is_admin && workbench ? (
+ {user.is_admin && hasWorkbench ? (
<Menu.Item value="users" onClick={openUserManagement}>
<Icon as={UsersIcon} boxSize="3.5" />
Manage users
diff --git a/invokeai/frontend/webv2/src/workbench/components/BottomPanel.tsx b/invokeai/frontend/webv2/src/workbench/components/BottomPanel.tsx
index 754e23d5cd..759cd54483 100644
--- a/invokeai/frontend/webv2/src/workbench/components/BottomPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/BottomPanel.tsx
@@ -1,11 +1,10 @@
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector } from '../WorkbenchContext';
import { getWidgetById } from '../widgetRegistry';
import { MissingWidgetFrame, WidgetRenderer } from './WidgetRenderer';
export const BottomPanel = () => {
- const { activeProject } = useWorkbench();
- const { panels } = activeProject.layout;
- const bottomRegion = activeProject.widgetRegions.bottom;
+ const panels = useActiveProjectSelector((project) => project.layout.panels);
+ const bottomRegion = useActiveProjectSelector((project) => project.widgetRegions.bottom);
const widget = getWidgetById(bottomRegion.activeWidgetId);
const View = widget?.manifest.view;
const canShowBottomPanel =
diff --git a/invokeai/frontend/webv2/src/workbench/components/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/components/CenterArea.tsx
index 472bfaf902..d7a5a2f386 100644
--- a/invokeai/frontend/webv2/src/workbench/components/CenterArea.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/CenterArea.tsx
@@ -2,7 +2,7 @@ import { Box, Flex, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { CheckIcon, MoreHorizontalIcon } from 'lucide-react';
import { WidgetIcon } from '../iconResolver';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../WorkbenchContext';
import type { RegisteredWidget, WidgetId } from '../types';
import { getWidgetsForRegion } from '../widgetRegistry';
import { useFocusRegionProps } from '../focusRegions';
@@ -29,9 +29,9 @@ const getCenterWidgetItems = (enabledWidgetIds: string[]): CenterWidgetItem[] =>
/** Center work area: the view tab strip plus the active registered center view. */
export const CenterArea = () => {
- const { activeProject, dispatch } = useWorkbench();
+ const centerRegion = useActiveProjectSelector((project) => project.widgetRegions.center);
+ const dispatch = useWorkbenchDispatch();
const focusRegionProps = useFocusRegionProps('center');
- const centerRegion = activeProject.widgetRegions.center;
const centerWidgetItems = getCenterWidgetItems(centerRegion.enabledWidgetIds);
const enabledCenterWidgetItems = centerWidgetItems.filter((item) => item.isEnabled && item.status === 'enabled');
const centerViewItems = enabledCenterWidgetItems.filter((item) => item.widget.manifest.centerPlacement !== 'toolbar');
diff --git a/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
index c35683917c..dd3826e9e9 100644
--- a/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/GraphPreviewDialog.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react';
import { formatRoute, isInvocationRouteValid, resolveInvocationRoute } from '../invocation';
import type { GraphContract, GraphId, InvocationSourceId } from '../types';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch } from '../WorkbenchContext';
import type { XYPosition } from '../workflows/types';
import { GraphPreviewFlow } from './GraphPreviewFlow';
import { Button } from './ui/Button';
@@ -31,7 +31,8 @@ export const GraphPreviewDialog = ({
title,
onOpenChange,
}: GraphPreviewDialogProps) => {
- const { activeProject, dispatch } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
const [mode, setMode] = useState<PreviewMode>('nodes');
const dialogRoute = sourceId
? resolveInvocationRoute(activeProject, 'dialog', { ...activeProject.invocation, sourceId, sourceLocked: true })
diff --git a/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx
index 1ebfe0942b..e0982f93b8 100644
--- a/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/InvokeControl.tsx
@@ -2,7 +2,7 @@ import { Flex, Group, HStack, Icon, Menu, Portal, Stack, Text, VStack } from '@c
import { useEffect, useRef } from 'react';
import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch, useWorkbenchSelector } from '../WorkbenchContext';
import {
formatRoute,
invocationSources,
@@ -28,7 +28,9 @@ import { Tooltip } from './ui/Tooltip';
const CONTROL_WIDTH = '12rem';
export const InvokeControl = () => {
- const { activeProject, dispatch, state } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
const { invocation } = activeProject;
// Project-graph route validation reads the invocation templates imperatively;
@@ -37,7 +39,7 @@ export const InvokeControl = () => {
const resolvedRoute = resolveInvocationRoute(activeProject);
const isLocked = invocation.sourceLocked || invocation.destinationLocked;
- const isConnected = state.backendConnection.status === 'connected';
+ const isConnected = backendConnectionStatus === 'connected';
// Legacy parity: the queue button disables with the full list of reasons,
// including a disconnected backend.
const blockingReasons = [
diff --git a/invokeai/frontend/webv2/src/workbench/components/LayoutPresetMenu.tsx b/invokeai/frontend/webv2/src/workbench/components/LayoutPresetMenu.tsx
index a6cacf2954..c4957cea90 100644
--- a/invokeai/frontend/webv2/src/workbench/components/LayoutPresetMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/LayoutPresetMenu.tsx
@@ -1,7 +1,7 @@
import { Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
import { CheckIcon, ChevronDownIcon } from 'lucide-react';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../WorkbenchContext';
import { getLayoutPreset, layoutPresets } from '../layoutPresets';
import type { LayoutPresetId } from '../types';
import { Button } from './ui/Button';
@@ -15,8 +15,9 @@ import { Button } from './ui/Button';
* one mutates only the active project's layout state, per the spec.
*/
export const LayoutPresetMenu = () => {
- const { activeProject, dispatch } = useWorkbench();
- const activePreset = getLayoutPreset(activeProject.layout.presetId);
+ const activePresetId = useActiveProjectSelector((project) => project.layout.presetId);
+ const dispatch = useWorkbenchDispatch();
+ const activePreset = getLayoutPreset(activePresetId);
return (
<Menu.Root positioning={{ placement: 'bottom-end' }}>
diff --git a/invokeai/frontend/webv2/src/workbench/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/components/OpenProjectDialog.tsx
index 3c69835fb6..9efdb4c4ac 100644
--- a/invokeai/frontend/webv2/src/workbench/components/OpenProjectDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/OpenProjectDialog.tsx
@@ -7,7 +7,7 @@ import { Row } from './ui/Row';
import { Scrollable } from './ui/Scrollable';
import { formatRelativeTime } from '../home/formatRelativeTime';
import { useNotify } from '../useNotify';
-import { useWorkbench } from '../WorkbenchContext';
+import { useWorkbenchDispatch, useWorkbenchSelector } from '../WorkbenchContext';
import { refreshProjectLibrary, useProjectLibrary, type ProjectSummary } from '../projects/library';
import { importProjectFile, pickProjectFile } from '../projects/projectFile';
import { adoptProjectRecord, hydrateProjectFromServer } from '../projects/syncedPersistence';
@@ -18,7 +18,8 @@ import { adoptProjectRecord, hydrateProjectFromServer } from '../projects/synced
* library and opens it in place — no navigation, the editor stays mounted.
*/
export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {
- const { state, dispatch } = useWorkbench();
+ const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);
+ const dispatch = useWorkbenchDispatch();
const notify = useNotify();
const library = useProjectLibrary();
const [busyProjectId, setBusyProjectId] = useState<string | null>(null);
@@ -29,7 +30,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos
}
}, [isOpen]);
- const openProjectIds = new Set(state.projects.map((project) => project.id));
+ const openProjectIds = new Set(projects.map((project) => project.id));
const available = library.summaries.filter((summary) => !openProjectIds.has(summary.id));
const openProject = async (summary: ProjectSummary) => {
diff --git a/invokeai/frontend/webv2/src/workbench/components/ProjectTabs.tsx b/invokeai/frontend/webv2/src/workbench/components/ProjectTabs.tsx
index 9425475a49..a9f0e7c497 100644
--- a/invokeai/frontend/webv2/src/workbench/components/ProjectTabs.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/ProjectTabs.tsx
@@ -13,7 +13,7 @@ import type { Project, WidgetRegion } from '../types';
import { exportOpenProject } from '../projects/projectFile';
import { useProjectActions } from '../projects/useProjectActions';
import { useOpenWorkbenchWidget } from '../useOpenWorkbenchWidget';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '../WorkbenchContext';
/**
* Document-style tabs for the open projects (the session), immediately right
@@ -27,7 +27,9 @@ import { useWorkbench } from '../WorkbenchContext';
* with rename, details, export, close, and delete.
*/
export const ProjectTabs = () => {
- const { state, activeProject, dispatch } = useWorkbench();
+ const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);
+ const activeProjectId = useActiveProjectSelector((project) => project.id);
+ 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);
@@ -45,9 +47,9 @@ export const ProjectTabs = () => {
return (
<>
- <Tabs.Root minW="max-content" variant="subtle" value={activeProject.id} h="full" w="full">
+ <Tabs.Root minW="max-content" variant="subtle" value={activeProjectId} h="full" w="full">
<Tabs.List flex="1 1 auto" h="full" py="1">
- {state.projects.map((project) => (
+ {projects.map((project) => (
<Tabs.Trigger
key={project.id}
value={project.id}
@@ -144,7 +146,7 @@ const ProjectTabContextMenu = ({
onRename: (project: Project) => void;
target: { project: Project; x: number; y: number } | null;
}) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const openWorkbenchWidget = useOpenWorkbenchWidget();
const targetRef = useRef(target);
diff --git a/invokeai/frontend/webv2/src/workbench/components/StatusBar.tsx b/invokeai/frontend/webv2/src/workbench/components/StatusBar.tsx
index 98af480928..39055cc3f4 100644
--- a/invokeai/frontend/webv2/src/workbench/components/StatusBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/StatusBar.tsx
@@ -4,7 +4,7 @@ import { CheckIcon, MoreHorizontalIcon } from 'lucide-react';
import { WidgetIcon } from '../iconResolver';
import type { RegisteredWidget, WidgetId } from '../types';
import { getWidgetsForRegion } from '../widgetRegistry';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../WorkbenchContext';
import { WidgetRenderer } from './WidgetRenderer';
import { Row } from './ui/Row';
import { Tooltip } from './ui/Tooltip';
@@ -20,8 +20,8 @@ interface BottomWidgetItem {
}
export const StatusBar = () => {
- const { activeProject, dispatch } = useWorkbench();
- const bottomRegion = activeProject.widgetRegions.bottom;
+ const bottomRegion = useActiveProjectSelector((project) => project.widgetRegions.bottom);
+ const dispatch = useWorkbenchDispatch();
const items: BottomWidgetItem[] = getWidgetsForRegion('bottom').map((widget) => ({
failureMessage: widget.failure?.message,
id: widget.manifest.id,
diff --git a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
index 88101f5ea1..b2bc067e50 100644
--- a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
@@ -25,7 +25,7 @@ import { getDestinationLabel, getSourceLabel } from '../invocation';
import { getQueueItemExpectedImageCount, getQueueProgressBarState, getQueueSummary } from '../queueSummary';
import { useWorkbenchPreferences } from '../settings/store';
import type { QueueItem } from '../types';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '../WorkbenchContext';
import { DEFAULT_THEME_ID, THEMES_BY_ID } from '../../theme/themes';
import { Tooltip } from './ui/Tooltip';
import { Link } from '@tanstack/react-router';
@@ -92,8 +92,9 @@ const getBatchCount = (values: Record<string, unknown>): number => {
};
const BatchCountField = () => {
- const { activeProject, dispatch } = useWorkbench();
- const batchCount = getBatchCount(activeProject.widgetStates.generate.values);
+ const generateValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const dispatch = useWorkbenchDispatch();
+ const batchCount = getBatchCount(generateValues);
return (
<NumberInput.Root
@@ -117,17 +118,18 @@ const BatchCountField = () => {
};
const QueueInfo = () => {
- const { activeProject, state } = useWorkbench();
+ const queueItems = useActiveProjectSelector((project) => project.queue.items);
+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
const modelLoads = useModelLoads();
const openWorkbenchWidget = useOpenWorkbenchWidget();
- const baseSummary = getQueueSummary(activeProject.queue.items);
+ const baseSummary = getQueueSummary(queueItems);
const runningProgress = useQueueItemProgress(baseSummary.runningQueueItemId ?? '');
- const summary = getQueueSummary(activeProject.queue.items, runningProgress);
+ const summary = getQueueSummary(queueItems, runningProgress);
const runningItem = summary.runningQueueItemId
- ? activeProject.queue.items.find((item) => item.id === summary.runningQueueItemId)
+ ? queueItems.find((item) => item.id === summary.runningQueueItemId)
: undefined;
const progressState = getQueueProgressBarState({
- isConnected: state.backendConnection.status === 'connected',
+ isConnected: backendConnectionStatus === 'connected',
isRunning: Boolean(runningItem),
loadingModelsCount: modelLoads.length,
progress: runningProgress,
diff --git a/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx
index 6cfc08cc67..93dc881705 100644
--- a/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/WidgetActionsMenu.tsx
@@ -2,7 +2,7 @@ import { Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { useState } from 'react';
import { GitBranchIcon, MoreHorizontalIcon, TargetIcon } from 'lucide-react';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch } from '../WorkbenchContext';
import { createGraphBearingSurface } from '../graphSurfaces';
import { compileProjectGraph } from '../workflows/buildGraph';
import { getInvocationTemplatesSnapshot } from '../workflows/templates';
@@ -44,7 +44,8 @@ const GraphSurfaceMenuItems = ({
surface: GraphBearingSurfaceContract;
onPreview: () => void;
}) => {
- const { activeProject, dispatch } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
const isActiveSource = activeProject.invocation.sourceId === surface.sourceId;
return (
@@ -75,7 +76,7 @@ const GraphSurfaceMenuItems = ({
};
export const WidgetActionsMenu = ({ manifest, region }: { manifest: WidgetManifest; region: WorkbenchRegion }) => {
- const { activeProject } = useWorkbench();
+ const activeProject = useActiveProject();
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const surface = manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region) : null;
const HeaderMenu = manifest.headerMenu;
diff --git a/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
index fa780bc6d1..3c82bc3d6c 100644
--- a/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/WidgetFrames.tsx
@@ -12,7 +12,7 @@ import { SettingsIcon, type LucideIcon } from 'lucide-react';
import { useFocusRegionProps } from '../focusRegions';
import { openWorkbenchSettings } from '../settings/settingsDialogStore';
import type { WidgetManifest, WidgetRegion, WorkbenchRegion } from '../types';
-import { useWorkbench } from '../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../WorkbenchContext';
import { WidgetActionsMenu } from './WidgetActionsMenu';
import { IconButton } from './ui/Button';
@@ -43,8 +43,8 @@ export const WidgetPanelFrame = ({
children: ReactNode;
region: Exclude<WidgetRegion, 'center'>;
}) => {
- const { activeProject, dispatch } = useWorkbench();
- const regionState = activeProject.widgetRegions[region];
+ const regionState = useActiveProjectSelector((project) => project.widgetRegions[region]);
+ const dispatch = useWorkbenchDispatch();
const [dragSizePx, setDragSizePx] = useState<number | null>(null);
const isLeft = region === 'left';
const isBottom = region === 'bottom';
diff --git a/invokeai/frontend/webv2/src/workbench/components/WorkbenchNotificationToaster.tsx b/invokeai/frontend/webv2/src/workbench/components/WorkbenchNotificationToaster.tsx
index 97a17ed75c..56eda48495 100644
--- a/invokeai/frontend/webv2/src/workbench/components/WorkbenchNotificationToaster.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/WorkbenchNotificationToaster.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef } from 'react';
import type { WorkbenchNotificationKind } from '../types';
-import { useWorkbench } from '../WorkbenchContext';
+import { useWorkbenchSelector } from '../WorkbenchContext';
import { toaster } from './ui/toaster';
const notificationToastType: Record<WorkbenchNotificationKind, 'error' | 'info' | 'success'> = {
@@ -11,16 +11,16 @@ const notificationToastType: Record<WorkbenchNotificationKind, 'error' | 'info'
};
export const WorkbenchNotificationToaster = () => {
- const { state } = useWorkbench();
+ const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);
const toastedNotificationIdsRef = useRef<Set<string> | null>(null);
useEffect(() => {
if (toastedNotificationIdsRef.current === null) {
- toastedNotificationIdsRef.current = new Set(state.notifications.map((notification) => notification.id));
+ toastedNotificationIdsRef.current = new Set(notifications.map((notification) => notification.id));
return;
}
- for (const notification of [...state.notifications].reverse()) {
+ for (const notification of [...notifications].reverse()) {
if (toastedNotificationIdsRef.current.has(notification.id)) {
continue;
}
@@ -34,7 +34,7 @@ export const WorkbenchNotificationToaster = () => {
});
});
}
- }, [state.notifications]);
+ }, [notifications]);
return null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
index 86a5b3b572..8d05334f55 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
@@ -10,7 +10,7 @@ import {
} from './syncedPersistence';
import type { Project } from '../types';
import { useNotify } from '../useNotify';
-import { useWorkbench } from '../WorkbenchContext';
+import { useWorkbenchDispatch, useWorkbenchSelector } from '../WorkbenchContext';
/**
* Close and delete for projects that are open in the editor, shared by the
@@ -26,7 +26,8 @@ export const useProjectActions = (): {
closeProject: (project: Project) => void;
deleteProject: (project: Project) => Promise<void>;
} => {
- const { state, dispatch } = useWorkbench();
+ const state = useWorkbenchSelector((snapshot) => snapshot.state);
+ const dispatch = useWorkbenchDispatch();
const navigate = useNavigate();
const notify = useNotify();
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
index 821644f19f..38f4032de1 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
@@ -40,12 +40,17 @@ import type {
DeveloperLogLevel,
DeveloperLogNamespace,
ProjectSettings,
+ Project,
SettingsSectionId,
WorkbenchLanguage,
WorkbenchPreferences,
WorkbenchThemeId,
} from '../types';
-import { useOptionalWorkbench } from '../WorkbenchContext';
+import {
+ useOptionalWorkbenchDispatch,
+ useOptionalWorkbenchSelector,
+ useOptionalWorkbenchStore,
+} from '../WorkbenchContext';
import {
closeWorkbenchSettings,
openWorkbenchSettings,
@@ -155,7 +160,7 @@ const SettingsDialogContent = () => {
};
const SettingsTabs = () => {
- const workbench = useOptionalWorkbench();
+ const hasWorkbench = useOptionalWorkbenchStore() !== null;
const allTabs: SettingsTabDefinition[] = [
{
children: <AppearanceSection />,
@@ -171,7 +176,7 @@ const SettingsTabs = () => {
},
{
children: <ProjectSection />,
- condition: Boolean(workbench),
+ condition: hasWorkbench,
icon: FolderIcon,
label: 'Project',
value: 'project',
@@ -381,20 +386,21 @@ const BehaviorSection = () => {
};
const ProjectSection = () => {
- const workbench = useOptionalWorkbench();
+ const activeProject = useOptionalWorkbenchSelector<Project | null>((snapshot) => snapshot.activeProject, null);
+ const dispatch = useOptionalWorkbenchDispatch();
- if (!workbench) {
+ if (!activeProject || !dispatch) {
return null;
}
- const settings = workbench.activeProject.settings;
+ const settings = activeProject.settings;
const updateProjectSettings = (patch: Partial<ProjectSettings>) => {
- workbench.dispatch({ settings: patch, type: 'setActiveProjectSettings' });
+ dispatch({ settings: patch, type: 'setActiveProjectSettings' });
};
return (
<SettingsSection
- description={`Settings saved with ${workbench.activeProject.name}. Future project-only settings can live here without becoming user preferences.`}
+ description={`Settings saved with ${activeProject.name}. Future project-only settings can live here without becoming user preferences.`}
title="Project"
>
<SettingToggle
@@ -535,7 +541,7 @@ const DeveloperSection = () => {
};
const WorkspaceSection = () => {
- const workbench = useOptionalWorkbench();
+ const dispatch = useOptionalWorkbenchDispatch();
const { scope } = useWorkbenchSettings();
const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);
@@ -550,8 +556,8 @@ const WorkspaceSection = () => {
title="Workspace"
>
<HStack gap="2" wrap="wrap">
- {workbench ? (
- <Button size="sm" variant="outline" onClick={() => workbench.dispatch({ type: 'resetActiveLayout' })}>
+ {dispatch ? (
+ <Button size="sm" variant="outline" onClick={() => dispatch({ type: 'resetActiveLayout' })}>
<RotateCcwIcon />
Reset layout
</Button>
diff --git a/invokeai/frontend/webv2/src/workbench/useNotify.ts b/invokeai/frontend/webv2/src/workbench/useNotify.ts
index d9899708d1..a5274ff669 100644
--- a/invokeai/frontend/webv2/src/workbench/useNotify.ts
+++ b/invokeai/frontend/webv2/src/workbench/useNotify.ts
@@ -1,7 +1,7 @@
import { useMemo } from 'react';
import type { WorkbenchNotificationKind } from './types';
-import { useOptionalWorkbench } from './WorkbenchContext';
+import { useOptionalWorkbenchDispatch } from './WorkbenchContext';
import { toaster } from './components/ui/toaster';
/**
@@ -21,8 +21,7 @@ const notificationToastType: Record<WorkbenchNotificationKind, 'error' | 'info'
};
export const useNotify = (): Notify => {
- const workbench = useOptionalWorkbench();
- const dispatch = workbench?.dispatch;
+ const dispatch = useOptionalWorkbenchDispatch();
return useMemo(() => {
const record =
diff --git a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
index 75b87c2a7e..ddbabc6dc1 100644
--- a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
+++ b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import type { RegisteredWidget, WidgetId, WidgetRegion } from './types';
-import { useOptionalWorkbench, useWorkbench } from './WorkbenchContext';
+import { useOptionalWorkbenchDispatch, useWorkbenchDispatch } from './WorkbenchContext';
import { useOptionalWorkbenchWidgetRegistry, useWorkbenchWidgetRegistry } from './WorkbenchWidgetRegistryContext';
const DEFAULT_OPEN_REGIONS: ReadonlyArray<WidgetRegion> = ['center', 'right', 'left', 'bottom'];
@@ -78,7 +78,7 @@ export const openWorkbenchWidget = (
};
export const useOpenWorkbenchWidget = () => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const { getWidgetsForRegion } = useWorkbenchWidgetRegistry();
return useCallback(
@@ -89,17 +89,17 @@ export const useOpenWorkbenchWidget = () => {
};
export const useOptionalOpenWorkbenchWidget = () => {
- const workbench = useOptionalWorkbench();
+ const dispatch = useOptionalWorkbenchDispatch();
const registry = useOptionalWorkbenchWidgetRegistry();
return useCallback(
(widgetId: WidgetId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult => {
- if (!workbench || !registry) {
+ if (!dispatch || !registry) {
return { ok: false, reason: 'unavailable' };
}
- return openWorkbenchWidget(workbench.dispatch, registry.getWidgetsForRegion, widgetId, options);
+ return openWorkbenchWidget(dispatch, registry.getWidgetsForRegion, widgetId, options);
},
- [registry, workbench]
+ [dispatch, registry]
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
index b136360895..9a9970a5e0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
@@ -3,12 +3,12 @@ import { CloudAlertIcon, CloudCheckIcon } from 'lucide-react';
import { StatusWidgetChip } from '../../components/WidgetFrames';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchSelector } from '../../WorkbenchContext';
export const AutosaveStatusWidgetView = ({ presentation }: WidgetViewProps) => {
- const { state } = useWorkbench();
- const icon = state.autosave.status === 'error' ? CloudAlertIcon : CloudCheckIcon;
- const label = state.autosave.status === 'saved' ? 'Saved' : state.autosave.status;
+ const autosave = useWorkbenchSelector((snapshot) => snapshot.state.autosave);
+ const icon = autosave.status === 'error' ? CloudAlertIcon : CloudCheckIcon;
+ const label = autosave.status === 'saved' ? 'Saved' : autosave.status;
if (presentation === 'tooltip') {
return (
@@ -19,14 +19,14 @@ export const AutosaveStatusWidgetView = ({ presentation }: WidgetViewProps) => {
<Text color="fg.subtle" fontSize="2xs">
Status: {label}
</Text>
- {state.autosave.lastSavedAt ? (
+ {autosave.lastSavedAt ? (
<Text color="fg.subtle" fontSize="2xs">
- Last saved: {state.autosave.lastSavedAt}
+ Last saved: {autosave.lastSavedAt}
</Text>
) : null}
- {state.autosave.error ? (
+ {autosave.error ? (
<Text color="fg.error" fontSize="2xs">
- {state.autosave.error}
+ {autosave.error}
</Text>
) : null}
</Stack>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 3a97779b5d..d4e12414ae 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -1,12 +1,13 @@
import { Box, Flex } from '@chakra-ui/react';
import type { KeyboardEvent } from 'react';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch } from '../../WorkbenchContext';
import { CanvasDocumentFrame, CanvasPlaneImage, EmptyCanvasFrame, ToolScrubber } from './CanvasDocumentFrame';
import { CanvasStagingControls, EmptyStagingControls } from './CanvasStagingControls';
export const CanvasWidgetView = () => {
- const { activeProject, dispatch } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
const { document, stagingArea } = activeProject.canvas;
const { layers } = document;
const selectedCandidate = stagingArea.pendingImages[stagingArea.selectedImageIndex];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx
index c6874c4836..c7f40dd62c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsHeaderActions.tsx
@@ -2,21 +2,22 @@ import { Badge } from '@chakra-ui/react';
import { BugIcon } from 'lucide-react';
import { Button } from '../../components/ui/Button';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchDispatch, useWorkbenchSelector } from '../../WorkbenchContext';
export const DiagnosticsHeaderActions = () => {
- const { dispatch, state } = useWorkbench();
+ const errorCount = useWorkbenchSelector((snapshot) => snapshot.state.errorLog.length);
+ const dispatch = useWorkbenchDispatch();
return (
<>
- {state.errorLog.length ? (
+ {errorCount ? (
<Badge colorPalette="red" size="xs">
<BugIcon />
- {state.errorLog.length}
+ {errorCount}
</Badge>
) : null}
<Button
- disabled={state.errorLog.length === 0}
+ disabled={errorCount === 0}
size="2xs"
variant="outline"
onClick={() => dispatch({ type: 'clearErrorLog' })}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
index da7cdd9969..861646cbdc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
@@ -3,13 +3,13 @@ import { BugIcon, ClipboardListIcon } from 'lucide-react';
import { StatusWidgetChip } from '../../components/WidgetFrames';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchSelector } from '../../WorkbenchContext';
import { Button } from '../../components/ui/Button';
import { Panel } from '../../components/ui/Panel';
export const DiagnosticsWidgetView = ({ presentation, region }: WidgetViewProps) => {
- const { state } = useWorkbench();
- const errorCount = state.errorLog.length;
+ const errorLog = useWorkbenchSelector((snapshot) => snapshot.state.errorLog);
+ const errorCount = errorLog.length;
const label = errorCount === 0 ? 'Clean' : `${errorCount} issue${errorCount === 1 ? '' : 's'}`;
if (region === 'bottom' && presentation !== 'expanded') {
@@ -22,17 +22,17 @@ export const DiagnosticsWidgetView = ({ presentation, region }: WidgetViewProps)
};
const DiagnosticsPanel = () => {
- const { state } = useWorkbench();
+ const errorLog = useWorkbenchSelector((snapshot) => snapshot.state.errorLog);
return (
<Stack gap="3">
- {state.errorLog.length === 0 ? (
+ {errorLog.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs">
Shell errors and debugging details will appear here without covering the workbench.
</Text>
) : (
<Stack gap="2">
- {state.errorLog.map((message, index) => (
+ {errorLog.map((message, index) => (
<Panel key={`${message}-${index}`} gap="2" p="2">
<Text color="fg.muted" fontFamily="mono" fontSize="2xs" whiteSpace="pre-wrap">
{message}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
index 811500f272..5f65aac96e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
@@ -4,7 +4,7 @@ import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { IconButton } from '../../components/ui/Button';
import { getGallerySettings } from '../../gallery/settings';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../WorkbenchContext';
import { getGalleryPage, getGalleryTotalImages } from './galleryStateView';
import { GALLERY_PAGE_SIZE } from './useGalleryData';
@@ -14,8 +14,8 @@ import { GALLERY_PAGE_SIZE } from './useGalleryData';
* decoupled from the view's data fetching.
*/
export const GalleryWidgetFooter = (_props: WidgetViewProps) => {
- const { activeProject, dispatch } = useWorkbench();
- const galleryValues = activeProject.widgetStates.gallery.values;
+ const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
+ const dispatch = useWorkbenchDispatch();
const settings = getGallerySettings(galleryValues);
const page = getGalleryPage(galleryValues);
const totalImages = getGalleryTotalImages(galleryValues);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
index fcd01a9eca..57cb602437 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
@@ -5,7 +5,7 @@ import { StatusWidgetChip } from '../../components/WidgetFrames';
import { useImageActions } from '../../components/useImageActions';
import { getGallerySettings } from '../../gallery/settings';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch } from '../../WorkbenchContext';
import { GalleryPanelContent } from './GalleryPanelContent';
import {
getGalleryPage,
@@ -23,7 +23,8 @@ import { useGalleryActions } from './useGalleryActions';
import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';
export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) => {
- const { activeProject, dispatch } = useWorkbench();
+ const activeProject = useActiveProject();
+ const dispatch = useWorkbenchDispatch();
const galleryValues = activeProject.widgetStates.gallery.values;
const galleryView = getGalleryView(galleryValues);
const searchTerm = getGallerySearchTerm(galleryValues);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
index 4830a0c9a5..83f4c04d79 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
@@ -5,11 +5,12 @@ import { normalizeGenerateSettings, normalizeGenerateWidgetValues } from '../../
import type { GenerateSettings, VaeModelConfig } from '../../generation/types';
import { ensureModelsLoaded, useModelsSnapshot } from '../../models/modelsStore';
import type { ModelConfig } from '../../models/types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../WorkbenchContext';
import { GenerateSettingsForm } from './GenerateSettingsForm';
export const GenerateWidgetView = () => {
- const { activeProject, dispatch } = useWorkbench();
+ const storedValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const dispatch = useWorkbenchDispatch();
const { error, models, status } = useModelsSnapshot();
useEffect(() => {
@@ -21,7 +22,6 @@ export const GenerateWidgetView = () => {
() => models.filter((model): model is ModelConfig & VaeModelConfig => model.type === 'vae'),
[models]
);
- const storedValues = activeProject.widgetStates.generate.values;
const normalizedSettings = normalizeGenerateSettings(storedValues);
const selectedModel = supportedModels.find((model) => model.key === normalizedSettings?.modelKey);
const settings = normalizedSettings ?? getDefaultGenerateSettings(selectedModel ?? supportedModels[0]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/history-controls/HistoryControlsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/history-controls/HistoryControlsWidgetView.tsx
index 8c8359dacc..06f4b92a3c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/history-controls/HistoryControlsWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/history-controls/HistoryControlsWidgetView.tsx
@@ -2,12 +2,12 @@ import { HStack } from '@chakra-ui/react';
import { Redo2Icon, Undo2Icon } from 'lucide-react';
import { IconButton } from '../../components/ui/Button';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../WorkbenchContext';
export const HistoryControlsWidgetView = () => {
- const { activeProject, dispatch } = useWorkbench();
- const canUndo = activeProject.undoRedo.past.length > 0;
- const canRedo = activeProject.undoRedo.future.length > 0;
+ const canUndo = useActiveProjectSelector((project) => project.undoRedo.past.length > 0);
+ const canRedo = useActiveProjectSelector((project) => project.undoRedo.future.length > 0);
+ const dispatch = useWorkbenchDispatch();
return (
<HStack align="stretch" gap="1" h="full">
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index b7bd84c59b..33baa4d26a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -2,10 +2,10 @@ import { Box, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';
import { LayersIcon } from 'lucide-react';
import { Panel } from '../../components/ui/Panel';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProject } from '../../WorkbenchContext';
export const LayersWidgetView = () => {
- const { activeProject } = useWorkbench();
+ const activeProject = useActiveProject();
const layers = activeProject.canvas.document.layers;
return (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/LayoutHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/LayoutHeaderActions.tsx
index 3a29cf6a51..a57fcf71e6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/LayoutHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/LayoutHeaderActions.tsx
@@ -1,10 +1,10 @@
import { HStack } from '@chakra-ui/react';
import { Button } from '../../components/ui/Button';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../WorkbenchContext';
export const LayoutHeaderActions = () => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
return (
<HStack gap="1">
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx
index 7e634a83e8..ef1b6f64b8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef } from 'react';
import { refreshInstalls, useInstallOutcomes } from '../../models/installsStore';
import { refreshModels } from '../../models/modelsStore';
import { useNotify } from '../../useNotify';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchSelector } from '../../WorkbenchContext';
/**
* Renders nothing. Keeps the model stores honest across the app lifecycle:
@@ -13,10 +13,9 @@ import { useWorkbench } from '../../WorkbenchContext';
*/
export const ModelsRuntime = () => {
const notify = useNotify();
- const { state } = useWorkbench();
+ const connectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
const outcomes = useInstallOutcomes();
const seenOutcomeIdsRef = useRef<Set<number> | null>(null);
- const connectionStatus = state.backendConnection.status;
useEffect(() => {
if (connectionStatus === 'connected') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx
index ce94421895..c58a8519ff 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx
@@ -1,10 +1,10 @@
import { HStack } from '@chakra-ui/react';
import { Button } from '../../components/ui/Button';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../WorkbenchContext';
export const NotificationsHeaderActions = () => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
return (
<HStack gap="2">
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
index 4651344e4c..95fd82f53e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
@@ -3,7 +3,7 @@ import { BellIcon, CircleCheckIcon, CircleXIcon, InfoIcon, TriangleAlertIcon, ty
import { StatusWidgetChip } from '../../components/WidgetFrames';
import type { WidgetViewProps, WorkbenchNotificationKind } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchSelector } from '../../WorkbenchContext';
const kindColorPalette: Record<WorkbenchNotificationKind, string> = {
error: 'red',
@@ -18,10 +18,10 @@ const kindIcon = {
} satisfies Record<WorkbenchNotificationKind, LucideIcon>;
export const NotificationsWidgetView = ({ presentation, region }: WidgetViewProps) => {
- const { state } = useWorkbench();
- const unreadCount = state.notifications.filter((notification) => !notification.isRead).length;
- const errorCount = state.notifications.filter((notification) => notification.kind === 'error').length;
- const label = unreadCount > 0 ? `${unreadCount} new` : `${state.notifications.length} total`;
+ 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 icon = errorCount > 0 ? TriangleAlertIcon : BellIcon;
if (region === 'bottom' && presentation !== 'expanded') {
@@ -32,17 +32,17 @@ export const NotificationsWidgetView = ({ presentation, region }: WidgetViewProp
};
const NotificationsPanel = () => {
- const { state } = useWorkbench();
+ const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);
return (
<Stack flex="1" gap="3" minH="0">
- {state.notifications.length === 0 ? (
+ {notifications.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs">
Successful operations, errors, and system messages appear here.
</Text>
) : (
<Stack gap="2">
- {state.notifications.map((notification) => {
+ {notifications.map((notification) => {
const IconComponent = kindIcon[notification.kind];
return (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 566b12cb2d..4803ef8091 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -14,7 +14,7 @@ import {
} from '../../gallery/api';
import { getGallerySettings } from '../../gallery/settings';
import type { GeneratedImageContract, WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../WorkbenchContext';
import { getGalleryCompareImage, getGalleryRecentImagesKey, getGalleryRefreshToken } from '../gallery/galleryStateView';
import { PreviewCompare } from './PreviewCompare';
@@ -93,8 +93,9 @@ const previewGridCss = {
} as const;
export const PreviewWidgetView = ({ region }: WidgetViewProps) => {
- const { activeProject, dispatch } = useWorkbench();
- const galleryValues = activeProject.widgetStates.gallery.values;
+ const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
+ const generateValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const dispatch = useWorkbenchDispatch();
const selectedImage = useMemo(() => getSelectedImage(galleryValues), [galleryValues]);
const compareImage = getGalleryCompareImage(galleryValues);
const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : null;
@@ -235,7 +236,7 @@ export const PreviewWidgetView = ({ region }: WidgetViewProps) => {
const imageActions = useImageActions({
boards,
dispatch,
- generateValues: activeProject.widgetStates.generate.values,
+ generateValues,
onImagesDeleted,
});
const contextMenuImage = useMemo<GalleryImage | null>(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
index f3d7d12b6b..7c4981dc7f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
@@ -10,7 +10,7 @@ import { useProjectSync } from '../../projects/syncStore';
import { useProjectActions } from '../../projects/useProjectActions';
import type { Project } from '../../types';
import { useNotify } from '../../useNotify';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProject, useWorkbenchDispatch, useWorkbenchSelector } from '../../WorkbenchContext';
/**
* The Project panel: rename the active project, see its sync/debug details,
@@ -19,7 +19,7 @@ import { useWorkbench } from '../../WorkbenchContext';
* any of its members.
*/
export const ProjectWidgetView = () => {
- const { activeProject } = useWorkbench();
+ const activeProject = useActiveProject();
return (
<Stack gap="5" p="3">
@@ -31,7 +31,7 @@ export const ProjectWidgetView = () => {
};
const NameSection = ({ project }: { project: Project }) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const commitName = (value: string) => {
const name = value.trim();
@@ -72,12 +72,13 @@ const formatTimestamp = (timestamp: string | undefined): string => {
};
const RecoverySection = ({ project }: { project: Project }) => {
- const { dispatch, state } = useWorkbench();
+ const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);
+ const dispatch = useWorkbenchDispatch();
const { deleteProject } = useProjectActions();
const [deleteTarget, setDeleteTarget] = useState<Project | null>(null);
const rootId = getRecoveryRootId(project);
- const original = project.recoveryOf ? state.projects.find((candidate) => candidate.id === project.recoveryOf) : null;
- const recoveries = state.projects.filter(
+ const original = project.recoveryOf ? projects.find((candidate) => candidate.id === project.recoveryOf) : null;
+ const recoveries = projects.filter(
(candidate) => candidate.id !== project.id && getRecoveryRootId(candidate) === rootId && candidate.recoveryOf
);
@@ -163,13 +164,14 @@ const RecoverySection = ({ project }: { project: Project }) => {
};
const DetailsSection = ({ project }: { project: Project }) => {
- const { state } = useWorkbench();
+ const backendConnectionStatus = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection.status);
+ const lastSavedAt = useWorkbenchSelector((snapshot) => snapshot.state.autosave.lastSavedAt);
const sync = useProjectSync();
const notify = useNotify();
const projectSync = sync.projects[project.id];
const syncLabel =
- state.backendConnection.status !== 'connected'
+ backendConnectionStatus !== 'connected'
? 'Offline — saved in this browser'
: projectSync === undefined || projectSync.isPendingPush
? 'Waiting to sync'
@@ -205,9 +207,7 @@ const DetailsSection = ({ project }: { project: Project }) => {
</HStack>
</DetailRow>
<DetailRow label="Sync">{syncLabel}</DetailRow>
- <DetailRow label="Last saved">
- {state.autosave.lastSavedAt ? formatTimestamp(state.autosave.lastSavedAt) : 'Not yet'}
- </DetailRow>
+ <DetailRow label="Last saved">{lastSavedAt ? formatTimestamp(lastSavedAt) : 'Not yet'}</DetailRow>
<DetailRow label="Graph nodes">{project.projectGraph.nodes.length}</DetailRow>
<DetailRow label="Queue items">{project.queue.items.length}</DetailRow>
<DetailRow label="Events">{project.events.length}</DetailRow>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
index dcefd6ca15..398c32c1b9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
@@ -5,14 +5,12 @@ import { useQueueItemProgress } from '../../backend/progressStore';
import { StatusWidgetChip } from '../../components/WidgetFrames';
import { Button } from '../../components/ui/Button';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch, useWorkbenchSelector } from '../../WorkbenchContext';
import { getDestinationLabel, getSourceLabel } from '../../invocation';
export const QueueWidgetView = ({ presentation, region }: WidgetViewProps) => {
- const { activeProject } = useWorkbench();
- const pendingQueueCount = activeProject.queue.items.filter(
- (item) => item.status === 'pending' || item.status === 'running'
- ).length;
+ const queueItems = useActiveProjectSelector((project) => project.queue.items);
+ const pendingQueueCount = queueItems.filter((item) => item.status === 'pending' || item.status === 'running').length;
if (region === 'bottom' && presentation !== 'expanded') {
return <StatusWidgetChip icon={ListOrderedIcon}>{pendingQueueCount} queued</StatusWidgetChip>;
@@ -54,8 +52,9 @@ const QueueItemLiveProgress = ({ queueItemId }: { queueItemId: string }) => {
};
const QueueContents = () => {
- const { dispatch, state } = useWorkbench();
- const queueRows = state.projects.flatMap((project) =>
+ const projects = useWorkbenchSelector((snapshot) => snapshot.state.projects);
+ const dispatch = useWorkbenchDispatch();
+ const queueRows = projects.flatMap((project) =>
project.queue.items.map((item) => ({ item, projectName: project.name }))
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx
index 33ba022e8f..f77a4165cc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/server-status/ServerStatusWidgetView.tsx
@@ -3,11 +3,10 @@ import { CircleXIcon, PlugZapIcon } from 'lucide-react';
import { StatusWidgetChip } from '../../components/WidgetFrames';
import type { WidgetViewProps } from '../../types';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useWorkbenchSelector } from '../../WorkbenchContext';
export const ServerStatusWidgetView = ({ presentation }: WidgetViewProps) => {
- const { state } = useWorkbench();
- const { backendConnection } = state;
+ const backendConnection = useWorkbenchSelector((snapshot) => snapshot.state.backendConnection);
const isConnected = backendConnection.status === 'connected';
const isDisconnected = backendConnection.status === 'disconnected';
const label = isConnected
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
index ba6106ede7..ec66fc33dd 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetChrome.tsx
@@ -5,7 +5,7 @@ import { useEffect, useId, useRef, type ChangeEvent } from 'react';
import { IconButton } from '../../components/ui/Button';
import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
import { useNotify } from '../../useNotify';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../WorkbenchContext';
import {
buildCurrentImageNode,
buildInvocationNode,
@@ -39,7 +39,8 @@ import {
*/
export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {
- const { activeProject, dispatch } = useWorkbench();
+ const workflowName = useActiveProjectSelector((project) => project.projectGraph.name);
+ const dispatch = useWorkbenchDispatch();
if (region !== 'center') {
return (
@@ -65,7 +66,7 @@ export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {
maxW="16rem"
placeholder="Untitled Workflow"
size="2xs"
- value={activeProject.projectGraph.name}
+ value={workflowName}
variant="flushed"
onChange={(event: ChangeEvent<HTMLInputElement>) =>
dispatch({
@@ -80,9 +81,9 @@ export const WorkflowWidgetLabel = ({ region }: WidgetLabelProps) => {
/** Entries contributed to the shared widget actions menu. */
export const WorkflowMenuItems = (_props: WidgetViewProps) => {
- const { activeProject, dispatch } = useWorkbench();
+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
+ const dispatch = useWorkbenchDispatch();
const notify = useNotify();
- const projectGraph = activeProject.projectGraph;
const openDetailsPanel = () => {
dispatch({ region: 'left', type: 'openRegionWidget', widgetId: 'workflow' });
@@ -124,12 +125,13 @@ export const WorkflowMenuItems = (_props: WidgetViewProps) => {
};
export const WorkflowHeaderActions = ({ region }: WidgetViewProps) => {
- const { activeProject, dispatch } = useWorkbench();
+ const graphHistory = useActiveProjectSelector((project) => project.graphHistory);
+ const dispatch = useWorkbenchDispatch();
const notify = useNotify();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const { dialogHostId, importRequestCount, isAddNodeOpen, isLibraryOpen, isNewWorkflowConfirmOpen } =
workflowUiStore.useSnapshot();
- const restorableHistory = activeProject.graphHistory.filter((entry) => entry.document);
+ const restorableHistory = graphHistory.filter((entry) => entry.document);
// Both workflow surfaces can be mounted at once; exactly one (the first to
// mount) hosts the shared dialogs and the import file input.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
index 5cba2f757a..74f11312b4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx
@@ -1,7 +1,7 @@
import { Box, HStack, Icon, Text } from '@chakra-ui/react';
import { WorkflowIcon } from 'lucide-react';
-import { useWorkbench } from '../../WorkbenchContext';
+import { useActiveProjectSelector } from '../../WorkbenchContext';
import type { WidgetViewProps } from '../../types';
import { WorkflowEditorView } from './editor/WorkflowEditorView';
import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';
@@ -15,8 +15,9 @@ import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';
*/
const WorkflowStatusBarItem = () => {
- const { activeProject } = useWorkbench();
- const isRunning = activeProject.queue.items.some(
+ 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')
);
@@ -24,7 +25,7 @@ const WorkflowStatusBarItem = () => {
<HStack gap="1" maxW="14rem" minW="0">
<Icon as={WorkflowIcon} boxSize="3" color={isRunning ? 'brand.solid' : undefined} flexShrink={0} />
<Text fontSize="2xs" minW="0" truncate>
- {activeProject.projectGraph.name || 'Untitled Workflow'}
+ {workflowName || 'Untitled Workflow'}
</Text>
{isRunning ? <Box bg="brand.solid" boxSize="1.5" flexShrink={0} rounded="full" /> : null}
</HStack>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
index 45589c1e26..980a3681cb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
@@ -3,7 +3,7 @@ import type { NodeProps } from '@xyflow/react';
import { memo } from 'react';
import { useProgressImage } from '../../../backend/progressImageStore';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector } from '../../../WorkbenchContext';
import type { GeneratedImageContract } from '../../../types';
import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';
@@ -20,10 +20,10 @@ const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract
};
const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImageFlowNodeType>) => {
- const { activeProject } = useWorkbench();
+ const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
const progressImage = useProgressImage();
const node = data.documentNode;
- const latestImage = getLatestImage(activeProject.widgetStates.gallery.values);
+ const latestImage = getLatestImage(galleryValues);
const src = progressImage?.dataUrl ?? latestImage?.imageUrl ?? null;
return (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
index 1d78ad034b..0d6e724b05 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx
@@ -23,7 +23,7 @@ import { FlowMiniMap } from '../../../components/FlowMiniMap';
import { flowThemeCss, getFlowColorMode } from '../../../components/flowTheme';
import { useNotify } from '../../../useNotify';
import { useWorkbenchPreferences } from '../../../settings/store';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../../WorkbenchContext';
import { getProjectGraphReadiness } from '../../../workflows/buildGraph';
import { createWorkflowId } from '../../../workflows/document';
import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSnapshot } from '../../../workflows/templates';
@@ -68,12 +68,12 @@ const isEditableTarget = (target: EventTarget | null): boolean =>
target instanceof HTMLElement && target.closest('input, textarea, select, [contenteditable="true"]') !== null;
const WorkflowFlow = () => {
- const { activeProject, dispatch } = useWorkbench();
+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
+ const dispatch = useWorkbenchDispatch();
const notify = useNotify();
const { themeId, workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =
useWorkbenchPreferences();
const templatesSnapshot = useInvocationTemplatesSnapshot();
- const projectGraph = activeProject.projectGraph;
const edgeType: FlowEdgeType = workflowEdgeStyle === 'straight' ? 'straight' : 'default';
const [flowNodes, setFlowNodes] = useState<WorkflowFlowNode[]>(() => toFlowNodes(projectGraph));
const [flowEdges, setFlowEdges] = useState<FlowEdge[]>(() => toFlowEdges(projectGraph, [], edgeType));
@@ -455,14 +455,14 @@ const WorkflowFlow = () => {
};
const ReadinessBanner = () => {
- const { activeProject } = useWorkbench();
+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
const templatesSnapshot = useInvocationTemplatesSnapshot();
const readiness = useMemo(
- () => getProjectGraphReadiness(activeProject.projectGraph, templatesSnapshot),
- [activeProject.projectGraph, templatesSnapshot]
+ () => getProjectGraphReadiness(projectGraph, templatesSnapshot),
+ [projectGraph, templatesSnapshot]
);
- if (readiness.canInvoke || activeProject.projectGraph.nodes.length === 0) {
+ if (readiness.canInvoke || projectGraph.nodes.length === 0) {
return null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
index 72c012d4ee..0907fc3334 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
@@ -7,7 +7,7 @@ import { SCHEDULER_OPTIONS } from '../../../generation/settings';
import { listGalleryBoards, type GalleryBoard } from '../../../gallery/api';
import type { ModelConfig, ModelTaxonomyType } from '../../../models/types';
import type { GeneratedImageContract } from '../../../types';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector } from '../../../WorkbenchContext';
import type { FieldInputTemplate } from '../../../workflows/types';
/**
@@ -214,16 +214,13 @@ const BoardInput = ({ onChange, template, value }: WorkflowFieldInputProps) => {
};
const ImageInput = ({ onChange, value }: WorkflowFieldInputProps) => {
- const { activeProject } = useWorkbench();
+ const gallerySelection = useActiveProjectSelector(
+ (project) => project.widgetStates.gallery.values.selectedImage as GeneratedImageContract | null | undefined
+ );
const imageName =
typeof (value as { image_name?: unknown } | null)?.image_name === 'string'
? (value as { image_name: string }).image_name
: null;
- const gallerySelection = activeProject.widgetStates.gallery.values.selectedImage as
- | GeneratedImageContract
- | null
- | undefined;
-
return (
<HStack gap="1.5" minW="0">
{imageName ? (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx
index 5f9c069619..7ab6d100ec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/library/WorkflowLibraryDialog.tsx
@@ -8,7 +8,7 @@ import { ConfirmDialog } from '../../../components/ui/ConfirmDialog';
import { JsonPreview } from '../../../components/ui/JsonPreview';
import { Scrollable } from '../../../components/ui/Scrollable';
import { useNotify } from '../../../useNotify';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../../WorkbenchContext';
import {
createLibraryWorkflow,
deleteLibraryWorkflow,
@@ -102,7 +102,8 @@ export const WorkflowLibraryDialog = ({
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
}) => {
- const { activeProject, dispatch } = useWorkbench();
+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
+ const dispatch = useWorkbenchDispatch();
const notify = useNotify();
const [category, setCategory] = useState<WorkflowLibraryCategory>('user');
const [searchTerm, setSearchTerm] = useState('');
@@ -117,7 +118,6 @@ export const WorkflowLibraryDialog = ({
const [isSaving, setIsSaving] = useState(false);
const hasAutoSwitchedRef = useRef(false);
const refreshTokenRef = useRef(0);
- const projectGraph = activeProject.projectGraph;
const refresh = useCallback(
(nextPage: number) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx
index 7850ac04a7..091d25a0cc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/FormBuilderTab.tsx
@@ -3,7 +3,7 @@ import { Columns2Icon, CrosshairIcon, GripVerticalIcon, InfoIcon, PlusIcon, Rows
import { createContext, use, useMemo, useState, type ChangeEvent, type DragEvent, type ReactNode } from 'react';
import { Button, IconButton } from '../../../components/ui/Button';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
import { getFormChildren } from '../../../workflows/document';
import type {
ContainerFormElement,
@@ -52,7 +52,7 @@ const BuilderCard = ({
parentId: string;
title: string;
}) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const { draggingElementId, setDraggingElementId } = use(BuilderDndContext);
const [isDragArmed, setIsDragArmed] = useState(false);
const [dropEdge, setDropEdge] = useState<DropEdge | null>(null);
@@ -166,7 +166,7 @@ const BuilderCard = ({
/** Drop zone covering a container's body, appending at the end. Doubles as the empty-container hint. */
const ContainerDropZone = ({ container, isEmpty }: { container: ContainerFormElement; isEmpty: boolean }) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const { draggingElementId } = use(BuilderDndContext);
const [isActive, setIsActive] = useState(false);
const canDrop = draggingElementId !== null && draggingElementId !== container.id;
@@ -255,7 +255,7 @@ const BuilderElement = ({
parentId: string;
projectGraph: ProjectGraphState;
}) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
switch (element.type) {
case 'container': {
@@ -402,7 +402,7 @@ const BuilderElement = ({
};
const AddElementMenu = () => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const add = (elementType: 'divider' | 'heading' | 'text' | 'container', layout?: 'row' | 'column') =>
dispatch({ action: { elementType, layout, type: 'addFormElement' }, type: 'applyProjectGraphAction' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx
index 72a00ecd02..f1a678b481 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/LinearFormView.tsx
@@ -1,7 +1,7 @@
import { Separator, Stack, Text } from '@chakra-ui/react';
import { Button } from '../../../components/ui/Button';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
import { getFormChildren } from '../../../workflows/document';
import type { ProjectGraphState, WorkflowFormElement } from '../../../workflows/types';
import { NodeFieldControl } from './NodeFieldControl';
@@ -41,7 +41,7 @@ const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement;
};
export const LinearFormView = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const rootChildren = getFormChildren(projectGraph.form);
if (rootChildren.length === 0) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx
index 90e1fee538..d1a64369aa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeFieldControl.tsx
@@ -4,7 +4,7 @@ import { useState, type ChangeEvent } from 'react';
import { FieldLabel } from '../../../components/ui/Field';
import { Tooltip } from '../../../components/ui/Tooltip';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
import type { NodeFieldFormElement, ProjectGraphState } from '../../../workflows/types';
import { isInvocationNode } from '../../../workflows/types';
@@ -40,7 +40,7 @@ export const NodeFieldControl = ({
isLabelEditable?: boolean;
projectGraph: ProjectGraphState;
}) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const { fieldName, instance, invocationNode, nodeContext, nodeId, template } = useNodeFieldBinding(
element,
projectGraph
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
index 43712f6bf1..ccaf222091 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
@@ -4,7 +4,7 @@ import type { ChangeEvent } from 'react';
import { JsonPreview } from '../../../components/ui/JsonPreview';
import { Scrollable } from '../../../components/ui/Scrollable';
import { Tabs } from '../../../components/ui/Tabs';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../../WorkbenchContext';
import { useInvocationTemplatesSnapshot } from '../../../workflows/templates';
import type {
InvocationTemplate,
@@ -41,7 +41,7 @@ const DetailRow = ({ label, value }: { label: string; value: string }) => (
const JsonBlock = ({ label, value }: { label: string; value: unknown }) => <JsonPreview label={label} value={value} />;
const DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template: InvocationTemplate | undefined }) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
return (
<Stack gap="2">
@@ -126,9 +126,10 @@ const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab })
};
export const NodeInspector = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
- const { activeProject, dispatch } = useWorkbench();
+ const workflowWidgetValues = useActiveProjectSelector((project) => project.widgetStates.workflow.values);
+ const dispatch = useWorkbenchDispatch();
const { selectedNodeIds } = workflowSelectionStore.useSnapshot();
- const tab = getInspectorTab(activeProject.widgetStates.workflow.values);
+ const tab = getInspectorTab(workflowWidgetValues);
const selectedNode = projectGraph.nodes.find((node) => node.id === selectedNodeIds[0]);
return (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx
index c1f4a81db5..6540718942 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowDetailsTab.tsx
@@ -2,12 +2,12 @@ import { HStack, Input, Stack, Textarea } from '@chakra-ui/react';
import type { ChangeEvent } from 'react';
import { Field } from '../../../components/ui/Field';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useWorkbenchDispatch } from '../../../WorkbenchContext';
import type { WorkflowMetadata } from '../../../workflows/types';
/** Workflow metadata editing — the legacy "Details" tab. */
export const WorkflowDetailsTab = ({ metadata }: { metadata: WorkflowMetadata }) => {
- const { dispatch } = useWorkbench();
+ const dispatch = useWorkbenchDispatch();
const commit = (patch: Partial<WorkflowMetadata>) =>
dispatch({ action: { patch, type: 'setMetadata' }, type: 'applyProjectGraphAction' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
index e2dd0b3a0c..bd47faedc2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
@@ -4,7 +4,7 @@ import { useEffect } from 'react';
import { Scrollable } from '../../../components/ui/Scrollable';
import { Tabs } from '../../../components/ui/Tabs';
-import { useWorkbench } from '../../../WorkbenchContext';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '../../../WorkbenchContext';
import { ensureInvocationTemplatesLoaded } from '../../../workflows/templates';
import { FormBuilderTab } from './FormBuilderTab';
import { LinearFormView } from './LinearFormView';
@@ -80,9 +80,9 @@ const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode:
};
export const WorkflowLinearPanel = () => {
- const { activeProject, dispatch } = useWorkbench();
- const projectGraph = activeProject.projectGraph;
- const widgetValues = activeProject.widgetStates.workflow.values;
+ const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
+ const widgetValues = useActiveProjectSelector((project) => project.widgetStates.workflow.values);
+ const dispatch = useWorkbenchDispatch();
const mode = getPanelMode(widgetValues);
const editTab = getEditTab(widgetValues);