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.

feat(webv2): add workbench widget runtime api

joshistoast1e4341a62b12
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index f72c3de4ff..04455f0098 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -19,6 +19,10 @@
},
"dependencies": {
"@chakra-ui/react": "^3.36.0",
+ "@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/modifiers": "^9.0.0",
+ "@dnd-kit/sortable": "^10.0.0",
+ "@dnd-kit/utilities": "^3.2.2",
"@emotion/react": "^11.14.0",
"@fontsource/inter": "^5.2.8",
"@tanstack/react-router": "^1.170.15",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index f3d47acb36..d17a912e0e 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -11,6 +11,18 @@ importers:
'@chakra-ui/react':
specifier: ^3.36.0
+ '@dnd-kit/core':
+ specifier: ^6.3.1
+ '@dnd-kit/modifiers':
+ specifier: ^9.0.0
+ '@dnd-kit/sortable':
+ specifier: ^10.0.0
+ '@dnd-kit/utilities':
+ specifier: ^3.2.2
+ version: 3.2.2([email protected])
'@emotion/react':
specifier: ^11.14.0
version: 11.14.0(@types/[email protected])([email protected])
@@ -165,6 +177,34 @@ packages:
react: '>=18'
react-dom: '>=18'
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
+ peerDependencies:
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}
+ peerDependencies:
+ react: '>=16.8.0'
+ react-dom: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==}
+ peerDependencies:
+ '@dnd-kit/core': ^6.3.0
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}
+ peerDependencies:
+ '@dnd-kit/core': ^6.3.0
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}
+ peerDependencies:
+ react: '>=16.8.0'
+
'@emnapi/[email protected]':
resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
@@ -1947,6 +1987,38 @@ snapshots:
react: 19.2.7
react-dom: 19.2.7([email protected])
+ dependencies:
+ react: 19.2.7
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/accessibility': 3.1.1([email protected])
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.7
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.7
+ tslib: 2.8.1
+
+ dependencies:
+ react: 19.2.7
+ tslib: 2.8.1
+
'@emnapi/[email protected]':
dependencies:
'@emnapi/wasi-threads': 1.2.1
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/EmptyState.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/EmptyState.tsx
new file mode 100644
index 0000000000..fb37633fbb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/ui/EmptyState.tsx
@@ -0,0 +1,30 @@
+import { EmptyState as ChakraEmptyState, VStack } from '@chakra-ui/react';
+import * as React from 'react';
+
+export interface EmptyStateProps extends ChakraEmptyState.RootProps {
+ title: string;
+ description?: string | null;
+ icon?: React.ReactNode;
+ danger?: boolean;
+}
+
+export const EmptyState = React.forwardRef<HTMLDivElement, EmptyStateProps>(function EmptyState(props, ref) {
+ const { title, description, icon, children, danger, ...rest } = props;
+ const fgColor = danger ? 'fg.error' : undefined;
+ return (
+ <ChakraEmptyState.Root ref={ref} {...rest} size={props.size ?? 'sm'}>
+ <ChakraEmptyState.Content>
+ {icon && <ChakraEmptyState.Indicator color={fgColor}>{icon}</ChakraEmptyState.Indicator>}
+ {description ? (
+ <VStack textAlign="center" color={fgColor}>
+ <ChakraEmptyState.Title>{title}</ChakraEmptyState.Title>
+ <ChakraEmptyState.Description>{description}</ChakraEmptyState.Description>
+ </VStack>
+ ) : (
+ <ChakraEmptyState.Title color={fgColor}>{title}</ChakraEmptyState.Title>
+ )}
+ {children}
+ </ChakraEmptyState.Content>
+ </ChakraEmptyState.Root>
+ );
+});
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx
index ac04a98065..5837dc1bdb 100644
--- a/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/ui/Toolbar.tsx
@@ -1,6 +1,9 @@
import type { ComponentProps } from 'react';
-import { Icon, Separator, Stack, type StackProps, IconButton } from '@chakra-ui/react';
+import { Icon, Separator, Stack, type StackProps } from '@chakra-ui/react';
+
+import { IconButton } from './Button';
+import { Tooltip } from './Tooltip';
/**
* The workbench's floating tool strip, shared by canvas-like surfaces (the
@@ -37,16 +40,18 @@ export const ToolbarButton = ({
isActive?: boolean;
label: string;
} & Omit<ComponentProps<typeof IconButton>, 'aria-label'>) => (
- <IconButton
- aria-label={label}
- aria-pressed={isActive}
- size="sm"
- title={label}
- variant={isActive ? 'solid' : 'ghost'}
- {...buttonProps}
- >
- <Icon as={icon} boxSize="3.5" />
- </IconButton>
+ <Tooltip content={label} positioning={{ placement: 'right-start' }}>
+ <IconButton
+ aria-label={label}
+ aria-pressed={isActive}
+ size="sm"
+ title={label}
+ variant={isActive ? 'solid' : 'ghost'}
+ {...buttonProps}
+ >
+ <Icon as={icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
);
export const ToolbarSeparator = ({ direction = 'column' }: { direction?: 'column' | 'row' }) => (
diff --git a/invokeai/frontend/webv2/src/workbench/extensions/README.md b/invokeai/frontend/webv2/src/workbench/extensions/README.md
new file mode 100644
index 0000000000..3864f04f13
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/extensions/README.md
@@ -0,0 +1,64 @@
+# Workbench Widget Extensions
+
+The workbench shell is now structured around widget types and widget instances.
+
+- A widget manifest registers a widget type.
+- A project layout stores widget instances in ordered region lists.
+- A widget instance owns persisted project state.
+- The shell owns placement, drag/drop, resizing, failure containment, and contribution APIs.
+
+## Manifest Shape
+
+Widgets should provide component icons, not icon IDs or import strings:
+
+```tsx
+import { LayersIcon } from 'lucide-react';
+
+export const manifest = {
+ id: 'invoke.layers',
+ version: 1,
+ label: 'Layers',
+ labelText: 'Layers',
+ icon: LayersIcon,
+ allowedRegions: ['right'],
+ allowMultiple: false,
+ state: {
+ version: 1,
+ persistence: 'project',
+ createInitial: () => ({}),
+ },
+ view: LayersWidgetView,
+};
+```
+
+Third-party widgets should ship icons as JSX/SVG components in their compiled widget bundle.
+
+## Discovery Options
+
+Custom nodes today are server-discovered. The backend scans `custom_nodes_path`, skips hidden/underscore directories, requires `__init__.py`, and imports each pack with Python `importlib`. The management API can clone a git repo into that directory, reload nodes, and list installed packs.
+
+Widgets should not mirror Python import execution directly in the browser. The safer server-first shape is:
+
+- Add a configured `widgets_path` beside `custom_nodes_path`.
+- Require each widget pack directory to include a manifest file, for example `invokeai-widget.json`.
+- Let the server list widget packs and expose static compiled assets from each pack.
+- The browser fetches a signed/validated widget catalog from the server.
+- The shell dynamically imports approved widget entrypoints by URL only after the server has validated the pack manifest.
+
+This avoids symlink assumptions and lets multi-user/admin rules follow the existing custom-node management pattern.
+
+## Missing Core Systems
+
+The extension API stubs exist in `extensionApi.ts`, but these systems still need real shell features:
+
+- Command registry UI and lifecycle ownership.
+- Command palette UI.
+- Hotkey manager with context-aware `when` clauses.
+- Global search UI and ranked result aggregation.
+- Menu contribution rendering beyond widget header menus.
+- Toolbar contribution rendering for locations like `center.tabs.trailing` and status bar slots.
+- Extension install/uninstall/reload API for widget packs.
+- Widget pack trust, signing, permission prompts, and admin policy.
+- Extension asset serving and cache invalidation.
+
+Undo/redo history controls were removed from normal widget registration because they render buttons and do not belong inside another button-like widget tab/slot. They should return as command and toolbar contributions when the command/toolbar systems exist.
diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts
new file mode 100644
index 0000000000..4c0975869a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts
@@ -0,0 +1,93 @@
+import type {
+ WidgetCommandApi,
+ WidgetCommandContribution,
+ WidgetCommandPaletteApi,
+ WidgetCommandPaletteContribution,
+ WidgetHotkeyApi,
+ WidgetHotkeyContribution,
+ WidgetMenuApi,
+ WidgetMenuContribution,
+ WidgetSearchApi,
+ WidgetSearchProvider,
+ WidgetToolbarApi,
+ WidgetToolbarContribution,
+} from '@workbench/types';
+
+const noopDispose = (): void => {};
+
+class ContributionStore<Contribution> {
+ private readonly contributions = new Map<string, Contribution>();
+
+ register(contribution: Contribution, fallbackId: string): () => void {
+ const id = fallbackId;
+
+ this.contributions.set(id, contribution);
+
+ return () => {
+ this.contributions.delete(id);
+ };
+ }
+
+ list(): Contribution[] {
+ return [...this.contributions.values()];
+ }
+}
+
+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>();
+
+export const commandApi: WidgetCommandApi = {
+ execute(commandId, ...args) {
+ const command = commandStore.list().find((candidate) => candidate.id === commandId);
+
+ return Promise.resolve(command ? command.handler(...args) : undefined);
+ },
+ register(command) {
+ return commandStore.register(command, command.id);
+ },
+};
+
+export const hotkeyApi: WidgetHotkeyApi = {
+ register(hotkey) {
+ return hotkeyStore.register(hotkey, `${hotkey.commandId}:${hotkey.keybinding}`);
+ },
+};
+
+export const menuApi: WidgetMenuApi = {
+ register(menu) {
+ return menuStore.register(menu, menu.id);
+ },
+};
+
+export const commandPaletteApi: WidgetCommandPaletteApi = {
+ register(entry) {
+ return paletteStore.register(entry, entry.commandId);
+ },
+};
+
+export const searchApi: WidgetSearchApi = {
+ registerProvider(provider) {
+ return searchStore.register(provider, provider.id);
+ },
+};
+
+export const toolbarApi: WidgetToolbarApi = {
+ register(toolbar) {
+ return toolbarStore.register(toolbar, toolbar.id);
+ },
+};
+
+export const extensionContributionStores = {
+ commands: commandStore,
+ hotkeys: hotkeyStore,
+ menus: menuStore,
+ palette: paletteStore,
+ search: searchStore,
+ toolbars: toolbarStore,
+};
+
+export const disposeExtensionContribution = noopDispose;
diff --git a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
index 4ff42946da..0704ee8a7f 100644
--- a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
+++ b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
@@ -1,60 +1,10 @@
import { Icon, type IconProps } from '@chakra-ui/react';
import { SquareIcon } from 'lucide-react';
-import { lazy, Suspense, type ComponentType } from 'react';
-import type { WidgetIconId } from './types';
+import type { WidgetIconComponent } from './types';
-type IconImporter = () => Promise<{ default: ComponentType }>;
+export const WidgetIcon = ({ icon, ...props }: IconProps & { icon?: WidgetIconComponent }) => {
+ const ResolvedIcon = icon ?? SquareIcon;
-const iconImporters = {
- 'lucide-react:box': () => import('lucide-react/dist/esm/icons/box.mjs'),
- 'lucide-react:bug': () => import('lucide-react/dist/esm/icons/bug.mjs'),
- 'lucide-react:cloud-check': () => import('lucide-react/dist/esm/icons/cloud-check.mjs'),
- 'lucide-react:bell': () => import('lucide-react/dist/esm/icons/bell.mjs'),
- 'lucide-react:eye': () => import('lucide-react/dist/esm/icons/eye.mjs'),
- 'lucide-react:folder-cog': () => import('lucide-react/dist/esm/icons/folder-cog.mjs'),
- 'lucide-react:image': () => import('lucide-react/dist/esm/icons/image.mjs'),
- 'lucide-react:info': () => import('lucide-react/dist/esm/icons/info.mjs'),
- 'lucide-react:layers': () => import('lucide-react/dist/esm/icons/layers.mjs'),
- 'lucide-react:list-ordered': () => import('lucide-react/dist/esm/icons/list-ordered.mjs'),
- 'lucide-react:panel-bottom': () => import('lucide-react/dist/esm/icons/panel-bottom.mjs'),
- 'lucide-react:plug-zap': () => import('lucide-react/dist/esm/icons/plug-zap.mjs'),
- 'lucide-react:sliders-horizontal': () => import('lucide-react/dist/esm/icons/sliders-horizontal.mjs'),
- 'lucide-react:undo-2': () => import('lucide-react/dist/esm/icons/undo-2.mjs'),
- 'lucide-react:users': () => import('lucide-react/dist/esm/icons/users.mjs'),
- 'lucide-react:wand-sparkles': () => import('lucide-react/dist/esm/icons/wand-sparkles.mjs'),
- 'lucide-react:workflow': () => import('lucide-react/dist/esm/icons/workflow.mjs'),
-} satisfies Partial<Record<WidgetIconId, IconImporter>>;
-
-const iconCache = new Map<WidgetIconId, ComponentType>();
-
-const getIconImporter = (iconId: WidgetIconId): IconImporter | undefined =>
- iconImporters[iconId as keyof typeof iconImporters];
-
-export const isSupportedIconId = (iconId: string): iconId is WidgetIconId => {
- return getIconImporter(iconId as WidgetIconId) !== undefined;
-};
-
-const resolveLazyIcon = (iconId: WidgetIconId): ComponentType => {
- const cachedIcon = iconCache.get(iconId);
-
- if (cachedIcon) {
- return cachedIcon;
- }
-
- const LazyIcon = lazy(getIconImporter(iconId) ?? (() => Promise.resolve({ default: SquareIcon })));
-
- iconCache.set(iconId, LazyIcon);
-
- return LazyIcon;
-};
-
-export const WidgetIcon = ({ iconId, ...props }: IconProps & { iconId: WidgetIconId }) => {
- const ResolvedIcon = resolveLazyIcon(iconId);
-
- return (
- <Suspense fallback={<Icon as={SquareIcon} {...props} />}>
- <Icon as={ResolvedIcon} {...props} />
- </Suspense>
- );
+ return <Icon as={ResolvedIcon} {...props} />;
};
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index 2e72fadb8d..a11ec33124 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -15,6 +15,7 @@ import {
isSupportedGenerateModel,
} from './generation/baseGenerationPolicies';
import { normalizeGenerateWidgetValues } from './generation/settings';
+import { getProjectWidgetValues } from './widgetState';
import { getProjectGraphReadiness } from './workflows/buildGraph';
import { getInvocationTemplatesSnapshot } from './workflows/templates';
@@ -79,10 +80,12 @@ const sourceWidgetIds: Partial<Record<InvocationSourceId, WidgetId>> = {
};
const isWidgetMounted = (project: Project, widgetId: WidgetId): boolean =>
- Object.values(project.widgetRegions).some((region) => region.enabledWidgetIds.includes(widgetId));
+ Object.values(project.widgetRegions).some((region) =>
+ region.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === widgetId)
+ );
const getGenerateSnapshotValidationReasons = (project: Project, models?: readonly ModelConfig[]): string[] => {
- const values = normalizeGenerateWidgetValues(project.widgetStates.generate.values);
+ const values = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));
if (!values || !isSupportedGenerateModel(values.model)) {
return ['Generate needs a supported model before it can be invoked.'];
diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx
index 1342fa6632..b72b0a2fc2 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectTabs.tsx
@@ -163,9 +163,9 @@ const ProjectTabContextMenu = ({
// to enabling it in the right rail. Both actions operate on the active
// project, which the switch above just made this one.
const { left, right } = project.widgetRegions;
- const region = right.enabledWidgetIds.includes('project')
+ const region = right.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === 'project')
? 'right'
- : left.enabledWidgetIds.includes('project')
+ : left.instanceIds.some((instanceId) => project.widgetInstances[instanceId]?.typeId === 'project')
? 'left'
: null;
const preferredRegions: WidgetRegion[] = [region ?? 'right'];
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
index 175b1cf71f..78e1905327 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
@@ -25,8 +25,8 @@ describe('project document serialization', () => {
layout: project.layout,
projectGraph: project.projectGraph,
widgetGraphs: {},
+ widgetInstances: project.widgetInstances,
widgetRegions: project.widgetRegions,
- widgetStates: project.widgetStates,
},
});
@@ -39,7 +39,7 @@ describe('project document serialization', () => {
expect(roundTripped).not.toBeNull();
expect(roundTripped?.undoRedo).toEqual({ future: [], past: [] });
expect(roundTripped?.id).toBe(project.id);
- expect(roundTripped?.widgetStates).toEqual(project.widgetStates);
+ expect(roundTripped?.widgetInstances).toEqual(project.widgetInstances);
});
it('rejects documents that do not look like projects', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts b/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
index 680639f1c7..19c28d55fe 100644
--- a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
@@ -39,6 +39,7 @@ const createQueueItem = ({
graph: { edges: [], id: 'graph-1', label: 'Graph', nodes: [], updatedAt: submittedAt, version: 1 },
sourceId,
submittedAt,
+ widgetInstances: {},
widgetStates: {
generate: { id: 'generate', label: 'Generate', values: { batchCount }, version: 1 },
} as unknown as QueueItem['snapshot']['widgetStates'],
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx
index f1aeedf549..f271c58138 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx
@@ -1,5 +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';
const getBatchCount = (values: Record<string, unknown>): number => {
@@ -9,7 +10,7 @@ const getBatchCount = (values: Record<string, unknown>): number => {
};
export const BatchCountField = () => {
- const generateValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));
const dispatch = useWorkbenchDispatch();
const batchCount = getBatchCount(generateValues);
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
index 226b842a9f..9303f7862c 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
@@ -12,6 +12,7 @@ import {
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 { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';
@@ -52,7 +53,7 @@ const InvokeTooltipContent = ({
isValid: boolean;
project: Project;
}) => {
- const batchCount = getBatchCount(project.widgetStates.generate.values);
+ const batchCount = getBatchCount(getProjectWidgetValues(project, 'generate'));
const destination = getDestinationLabel(project.invocation.destination);
const summary =
project.invocation.sourceId === 'generate'
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index 992386a83e..28aab4e921 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -1,4 +1,4 @@
-import type { ComponentType } from 'react';
+import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';
import type { ProjectGraphState } from './workflows/types';
@@ -8,7 +8,7 @@ export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow' | 'mode
export type GraphId = string;
-export type WidgetId =
+export type FirstPartyWidgetTypeId =
| 'autosave-status'
| 'canvas'
| 'diagnostics'
@@ -27,6 +27,10 @@ export type WidgetId =
| 'version-status'
| 'workflow';
+export type WidgetTypeId = FirstPartyWidgetTypeId | (string & {});
+export type WidgetInstanceId = string;
+export type WidgetId = WidgetTypeId;
+
export type WorkbenchRegion = 'left' | 'right' | 'center' | 'bottom' | 'dialog' | 'popover';
export type QueueItemStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
@@ -88,13 +92,23 @@ export interface BackendGraphContract {
}
export interface WidgetStateContract {
- id: WidgetId;
+ id: WidgetTypeId;
label: string;
version: 1;
values: Record<string, unknown>;
graphId?: GraphId;
}
+export type WidgetStateMap = Record<string, WidgetStateContract>;
+
+export interface WidgetInstanceContract {
+ id: WidgetInstanceId;
+ typeId: WidgetTypeId;
+ title?: string;
+ state: WidgetStateContract;
+ createdAt: string;
+}
+
export interface GraphBearingSurfaceContract {
surfaceId: string;
widgetId: WidgetId;
@@ -109,6 +123,8 @@ export interface GraphBearingSurfaceContract {
export interface WidgetViewProps {
region: WorkbenchRegion;
manifest: WidgetManifest;
+ instance: WidgetInstanceContract;
+ runtime: WidgetRuntimeApi;
presentation?: 'compact' | 'expanded' | 'tooltip';
}
@@ -125,18 +141,129 @@ export interface WidgetLabelProps {
export type WidgetLabel = string | ComponentType<WidgetLabelProps>;
-export type WidgetIconId = `lucide-react:${string}`;
+export type WidgetIconComponent =
+ | JSXElementConstructor<SVGProps<SVGSVGElement>>
+ | ExoticComponent<SVGProps<SVGSVGElement>>;
+
+export interface WidgetStateRegistration<State extends Record<string, unknown> = Record<string, unknown>> {
+ version: 1;
+ createInitial: () => State;
+ migrate?: (state: unknown, fromVersion: number) => State;
+ persistence?: 'project' | 'workspace' | 'session' | 'none';
+}
+
+export interface WidgetRuntimeApi<State extends Record<string, unknown> = Record<string, unknown>> {
+ instanceId: WidgetInstanceId;
+ typeId: WidgetTypeId;
+ region: WorkbenchRegion;
+ state: State;
+ patchState: (values: Partial<State>) => void;
+ setState: (values: State) => void;
+ commands: WidgetCommandApi;
+ hotkeys: WidgetHotkeyApi;
+ menus: WidgetMenuApi;
+ palette: WidgetCommandPaletteApi;
+ search: WidgetSearchApi;
+ toolbars: WidgetToolbarApi;
+ workbench: WidgetWorkbenchApi;
+}
+
+export interface WidgetCommandApi {
+ execute: (commandId: string, ...args: unknown[]) => Promise<unknown>;
+ register: (command: WidgetCommandContribution) => () => void;
+}
+
+export interface WidgetCommandContribution {
+ id: string;
+ title: string;
+ handler: (...args: unknown[]) => unknown | Promise<unknown>;
+}
+
+export interface WidgetHotkeyApi {
+ register: (hotkey: WidgetHotkeyContribution) => () => void;
+}
+
+export interface WidgetHotkeyContribution {
+ commandId: string;
+ keybinding: string;
+ when?: string;
+}
+
+export interface WidgetMenuApi {
+ register: (menu: WidgetMenuContribution) => () => void;
+}
+
+export interface WidgetMenuContribution {
+ id: string;
+ items: Array<{ commandId: string; group?: string }>;
+}
+
+export interface WidgetCommandPaletteApi {
+ register: (entry: WidgetCommandPaletteContribution) => () => void;
+}
+
+export interface WidgetCommandPaletteContribution {
+ commandId: string;
+ title: string;
+ keywords?: string[];
+}
+
+export interface WidgetSearchApi {
+ registerProvider: (provider: WidgetSearchProvider) => () => void;
+}
+
+export interface WidgetSearchProvider {
+ id: string;
+ label: string;
+ search: (query: string) => Promise<WidgetSearchResult[]> | WidgetSearchResult[];
+}
+
+export interface WidgetSearchResult {
+ id: string;
+ title: string;
+ subtitle?: string;
+ commandId?: string;
+}
+
+export interface WidgetToolbarApi {
+ register: (toolbar: WidgetToolbarContribution) => () => void;
+}
+
+export interface WidgetToolbarContribution {
+ id: string;
+ location: 'center.tabs.trailing' | 'status.left' | 'status.right';
+ items: Array<{ commandId: string; icon?: WidgetIconComponent; label?: string }>;
+}
+
+export interface OpenWorkbenchWidgetOptions {
+ createNew?: boolean;
+ preferredRegions?: ReadonlyArray<WidgetRegion>;
+ requireCenterView?: boolean;
+}
+
+export type WidgetWorkbenchApiResult =
+ | { ok: true; region?: WidgetRegion }
+ | { ok: false; reason: 'unavailable' | 'unsupported' | 'not-found' };
+
+export interface WidgetWorkbenchApi {
+ openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) => WidgetWorkbenchApiResult;
+ revealWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;
+ closeWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;
+}
/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */
export type SettingsSectionId = 'appearance' | 'behavior' | 'project' | 'workflow' | 'developer' | 'workspace';
export interface WidgetManifest {
- id: WidgetId;
+ /** Widget runtime API contract version. Defaults to 1 during registry normalization. */
+ apiVersion?: 1;
+ id: WidgetTypeId;
label: WidgetLabel;
labelText: string;
version: 1;
- regions: WorkbenchRegion[];
- icon: WidgetIconId;
+ allowedRegions: WidgetRegion[];
+ allowMultiple: boolean;
+ icon: WidgetIconComponent;
bottomPanel?: 'expandable' | 'tooltip';
centerPlacement?: 'toolbar' | 'view';
/** Only offered while an admin is signed in to a multi-user backend. */
@@ -156,6 +283,7 @@ export interface WidgetManifest {
/** When set, the frame header shows a gear that opens this settings dialog section. */
settingsSection?: SettingsSectionId;
footer?: WidgetFooter;
+ state?: WidgetStateRegistration;
graphBearing?: {
sourceId: InvocationSourceId;
defaultGraphId: GraphId;
@@ -167,14 +295,19 @@ export interface WidgetManifest {
};
}
+export interface NormalizedWidgetManifest extends Omit<WidgetManifest, 'apiVersion' | 'state'> {
+ apiVersion: 1;
+ state: WidgetStateRegistration;
+}
+
export interface RegisteredWidget {
- manifest: WidgetManifest;
+ manifest: NormalizedWidgetManifest;
status: 'enabled' | 'disabled' | 'hidden';
failure?: WidgetFailure;
}
export interface WidgetFailure {
- widgetId: WidgetId;
+ widgetId: WidgetTypeId;
message: string;
details: string;
occurredAt: string;
@@ -275,8 +408,8 @@ export interface PanelState {
export type WidgetRegion = 'left' | 'right' | 'bottom' | 'center';
export interface WidgetRegionState {
- activeWidgetId: WidgetId;
- enabledWidgetIds: WidgetId[];
+ activeInstanceId: WidgetInstanceId;
+ instanceIds: WidgetInstanceId[];
isCollapsed: boolean;
sizePx: number;
}
@@ -302,9 +435,9 @@ export interface Project {
invocation: InvocationControllerState;
/** The one active project graph: an editable workflow document, compiled to a `GraphContract` at invoke time. */
projectGraph: ProjectGraphState;
- widgetStates: Record<WidgetId, WidgetStateContract>;
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
widgetRegions: Record<WidgetRegion, WidgetRegionState>;
- widgetGraphs: Partial<Record<WidgetId, GraphContract>>;
+ widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;
canvas: CanvasStateContract;
graphHistory: GraphHistorySnapshot[];
undoRedo: UndoRedoHistory;
@@ -377,9 +510,9 @@ export interface ProjectUndoSnapshot {
layout: ProjectLayoutState;
invocation: InvocationControllerState;
projectGraph: ProjectGraphState;
- widgetStates: Record<WidgetId, WidgetStateContract>;
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
widgetRegions: Record<WidgetRegion, WidgetRegionState>;
- widgetGraphs: Partial<Record<WidgetId, GraphContract>>;
+ widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;
canvas: CanvasStateContract;
}
@@ -392,7 +525,8 @@ export interface QueueSubmissionSnapshot {
sourceId: InvocationSourceId;
destination: ResultDestination;
graph: GraphContract;
- widgetStates: Record<WidgetId, WidgetStateContract>;
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
+ widgetStates: WidgetStateMap;
canvas: CanvasStateContract;
submittedAt: string;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
index 49efd782a8..41a73f70a8 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx
@@ -2,7 +2,9 @@ import type {
GraphBearingSurfaceContract,
GraphContract,
Project,
+ WidgetInstanceContract,
WidgetManifest,
+ WidgetRuntimeApi,
WorkbenchRegion,
} from '@workbench/types';
@@ -81,7 +83,17 @@ const GraphSurfaceMenuItems = ({
);
};
-export const WidgetActionsMenu = ({ manifest, region }: { manifest: WidgetManifest; region: WorkbenchRegion }) => {
+export const WidgetActionsMenu = ({
+ instance,
+ manifest,
+ region,
+ runtime,
+}: {
+ instance: WidgetInstanceContract;
+ manifest: WidgetManifest;
+ region: WorkbenchRegion;
+ runtime: WidgetRuntimeApi;
+}) => {
const activeProject = useActiveProject();
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const surface = manifest.graphBearing?.surfaces.includes(region) ? createGraphBearingSurface(manifest, region) : null;
@@ -112,7 +124,9 @@ export const WidgetActionsMenu = ({ manifest, region }: { manifest: WidgetManife
<Menu.Content minW="13rem">
{surface ? <GraphSurfaceMenuItems surface={surface} onPreview={() => setIsPreviewOpen(true)} /> : null}
{surface && HeaderMenu ? <Menu.Separator borderColor="border.subtle" /> : null}
- {HeaderMenu ? <HeaderMenu manifest={manifest} region={region} /> : null}
+ {HeaderMenu ? (
+ <HeaderMenu instance={instance} manifest={manifest} region={region} runtime={runtime} />
+ ) : null}
</Menu.Content>
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx
index fa233b9920..d5e6c9b588 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx
@@ -6,18 +6,31 @@ import { Component, type ErrorInfo, type ReactNode } from 'react';
interface WidgetFailureBoundaryProps {
widgetId: WidgetId;
+ resetKey: string;
children: ReactNode;
}
interface WidgetFailureBoundaryState {
error?: Error;
details?: string;
+ resetKey: string;
}
export class WidgetFailureBoundary extends Component<WidgetFailureBoundaryProps, WidgetFailureBoundaryState> {
- state: WidgetFailureBoundaryState = {};
+ state: WidgetFailureBoundaryState = { resetKey: this.props.resetKey };
- static getDerivedStateFromError(error: Error): WidgetFailureBoundaryState {
+ static getDerivedStateFromProps(
+ props: WidgetFailureBoundaryProps,
+ state: WidgetFailureBoundaryState
+ ): Partial<WidgetFailureBoundaryState> | null {
+ if (props.resetKey !== state.resetKey) {
+ return { details: undefined, error: undefined, resetKey: props.resetKey };
+ }
+
+ return null;
+ }
+
+ static getDerivedStateFromError(error: Error): Partial<WidgetFailureBoundaryState> {
return { error };
}
@@ -56,14 +69,24 @@ export class WidgetFailureBoundary extends Component<WidgetFailureBoundaryProps,
</ScrollArea.Scrollbar>
<ScrollArea.Corner />
</ScrollArea.Root>
- <Button
- alignSelf="start"
- size="2xs"
- variant="outline"
- onClick={() => void navigator.clipboard?.writeText(copyableDetails)}
- >
- Copy Error
- </Button>
+ <Stack direction="row" gap="2">
+ <Button
+ alignSelf="start"
+ size="2xs"
+ variant="outline"
+ onClick={() => this.setState({ details: undefined, error: undefined, resetKey: this.props.resetKey })}
+ >
+ Retry
+ </Button>
+ <Button
+ alignSelf="start"
+ size="2xs"
+ variant="outline"
+ onClick={() => void navigator.clipboard?.writeText(copyableDetails)}
+ >
+ Copy Error
+ </Button>
+ </Stack>
</Stack>
);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
index 02f03dadbf..462b8a9fd5 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
@@ -1,4 +1,10 @@
-import type { WidgetManifest, WidgetRegion, WorkbenchRegion } from '@workbench/types';
+import type {
+ WidgetInstanceContract,
+ WidgetManifest,
+ WidgetRegion,
+ WidgetRuntimeApi,
+ WorkbenchRegion,
+} from '@workbench/types';
import { Box, Flex, HStack, Icon, Stack, Text, type RecipeVariantProps, useRecipe } from '@chakra-ui/react';
import { chipRecipe } from '@theme/recipes';
@@ -152,12 +158,16 @@ export const WidgetPanelFrame = ({
export const WidgetHeader = ({
actions,
+ instance,
manifest,
region,
+ runtime,
}: {
actions?: ReactNode;
+ instance: WidgetInstanceContract;
manifest: WidgetManifest;
region: WorkbenchRegion;
+ runtime: WidgetRuntimeApi;
}) => {
// Manifests may provide a component label (e.g. Workflow's editable
// `Workflow / [name]`); plain strings render as the standard title.
@@ -188,7 +198,7 @@ export const WidgetHeader = ({
<Icon as={SettingsIcon} boxSize="3.5" />
</IconButton>
) : null}
- <WidgetActionsMenu manifest={manifest} region={region} />
+ <WidgetActionsMenu instance={instance} manifest={manifest} region={region} runtime={runtime} />
</HStack>
</HStack>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
index 6719cc8ae6..6be0bdc3e5 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
@@ -1,76 +1,129 @@
-import type { RegisteredWidget, WidgetViewProps } from '@workbench/types';
+import type { RegisteredWidget, WidgetInstanceContract, 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 { useWidgetRuntime } from './createWidgetRuntime';
import { WidgetFailureBoundary } from './WidgetFailureBoundary';
import { WidgetHeader, WidgetPanelFrame } from './WidgetFrames';
-interface WidgetRendererProps extends Omit<WidgetViewProps, 'manifest'> {
+interface WidgetRendererProps extends Omit<WidgetViewProps, 'manifest' | 'runtime'> {
+ instance: WidgetInstanceContract;
widget: RegisteredWidget;
}
-export const WidgetRenderer = ({ presentation, region, widget }: WidgetRendererProps) => {
+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 });
if (!View) {
return null;
}
- const content = <View manifest={widget.manifest} presentation={presentation} region={region} />;
- const framedContent = (
- <WidgetShellFrame content={content} presentation={presentation} region={region} widget={widget} />
+ const content = (
+ <View
+ instance={instance}
+ manifest={widget.manifest}
+ presentation={presentation}
+ region={region}
+ runtime={runtime}
+ />
);
- if (!widget.manifest.failurePolicy.isolateRenderFailure) {
- return framedContent;
- }
-
- return <WidgetFailureBoundary widgetId={widget.manifest.id}>{framedContent}</WidgetFailureBoundary>;
+ return (
+ <WidgetShellFrame
+ content={content}
+ instance={instance}
+ presentation={presentation}
+ region={region}
+ runtime={runtime}
+ widget={widget}
+ />
+ );
};
const WidgetShellFrame = ({
content,
+ instance,
presentation,
region,
+ runtime,
widget,
}: {
content: React.ReactNode;
+ instance: WidgetInstanceContract;
presentation: WidgetViewProps['presentation'];
region: WidgetViewProps['region'];
+ runtime: WidgetRuntimeApi;
widget: RegisteredWidget;
}) => {
+ const safeContent = (
+ <RenderFailureSlot instance={instance} widget={widget}>
+ {content}
+ </RenderFailureSlot>
+ );
+
if (region === 'popover' || region === 'dialog' || presentation === 'compact' || presentation === 'tooltip') {
- return content;
+ return safeContent;
}
if (region === 'left' || region === 'right' || region === 'bottom') {
return (
<WidgetPanelFrame region={region}>
- <HeaderSlot presentation={presentation} region={region} widget={widget} />
- <PanelBodySlot>{content}</PanelBodySlot>
- <FooterSlot presentation={presentation} region={region} widget={widget} />
+ <HeaderSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />
+ <PanelBodySlot>{safeContent}</PanelBodySlot>
+ <FooterSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />
</WidgetPanelFrame>
);
}
return (
<Flex bg="bg.inset" direction="column" h="full" minH="0" w="full">
- <HeaderSlot presentation={presentation} region={region} widget={widget} />
+ <HeaderSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />
<Box flex="1" minH="0" overflow="hidden" position="relative">
- {content}
+ {safeContent}
</Box>
- <FooterSlot presentation={presentation} region={region} widget={widget} />
+ <FooterSlot instance={instance} presentation={presentation} region={region} runtime={runtime} widget={widget} />
</Flex>
);
};
+const RenderFailureSlot = ({
+ children,
+ instance,
+ widget,
+}: {
+ children: React.ReactNode;
+ instance: WidgetInstanceContract;
+ widget: RegisteredWidget;
+}) => {
+ if (!widget.manifest.failurePolicy.isolateRenderFailure) {
+ return children;
+ }
+
+ return (
+ <WidgetFailureBoundary resetKey={instance.id} widgetId={widget.manifest.id}>
+ {children}
+ </WidgetFailureBoundary>
+ );
+};
+
const HeaderSlot = ({
+ instance,
presentation,
region,
+ runtime,
widget,
}: {
+ instance: WidgetInstanceContract;
presentation: WidgetViewProps['presentation'];
region: WidgetViewProps['region'];
+ runtime: WidgetRuntimeApi;
widget: RegisteredWidget;
}) => {
if (widget.manifest.chrome?.header === 'hidden') {
@@ -79,13 +132,25 @@ const HeaderSlot = ({
const HeaderActions = widget.manifest.headerActions;
const actions = HeaderActions ? (
- <HeaderActions manifest={widget.manifest} presentation={presentation} region={region} />
+ <HeaderActions
+ instance={instance}
+ manifest={widget.manifest}
+ presentation={presentation}
+ region={region}
+ runtime={runtime}
+ />
) : null;
const bg = region === 'center' ? 'bg' : 'bg.subtle';
return (
<Box bg={bg} flexShrink={0}>
- <WidgetHeader actions={actions} manifest={widget.manifest} region={region} />
+ <WidgetHeader
+ actions={actions}
+ instance={instance}
+ manifest={widget.manifest}
+ region={region}
+ runtime={runtime}
+ />
</Box>
);
};
@@ -97,12 +162,16 @@ const PanelBodySlot = ({ children }: { children: React.ReactNode }) => (
);
const FooterSlot = ({
+ instance,
presentation,
region,
+ runtime,
widget,
}: {
+ instance: WidgetInstanceContract;
presentation: WidgetViewProps['presentation'];
region: WidgetViewProps['region'];
+ runtime: WidgetRuntimeApi;
widget: RegisteredWidget;
}) => {
const Footer = widget.manifest.footer;
@@ -114,7 +183,13 @@ const FooterSlot = ({
return (
<Box bg={bg} flexShrink={0}>
- <Footer manifest={widget.manifest} presentation={presentation} region={region} />
+ <Footer
+ instance={instance}
+ manifest={widget.manifest}
+ presentation={presentation}
+ region={region}
+ runtime={runtime}
+ />
</Box>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
new file mode 100644
index 0000000000..61abcd2fe6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
@@ -0,0 +1,189 @@
+import type {
+ Project,
+ NormalizedWidgetManifest,
+ RegisteredWidget,
+ WidgetInstanceContract,
+ WidgetRegion,
+ WidgetTypeId,
+} from '@workbench/types';
+import type { WorkbenchAction } from '@workbench/workbenchState';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { createWidgetRuntime } from './createWidgetRuntime';
+
+const TestIcon = () => null;
+const TestView = () => null;
+
+const createWidget = (
+ overrides: Partial<NormalizedWidgetManifest> & Pick<NormalizedWidgetManifest, 'id' | 'labelText'>
+): RegisteredWidget => ({
+ manifest: {
+ apiVersion: 1,
+ allowMultiple: false,
+ allowedRegions: ['left', 'right', 'center', 'bottom'],
+ bottomPanel: 'expandable',
+ centerPlacement: 'view',
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ icon: TestIcon,
+ label: overrides.labelText,
+ state: { createInitial: () => ({}), persistence: 'project', version: 1 },
+ version: 1,
+ view: TestView,
+ ...overrides,
+ },
+ status: 'enabled',
+});
+
+const createInstance = (id = 'alpha', typeId: WidgetTypeId = 'alpha'): WidgetInstanceContract => ({
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id,
+ state: { id: typeId, label: typeId, values: { current: true }, version: 1 },
+ typeId,
+});
+
+const createDispatch = () => {
+ const actions: WorkbenchAction[] = [];
+ const dispatch = (action: WorkbenchAction): void => {
+ actions.push(action);
+ };
+
+ return { actions, dispatch };
+};
+
+const createRegistry =
+ (widgetsByRegion: Partial<Record<WidgetRegion, RegisteredWidget[]>>) =>
+ (region: WidgetRegion): RegisteredWidget[] =>
+ widgetsByRegion[region] ?? [];
+
+const createPlacementProject = (
+ overrides: Partial<Pick<Project, 'widgetInstances' | 'widgetRegions'>> = {}
+): Pick<Project, 'widgetInstances' | 'widgetRegions'> => ({
+ widgetInstances: {
+ alpha: createInstance('alpha'),
+ beta: createInstance('beta', 'beta'),
+ ...overrides.widgetInstances,
+ },
+ widgetRegions: {
+ bottom: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ center: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ left: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ right: { activeInstanceId: 'alpha', instanceIds: ['alpha'], isCollapsed: false, sizePx: 240 },
+ ...overrides.widgetRegions,
+ },
+});
+
+describe('createWidgetRuntime', () => {
+ it('dispatches patchState and setState to the current widget instance', () => {
+ const { actions, dispatch } = createDispatch();
+ const runtime = createWidgetRuntime({
+ dispatch,
+ getWidgetById: () => undefined,
+ getWidgetsForRegion: createRegistry({}),
+ instance: createInstance(),
+ project: createPlacementProject(),
+ region: 'right',
+ });
+
+ runtime.patchState({ next: true });
+ runtime.setState({ replaced: true });
+
+ expect(actions).toEqual([
+ { instanceId: 'alpha', type: 'patchWidgetInstanceValues', values: { next: true } },
+ { instanceId: 'alpha', type: 'setWidgetInstanceValues', values: { replaced: true } },
+ ]);
+ });
+
+ it('opens widgets through canonical validation and seeded initial values', () => {
+ const { actions, dispatch } = createDispatch();
+ const createInitial = vi.fn(() => ({ seeded: true }));
+ const runtime = createWidgetRuntime({
+ dispatch,
+ getWidgetById: () => undefined,
+ getWidgetsForRegion: createRegistry({
+ bottom: [createWidget({ bottomPanel: 'tooltip', id: 'tooltip-widget', labelText: 'Tooltip Widget' })],
+ center: [createWidget({ centerPlacement: 'toolbar', id: 'toolbar-widget', labelText: 'Toolbar Widget' })],
+ right: [
+ createWidget({
+ id: 'panel-widget',
+ labelText: 'Panel Widget',
+ state: { createInitial, persistence: 'project', version: 1 },
+ }),
+ ],
+ }),
+ instance: createInstance(),
+ project: createPlacementProject(),
+ region: 'right',
+ });
+
+ expect(runtime.workbench.openWidget('panel-widget', { preferredRegions: ['right'] })).toEqual({
+ ok: true,
+ region: 'right',
+ });
+ expect(runtime.workbench.openWidget('tooltip-widget', { preferredRegions: ['bottom'] })).toEqual({
+ ok: false,
+ reason: 'unavailable',
+ });
+ expect(runtime.workbench.openWidget('toolbar-widget', { preferredRegions: ['center'] })).toEqual({
+ ok: false,
+ reason: 'unavailable',
+ });
+ expect(runtime.workbench.openWidget('missing-widget', { preferredRegions: ['right'] })).toEqual({
+ ok: false,
+ reason: 'unavailable',
+ });
+
+ expect(createInitial).toHaveBeenCalledTimes(1);
+ expect(actions).toEqual([
+ {
+ createNew: undefined,
+ initialValues: { seeded: true },
+ region: 'right',
+ type: 'openRegionWidget',
+ widgetId: 'panel-widget',
+ },
+ ]);
+ });
+
+ it('dispatches own-region close and reveal actions', () => {
+ const { actions, dispatch } = createDispatch();
+ const runtime = createWidgetRuntime({
+ dispatch,
+ getWidgetById: (typeId) => createWidget({ id: typeId, labelText: typeId }),
+ getWidgetsForRegion: createRegistry({}),
+ instance: createInstance(),
+ project: createPlacementProject({
+ widgetRegions: {
+ bottom: { activeInstanceId: 'alpha', instanceIds: ['alpha', 'beta'], isCollapsed: false, sizePx: 240 },
+ center: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ left: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ right: { activeInstanceId: 'alpha', instanceIds: [], isCollapsed: false, sizePx: 240 },
+ },
+ }),
+ region: 'bottom',
+ });
+
+ 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' },
+ ]);
+ });
+
+ it('returns unsupported for cross-region close and reveal', () => {
+ const { actions, dispatch } = createDispatch();
+ const runtime = createWidgetRuntime({
+ dispatch,
+ getWidgetById: () => undefined,
+ getWidgetsForRegion: createRegistry({}),
+ instance: createInstance(),
+ project: createPlacementProject(),
+ region: 'right',
+ });
+
+ expect(runtime.workbench.revealWidgetInstance('beta')).toEqual({ ok: false, reason: 'unsupported' });
+ expect(runtime.workbench.closeWidgetInstance('beta')).toEqual({ ok: false, reason: 'unsupported' });
+ expect(actions).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts
new file mode 100644
index 0000000000..ba0d55b2b8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.ts
@@ -0,0 +1,93 @@
+import type {
+ OpenWorkbenchWidgetOptions,
+ RegisteredWidget,
+ WidgetInstanceContract,
+ WidgetRegion,
+ WidgetRuntimeApi,
+ WidgetTypeId,
+ WorkbenchRegion,
+} from '@workbench/types';
+import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';
+import type { WorkbenchAction } from '@workbench/workbenchState';
+
+import {
+ commandApi,
+ commandPaletteApi,
+ hotkeyApi,
+ menuApi,
+ searchApi,
+ toolbarApi,
+} from '@workbench/extensions/extensionApi';
+import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';
+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);
+
+export const createWidgetRuntime = ({
+ dispatch,
+ getWidgetsForRegion,
+ getWidgetById,
+ instance,
+ project,
+ region,
+}: {
+ dispatch: Dispatch<WorkbenchAction>;
+ getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;
+ getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];
+ instance: WidgetInstanceContract;
+ project: WidgetPlacementProject;
+ region: WorkbenchRegion;
+}): WidgetRuntimeApi => ({
+ commands: commandApi,
+ hotkeys: hotkeyApi,
+ instanceId: instance.id,
+ menus: menuApi,
+ 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,
+ toolbars: toolbarApi,
+ typeId: instance.typeId,
+ workbench: {
+ closeWidgetInstance: (instanceId) => {
+ if (!isWidgetRegion(region)) {
+ return { ok: false, reason: 'unsupported' };
+ }
+
+ return closeWidgetPlacement({ dispatch, getWidgetById, instanceId, project, region });
+ },
+ openWidget: (typeId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions) =>
+ openWidgetPlacement({ dispatch, getWidgetsForRegion, options, typeId }),
+ revealWidgetInstance: (instanceId) => {
+ if (!isWidgetRegion(region)) {
+ return { ok: false, reason: 'unsupported' };
+ }
+
+ return revealWidgetPlacement({ dispatch, instanceId, project, region });
+ },
+ },
+});
+
+export const useWidgetRuntime = ({
+ dispatch,
+ getWidgetsForRegion,
+ getWidgetById,
+ instance,
+ project,
+ region,
+}: {
+ dispatch: Dispatch<WorkbenchAction>;
+ getWidgetById: (typeId: WidgetTypeId) => RegisteredWidget | undefined;
+ getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[];
+ instance: WidgetInstanceContract;
+ project: WidgetPlacementProject;
+ region: WorkbenchRegion;
+}): WidgetRuntimeApi =>
+ useMemo(
+ () => createWidgetRuntime({ dispatch, getWidgetById, getWidgetsForRegion, instance, project, region }),
+ [dispatch, getWidgetById, getWidgetsForRegion, instance, project, region]
+ );
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts
index 234fd98b17..1f0ae44298 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/index.ts
@@ -1,5 +1,10 @@
export { WidgetActionsMenu } from './WidgetActionsMenu';
export { WidgetBar, type WidgetBarItem } from './WidgetBar';
+export { WidgetEnableMenu, type WidgetEnableMenuItem } from './WidgetEnableMenu';
export { WidgetFailureBoundary } from './WidgetFailureBoundary';
export { FieldPlaceholder, StatusWidgetChip, WidgetHeader, WidgetPanelFrame } from './WidgetFrames';
+export { WidgetInstanceContextMenu, type WidgetInstanceContextMenuTarget } from './WidgetInstanceContextMenu';
+export { WidgetRegionDropOverlay } from './WidgetRegionDropOverlay';
+export { WidgetStrip } from './WidgetStrip';
export { MissingWidgetFrame, WidgetRenderer } from './WidgetRenderer';
+export { useWidgetSortable } from './useWidgetSortable';
diff --git a/invokeai/frontend/webv2/src/workbench/widgetState.ts b/invokeai/frontend/webv2/src/workbench/widgetState.ts
new file mode 100644
index 0000000000..63c14a7ef6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgetState.ts
@@ -0,0 +1,21 @@
+import type { Project, WidgetInstanceContract, WidgetStateContract, WidgetTypeId } from './types';
+
+const emptyWidgetState = (widgetId: WidgetTypeId): WidgetStateContract => ({
+ id: widgetId,
+ label: widgetId,
+ values: {},
+ version: 1,
+});
+
+export const getProjectWidgetInstance = (
+ project: Project,
+ widgetId: WidgetTypeId
+): WidgetInstanceContract | undefined =>
+ project.widgetInstances[widgetId] ??
+ Object.values(project.widgetInstances).find((instance) => instance.typeId === widgetId);
+
+export const getProjectWidgetState = (project: Project, widgetId: WidgetTypeId): WidgetStateContract =>
+ getProjectWidgetInstance(project, widgetId)?.state ?? emptyWidgetState(widgetId);
+
+export const getProjectWidgetValues = (project: Project, widgetId: WidgetTypeId): Record<string, unknown> =>
+ getProjectWidgetState(project, widgetId).values;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts
index 4c1b553e6d..d35f288a8f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { CloudCheckIcon } from 'lucide-react';
+
import { AutosaveStatusWidgetView } from './AutosaveStatusWidgetView';
export const autosaveStatusWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
bottomPanel: 'tooltip',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:cloud-check',
+ icon: CloudCheckIcon,
id: 'autosave-status',
label: 'Autosave',
labelText: 'Autosave',
- regions: ['bottom'],
version: 1,
view: AutosaveStatusWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts
index b1e1bf2860..2303b39442 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { WandSparklesIcon } from 'lucide-react';
+
import { CanvasWidgetView } from './CanvasWidgetView';
export const canvasWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['center'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
graphBearing: { defaultGraphId: 'canvas-graph', sourceId: 'canvas-fill', surfaces: ['center'] },
- icon: 'lucide-react:wand-sparkles',
+ icon: WandSparklesIcon,
id: 'canvas',
label: 'Canvas',
labelText: 'Canvas',
- regions: ['center'],
version: 1,
view: CanvasWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
index 9bb08c8250..8adddb7bcb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/DiagnosticsWidgetView.tsx
@@ -24,7 +24,7 @@ const DiagnosticsPanel = () => {
const errorLog = useWorkbenchSelector((snapshot) => snapshot.state.errorLog);
return (
- <Stack gap="3">
+ <Stack gap="3" p="2">
{errorLog.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs">
Shell errors and debugging details will appear here without covering the workbench.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts
index fbbc08b886..3250a2dcb3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/index.ts
@@ -1,17 +1,20 @@
import type { WidgetManifest } from '@workbench/types';
+import { BugIcon } from 'lucide-react';
+
import { DiagnosticsHeaderActions } from './DiagnosticsHeaderActions';
import { DiagnosticsWidgetView } from './DiagnosticsWidgetView';
export const diagnosticsWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom', 'right'],
bottomPanel: 'expandable',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: DiagnosticsHeaderActions,
- icon: 'lucide-react:bug',
+ icon: BugIcon,
id: 'diagnostics',
label: 'Diagnostics',
labelText: 'Diagnostics',
- regions: ['bottom', 'right'],
version: 1,
view: DiagnosticsWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
index 7a16d890a5..5ad148b818 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetFooter.tsx
@@ -3,6 +3,7 @@ import type { WidgetViewProps } from '@workbench/types';
import { ButtonGroup, HStack, Pagination } from '@chakra-ui/react';
import { IconButton } from '@workbench/components/ui';
import { getGallerySettings } from '@workbench/gallery/settings';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
@@ -15,7 +16,7 @@ import { GALLERY_PAGE_SIZE } from './useGalleryData';
* decoupled from the view's data fetching.
*/
export const GalleryWidgetFooter = (_props: WidgetViewProps) => {
- const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
const dispatch = useWorkbenchDispatch();
const settings = getGallerySettings(galleryValues);
const page = getGalleryPage(galleryValues);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
index aa4eea48c3..412ce23466 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx
@@ -3,6 +3,7 @@ import type { WidgetViewProps } from '@workbench/types';
import { getGallerySettings } 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 { ImageIcon } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef } from 'react';
@@ -27,7 +28,7 @@ import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';
export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) => {
const activeProject = useActiveProject();
const dispatch = useWorkbenchDispatch();
- const galleryValues = activeProject.widgetStates.gallery.values;
+ const galleryValues = getProjectWidgetValues(activeProject, 'gallery');
const galleryView = getGalleryView(galleryValues);
const searchTerm = getGallerySearchTerm(galleryValues);
const recentImagesKey = getGalleryRecentImagesKey(galleryValues);
@@ -104,7 +105,7 @@ export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) =>
const imageActions = useImageActions({
boards: data.boards,
dispatch,
- generateValues: activeProject.widgetStates.generate.values,
+ generateValues: getProjectWidgetValues(activeProject, 'generate'),
onImagesDeleted,
onStarredChange,
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts
index 13ec1bd86e..6ba9e5d985 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/index.ts
@@ -1,18 +1,21 @@
import type { WidgetManifest } from '@workbench/types';
+import { ImageIcon } from 'lucide-react';
+
import { GalleryWidgetFooter } from './GalleryWidgetFooter';
import { GalleryWidgetView } from './GalleryWidgetView';
export const galleryWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['left', 'right', 'center', 'bottom'],
bottomPanel: 'expandable',
chrome: { header: 'hidden' },
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
footer: GalleryWidgetFooter,
- icon: 'lucide-react:image',
+ icon: ImageIcon,
id: 'gallery',
label: 'Gallery',
labelText: 'Gallery',
- regions: ['left', 'right', 'center', 'bottom'],
version: 1,
view: GalleryWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
index f5b9eeeba3..39cecbfc2c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
@@ -18,6 +18,7 @@ import {
syncGenerateWidgetValuesWithModels,
} from '@workbench/generation/settings';
import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { useEffect, useMemo } from 'react';
@@ -38,7 +39,7 @@ const getSettingsWithAutoComponentSource = (
};
export const GenerateWidgetView = () => {
- const storedValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const storedValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));
const dispatch = useWorkbenchDispatch();
const { error, models, status } = useModelsSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts
index 07a622a017..af729ce668 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { SlidersHorizontalIcon } from 'lucide-react';
+
import { GenerateWidgetView } from './GenerateWidgetView';
export const generateWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['left'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
graphBearing: { defaultGraphId: 'generate-graph', sourceId: 'generate', surfaces: ['left'] },
- icon: 'lucide-react:sliders-horizontal',
+ icon: SlidersHorizontalIcon,
id: 'generate',
label: 'Generate',
labelText: 'Generate',
- regions: ['left'],
version: 1,
view: GenerateWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/history-controls/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/history-controls/index.ts
index 4f069177ba..4cdf228129 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/history-controls/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/history-controls/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { Undo2Icon } from 'lucide-react';
+
import { HistoryControlsWidgetView } from './HistoryControlsWidgetView';
export const historyControlsWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
centerPlacement: 'toolbar',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:undo-2',
+ icon: Undo2Icon,
id: 'history-controls',
label: 'History Controls',
labelText: 'History Controls',
- regions: ['bottom', 'center'],
version: 1,
view: HistoryControlsWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts
index e13c1303e0..fdc074379e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/index.ts
@@ -1,16 +1,19 @@
import type { WidgetManifest } from '@workbench/types';
+import { LayersIcon } from 'lucide-react';
+
import { LayersHeaderActions } from './LayersHeaderActions';
import { LayersWidgetView } from './LayersWidgetView';
export const layersWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['right'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: LayersHeaderActions,
- icon: 'lucide-react:layers',
+ icon: LayersIcon,
id: 'layers',
label: 'Layers',
labelText: 'Layers',
- regions: ['right'],
version: 1,
view: LayersWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/index.ts
index bfc723af1e..74680d0d41 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layout-actions/index.ts
@@ -1,16 +1,19 @@
import type { WidgetManifest } from '@workbench/types';
+import { PanelBottomIcon } from 'lucide-react';
+
import { LayoutActionsWidgetView } from './LayoutActionsWidgetView';
import { LayoutHeaderActions } from './LayoutHeaderActions';
export const layoutActionsWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: LayoutHeaderActions,
- icon: 'lucide-react:panel-bottom',
+ icon: PanelBottomIcon,
id: 'layout-actions',
label: 'Layout Actions',
labelText: 'Layout Actions',
- regions: ['bottom'],
version: 1,
view: LayoutActionsWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx
index 800ca3b13c..88d50eaa3e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx
@@ -2,7 +2,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 { Row } from '@workbench/components/ui';
+import { Button, Row } from '@workbench/components/ui';
+import { EmptyState } from '@workbench/components/ui/EmptyState';
import { getModelImageUrl } from '@workbench/models/api';
import {
filterModels,
@@ -12,8 +13,8 @@ import {
} from '@workbench/models/library';
import { useModelsSnapshot } from '@workbench/models/modelsStore';
import { formatBytes } from '@workbench/models/taxonomy';
-import { getLibraryScrollOffset, saveLibraryScrollOffset } from '@workbench/models/uiStore';
-import { BoxIcon } from 'lucide-react';
+import { getLibraryScrollOffset, openModelsCenterTab, saveLibraryScrollOffset } from '@workbench/models/uiStore';
+import { ArrowRightIcon, BoxIcon, CircleAlert } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ModelBadgeRow } from './ModelBadges';
@@ -51,6 +52,9 @@ export const ModelLibraryList = ({
const { coverImageVersions, error, missingModelKeys, models, status } = useModelsSnapshot();
const scrollRef = useRef<HTMLDivElement | null>(null);
const [contextMenuTarget, setContextMenuTarget] = useState<ModelContextMenuTarget | null>(null);
+ const openAddModels = () => {
+ openModelsCenterTab('add');
+ };
const rows = useMemo(
() => flattenGroupsToRows(groupModelsByType(filterModels(models, filters, missingModelKeys))),
@@ -102,28 +106,23 @@ export const ModelLibraryList = ({
}
if (status === 'error') {
- return (
- <Stack align="center" gap="1" py="8">
- <Text color="fg.error" fontSize="xs" fontWeight="600">
- Could not load models
- </Text>
- <Text color="fg.subtle" fontSize="2xs" maxW="20rem" textAlign="center">
- {error}
- </Text>
- </Stack>
- );
+ return <EmptyState title="Could not load models" description={error} icon={<Icon as={CircleAlert} />} danger />;
}
if (rows.length === 0) {
return (
- <Stack align="center" gap="1" py="8">
- <Text color="fg.muted" fontSize="xs" fontWeight="600">
- {models.length === 0 ? 'No models installed' : 'No models match your filters'}
- </Text>
- <Text color="fg.subtle" fontSize="2xs">
- {models.length === 0 ? 'Use Add Models to install your first model.' : 'Try clearing the search or filters.'}
- </Text>
- </Stack>
+ <EmptyState
+ title={models.length === 0 ? 'No models installed' : 'No models match your filters'}
+ description={
+ models.length === 0 ? 'Use Add Models to install your first model.' : 'Try clearing the search or filters.'
+ }
+ icon={<Icon as={CircleAlert} />}
+ >
+ <Button onClick={openAddModels} size="sm">
+ Add Models
+ <Icon as={ArrowRightIcon} />
+ </Button>
+ </EmptyState>
);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts
index 2185eafe56..442475d70c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts
@@ -1,16 +1,19 @@
import type { WidgetManifest } from '@workbench/types';
+import { BoxIcon } from 'lucide-react';
+
import { MaintenanceMenu } from './MaintenanceMenu';
import { ModelsWidgetView } from './ModelsWidgetView';
export const modelsWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['left', 'right', 'center'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: MaintenanceMenu,
- icon: 'lucide-react:box',
+ icon: BoxIcon,
id: 'models',
label: 'Models',
labelText: 'Models',
- regions: ['left', 'right', 'center'],
version: 1,
view: ModelsWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
index a604258014..4feb343b0f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx
@@ -35,7 +35,7 @@ const NotificationsPanel = () => {
const notifications = useWorkbenchSelector((snapshot) => snapshot.state.notifications);
return (
- <Stack flex="1" gap="3" minH="0">
+ <Stack flex="1" gap="3" minH="0" p="2">
{notifications.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs">
Successful operations, errors, and system messages appear here.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts
index 29e4d9f527..459ce2b110 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/index.ts
@@ -1,17 +1,20 @@
import type { WidgetManifest } from '@workbench/types';
+import { BellIcon } from 'lucide-react';
+
import { NotificationsHeaderActions } from './NotificationsHeaderActions';
import { NotificationsWidgetView } from './NotificationsWidgetView';
export const notificationsWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
bottomPanel: 'expandable',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: NotificationsHeaderActions,
- icon: 'lucide-react:bell',
+ icon: BellIcon,
id: 'notifications',
label: 'Notifications',
labelText: 'Notifications',
- regions: ['bottom'],
version: 1,
view: NotificationsWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 02eae1def8..49417eb56f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -17,6 +17,7 @@ import {
getGalleryImagesRefreshToken,
getGalleryRecentImagesKey,
} from '@workbench/widgets/gallery/galleryStateView';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -96,8 +97,8 @@ const previewGridCss = {
} as const;
export const PreviewWidgetView = ({ region }: WidgetViewProps) => {
- const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
- const generateValues = useActiveProjectSelector((project) => project.widgetStates.generate.values);
+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
+ const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));
const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector(
(project) => project.settings
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts
index c78ebbb0f0..bcacfd5804 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/index.ts
@@ -1,16 +1,19 @@
import type { WidgetManifest } from '@workbench/types';
+import { EyeIcon } from 'lucide-react';
+
import { PreviewHeaderActions } from './PreviewHeaderActions';
import { PreviewWidgetView } from './PreviewWidgetView';
export const previewWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['center', 'right'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
headerActions: PreviewHeaderActions,
- icon: 'lucide-react:eye',
+ icon: EyeIcon,
id: 'preview',
label: 'Preview',
labelText: 'Preview',
- regions: ['center', 'right'],
version: 1,
view: PreviewWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts
index 7a74ec96af..a9cda6a300 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/index.ts
@@ -1,14 +1,17 @@
import type { WidgetManifest } from '@workbench/types';
+import { FolderCogIcon } from 'lucide-react';
+
import { ProjectWidgetView } from './ProjectWidgetView';
export const projectWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['left', 'right'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:folder-cog',
+ icon: FolderCogIcon,
id: 'project',
label: 'Project',
labelText: 'Project',
- regions: ['left', 'right'],
version: 1,
view: ProjectWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
index b1f16eed67..148bb0ec2f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/QueueWidgetView.tsx
@@ -59,7 +59,7 @@ const QueueContents = () => {
);
return (
- <Stack gap="2">
+ <Stack gap="2" p="2">
{queueRows.length === 0 ? (
<Text color="fg.subtle" fontSize="2xs">
Queue submissions will appear here.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
index 2cbd145327..f1bf31d0e6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/index.ts
@@ -1,14 +1,17 @@
import type { WidgetManifest } from '@workbench/types';
+import { ListOrderedIcon } from 'lucide-react';
+
import { QueueWidgetView } from './QueueWidgetView';
export const queueWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['right', 'bottom'],
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:list-ordered',
+ icon: ListOrderedIcon,
id: 'queue',
label: 'Queue',
labelText: 'Queue',
- regions: ['right', 'bottom'],
version: 1,
view: QueueWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts
index a976d47511..424dc9773a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/server-status/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { PlugZapIcon } from 'lucide-react';
+
import { ServerStatusWidgetView } from './ServerStatusWidgetView';
export const serverStatusWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
bottomPanel: 'tooltip',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:plug-zap',
+ icon: PlugZapIcon,
id: 'server-status',
label: 'Server Status',
labelText: 'Server Status',
- regions: ['bottom'],
version: 1,
view: ServerStatusWidgetView,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts
index 32d57c7ac7..874c48a1ba 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/version-status/index.ts
@@ -1,15 +1,18 @@
import type { WidgetManifest } from '@workbench/types';
+import { InfoIcon } from 'lucide-react';
+
import { VersionStatusWidgetView } from './VersionStatusWidgetView';
export const versionStatusWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['bottom'],
bottomPanel: 'tooltip',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
- icon: 'lucide-react:info',
+ icon: InfoIcon,
id: 'version-status',
label: 'Version',
labelText: 'Version',
- regions: ['bottom'],
version: 1,
view: VersionStatusWidgetView,
};
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 d21055a300..5fc3fdd4cd 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/CurrentImageFlowNode.tsx
@@ -3,6 +3,7 @@ import type { NodeProps } from '@xyflow/react';
import { Box, Flex, Image, Text } from '@chakra-ui/react';
import { useProgressImage } from '@workbench/backend/progressImageStore';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { memo } from 'react';
@@ -21,7 +22,7 @@ const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract
};
const CurrentImageFlowNodeComponent = ({ data, selected }: NodeProps<CurrentImageFlowNodeType>) => {
- const galleryValues = useActiveProjectSelector((project) => project.widgetStates.gallery.values);
+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
const progressImage = useProgressImage();
const node = data.documentNode;
const latestImage = getLatestImage(galleryValues);
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 13e9689814..bb5ae682f6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/fields/WorkflowFieldInput.tsx
@@ -7,6 +7,7 @@ import { Button } from '@workbench/components/ui';
import { listGalleryBoards, type GalleryBoard } from '@workbench/gallery/api';
import { SCHEDULER_OPTIONS } from '@workbench/generation/baseGenerationPolicies';
import { ModelSelect } from '@workbench/models/components';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useEffect, useState, type ChangeEvent } from 'react';
@@ -267,7 +268,7 @@ const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInp
const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
const gallerySelection = useActiveProjectSelector(
- (project) => project.widgetStates.gallery.values.selectedImage as GeneratedImageContract | null | undefined
+ (project) => getProjectWidgetValues(project, 'gallery').selectedImage as GeneratedImageContract | null | undefined
);
const imageName =
typeof (value as { image_name?: unknown } | null)?.image_name === 'string'
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
index bbbe0c74cd..b8f7de6d4a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/index.ts
@@ -1,9 +1,13 @@
import type { WidgetManifest } from '@workbench/types';
+import { WorkflowIcon } from 'lucide-react';
+
import { WorkflowHeaderActions, WorkflowMenuItems, WorkflowWidgetLabel } from './WorkflowWidgetChrome';
import { WorkflowWidgetView } from './WorkflowWidgetView';
export const workflowWidgetManifest: WidgetManifest = {
+ allowMultiple: false,
+ allowedRegions: ['center', 'left', 'bottom'],
bottomPanel: 'expandable',
failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
graphBearing: {
@@ -13,11 +17,10 @@ export const workflowWidgetManifest: WidgetManifest = {
},
headerActions: WorkflowHeaderActions,
headerMenu: WorkflowMenuItems,
- icon: 'lucide-react:workflow',
+ icon: WorkflowIcon,
id: 'workflow',
label: WorkflowWidgetLabel,
labelText: 'Workflow',
- regions: ['center', 'left', 'bottom'],
settingsSection: 'workflow',
version: 1,
view: WorkflowWidgetView,
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 58928e2e0d..b2c0803dcb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/NodeInspector.tsx
@@ -9,6 +9,7 @@ import type { ChangeEvent } from 'react';
import { Flex, HStack, Stack, Text, Textarea } from '@chakra-ui/react';
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';
@@ -127,7 +128,7 @@ const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab })
};
export const NodeInspector = ({ projectGraph }: { projectGraph: ProjectGraphState }) => {
- const workflowWidgetValues = useActiveProjectSelector((project) => project.widgetStates.workflow.values);
+ const workflowWidgetValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'workflow'));
const dispatch = useWorkbenchDispatch();
const { selectedNodeIds } = workflowSelectionStore.useSnapshot();
const tab = getInspectorTab(workflowWidgetValues);
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 72ef43b848..8c503c480c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/linear/WorkflowLinearPanel.tsx
@@ -1,5 +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 { ensureInvocationTemplatesLoaded } from '@workbench/workflows/templates';
import { EyeIcon, PencilIcon } from 'lucide-react';
@@ -80,7 +81,7 @@ const PanelModeToggle = ({ mode, onChange }: { mode: PanelMode; onChange: (mode:
export const WorkflowLinearPanel = () => {
const projectGraph = useActiveProjectSelector((project) => project.projectGraph);
- const widgetValues = useActiveProjectSelector((project) => project.widgetStates.workflow.values);
+ const widgetValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'workflow'));
const dispatch = useWorkbenchDispatch();
const mode = getPanelMode(widgetValues);
const editTab = getEditTab(widgetValues);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 93623c510d..616ad0683f 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -4,6 +4,7 @@ import type { GenerateWidgetValues, MainModelConfig } from './generation/types';
import type { GeneratedImageContract, Project, WorkbenchState } from './types';
import { DEFAULT_PROJECT_SETTINGS } from './settings/store';
+import { getProjectWidgetValues } from './widgetState';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';
const model: MainModelConfig = {
@@ -76,7 +77,7 @@ describe('workbench widget region defaults', () => {
it('enables Diagnostics in the right side panel rail', () => {
const state = createInitialWorkbenchState();
- expect(getActiveProject(state).widgetRegions.right.enabledWidgetIds).toContain('diagnostics');
+ expect(getActiveProject(state).widgetRegions.right.instanceIds).toContain('diagnostics');
});
it('hydrates the old default right rail with Diagnostics while preserving customized rails', () => {
@@ -87,7 +88,7 @@ describe('workbench widget region defaults', () => {
...project,
widgetRegions: {
...project.widgetRegions,
- right: { ...project.widgetRegions.right, enabledWidgetIds: ['queue', 'gallery', 'layers'] },
+ right: { ...project.widgetRegions.right, instanceIds: ['queue', 'gallery', 'layers'] },
},
})),
} satisfies WorkbenchState;
@@ -97,7 +98,7 @@ describe('workbench widget region defaults', () => {
...project,
widgetRegions: {
...project.widgetRegions,
- right: { ...project.widgetRegions.right, enabledWidgetIds: ['gallery', 'layers'] },
+ right: { ...project.widgetRegions.right, instanceIds: ['gallery', 'layers'] },
},
})),
} satisfies WorkbenchState;
@@ -105,7 +106,7 @@ describe('workbench widget region defaults', () => {
const hydratedLegacyDefault = workbenchReducer(initial, { state: legacyDefault, type: 'hydrateWorkbench' });
const hydratedCustomized = workbenchReducer(initial, { state: customized, type: 'hydrateWorkbench' });
- expect(getActiveProject(hydratedLegacyDefault).widgetRegions.right.enabledWidgetIds).toEqual([
+ expect(getActiveProject(hydratedLegacyDefault).widgetRegions.right.instanceIds).toEqual([
'queue',
'gallery',
'layers',
@@ -113,7 +114,7 @@ describe('workbench widget region defaults', () => {
'diagnostics',
'project',
]);
- expect(getActiveProject(hydratedCustomized).widgetRegions.right.enabledWidgetIds).toEqual(['gallery', 'layers']);
+ expect(getActiveProject(hydratedCustomized).widgetRegions.right.instanceIds).toEqual(['gallery', 'layers']);
});
});
@@ -121,7 +122,7 @@ describe('workbench widget region opening', () => {
it('enables and selects a center widget without toggling it back off', () => {
let state = createInitialWorkbenchState();
const activeProject = getActiveProject(state);
- const enabledWidgetIds: Project['widgetRegions']['center']['enabledWidgetIds'] = ['canvas'];
+ const instanceIds: Project['widgetRegions']['center']['instanceIds'] = ['canvas'];
state = {
...state,
@@ -133,8 +134,8 @@ describe('workbench widget region opening', () => {
...project.widgetRegions,
center: {
...project.widgetRegions.center,
- activeWidgetId: 'canvas',
- enabledWidgetIds,
+ activeInstanceId: 'canvas',
+ instanceIds,
},
},
}
@@ -144,20 +145,20 @@ describe('workbench widget region opening', () => {
state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'models' });
- expect(getActiveProject(state).widgetRegions.center.activeWidgetId).toBe('models');
- expect(getActiveProject(state).widgetRegions.center.enabledWidgetIds).toEqual(['canvas', 'models']);
+ expect(getActiveProject(state).widgetRegions.center.activeInstanceId).toBe('models');
+ expect(getActiveProject(state).widgetRegions.center.instanceIds).toEqual(['canvas', 'models']);
state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'models' });
- expect(getActiveProject(state).widgetRegions.center.activeWidgetId).toBe('models');
- expect(getActiveProject(state).widgetRegions.center.enabledWidgetIds).toEqual(['canvas', 'models']);
+ expect(getActiveProject(state).widgetRegions.center.activeInstanceId).toBe('models');
+ expect(getActiveProject(state).widgetRegions.center.instanceIds).toEqual(['canvas', 'models']);
expect(getActiveProject(state).widgetRegions.center.isCollapsed).toBe(false);
});
it('opens and uncollapses the target panel region', () => {
let state = createInitialWorkbenchState();
const activeProject = getActiveProject(state);
- const enabledWidgetIds: Project['widgetRegions']['bottom']['enabledWidgetIds'] = ['diagnostics'];
+ const instanceIds: Project['widgetRegions']['bottom']['instanceIds'] = ['diagnostics'];
state = {
...state,
@@ -173,8 +174,8 @@ describe('workbench widget region opening', () => {
...project.widgetRegions,
bottom: {
...project.widgetRegions.bottom,
- activeWidgetId: 'diagnostics',
- enabledWidgetIds,
+ activeInstanceId: 'diagnostics',
+ instanceIds,
isCollapsed: true,
},
},
@@ -186,8 +187,8 @@ describe('workbench widget region opening', () => {
state = workbenchReducer(state, { region: 'bottom', type: 'openRegionWidget', widgetId: 'queue' });
expect(getActiveProject(state).layout.panels.isBottomOpen).toBe(true);
- expect(getActiveProject(state).widgetRegions.bottom.activeWidgetId).toBe('queue');
- expect(getActiveProject(state).widgetRegions.bottom.enabledWidgetIds).toEqual(['diagnostics', 'queue']);
+ expect(getActiveProject(state).widgetRegions.bottom.activeInstanceId).toBe('queue');
+ expect(getActiveProject(state).widgetRegions.bottom.instanceIds).toEqual(['diagnostics', 'queue']);
expect(getActiveProject(state).widgetRegions.bottom.isCollapsed).toBe(false);
});
});
@@ -805,15 +806,12 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
const updatedProject = getActiveProject(state);
+ const galleryValues = getProjectWidgetValues(updatedProject, 'gallery');
expect(updatedProject.canvas.stagingArea.pendingImages).toEqual([]);
- expect(updatedProject.widgetStates.gallery.values.recentImages).toEqual([
- createImage('gallery-image.png', queueItem.id),
- ]);
- expect(updatedProject.widgetStates.gallery.values.selectedImage).toEqual(
- createImage('gallery-image.png', queueItem.id)
- );
- expect(updatedProject.widgetStates.gallery.values.selectedImageName).toBe('gallery-image.png');
+ expect(galleryValues.recentImages).toEqual([createImage('gallery-image.png', queueItem.id)]);
+ expect(galleryValues.selectedImage).toEqual(createImage('gallery-image.png', queueItem.id));
+ expect(galleryValues.selectedImageName).toBe('gallery-image.png');
});
it('appends Gallery destination results for local fallback while backend owns boards', () => {
@@ -841,7 +839,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
type: 'routeQueueItemResults',
});
- const values = getActiveProject(state).widgetStates.gallery.values;
+ const values = getProjectWidgetValues(getActiveProject(state), 'gallery');
expect((values.recentImages as GeneratedImageContract[]).map((image) => image.imageName)).toEqual([
'gallery-image-2.png',
@@ -868,7 +866,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
});
const updatedQueueItem = getActiveProject(state).queue.items[0];
- const galleryValues = getActiveProject(state).widgetStates.gallery.values;
+ const galleryValues = getProjectWidgetValues(getActiveProject(state), 'gallery');
expect(updatedQueueItem.status).toBe('pending');
expect(updatedQueueItem.completedBackendItemIds).toEqual([11]);
@@ -897,8 +895,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, { image, type: 'selectGalleryImage' });
- expect(getActiveProject(state).widgetStates.gallery.values.selectedImageName).toBe('backend-selected.png');
- expect(getActiveProject(state).widgetStates.gallery.values.selectedImage).toEqual(image);
+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('backend-selected.png');
+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toEqual(image);
});
});
@@ -972,27 +970,31 @@ describe('workbench backend connection recovery', () => {
it('refreshes every project gallery when backend data may have changed', () => {
const initial = createInitialWorkbenchState();
- const previousTokens = initial.projects.map((project) => project.widgetStates.gallery.values.galleryRefreshToken);
+ const previousTokens = initial.projects.map(
+ (project) => getProjectWidgetValues(project, 'gallery').galleryRefreshToken
+ );
const previousImageTokens = initial.projects.map(
- (project) => project.widgetStates.gallery.values.galleryImagesRefreshToken
+ (project) => getProjectWidgetValues(project, 'gallery').galleryImagesRefreshToken
);
const state = workbenchReducer(initial, { type: 'refreshBackendData' });
expect(state.projects).toHaveLength(initial.projects.length);
for (const [index, project] of state.projects.entries()) {
- expect(project.widgetStates.gallery.values.galleryRefreshToken).toBeDefined();
- expect(project.widgetStates.gallery.values.galleryRefreshToken).not.toBe(previousTokens[index]);
- expect(project.widgetStates.gallery.values.galleryImagesRefreshToken).toBeDefined();
- expect(project.widgetStates.gallery.values.galleryImagesRefreshToken).not.toBe(previousImageTokens[index]);
+ const galleryValues = getProjectWidgetValues(project, 'gallery');
+
+ expect(galleryValues.galleryRefreshToken).toBeDefined();
+ expect(galleryValues.galleryRefreshToken).not.toBe(previousTokens[index]);
+ expect(galleryValues.galleryImagesRefreshToken).toBeDefined();
+ expect(galleryValues.galleryImagesRefreshToken).not.toBe(previousImageTokens[index]);
}
});
it('can refresh gallery images without invalidating board data', () => {
const initial = createInitialWorkbenchState();
const state = workbenchReducer(initial, { type: 'touchGalleryImagesRefresh' });
- const previousValues = getActiveProject(initial).widgetStates.gallery.values;
- const values = getActiveProject(state).widgetStates.gallery.values;
+ const previousValues = getProjectWidgetValues(getActiveProject(initial), 'gallery');
+ const values = getProjectWidgetValues(getActiveProject(state), 'gallery');
expect(values.galleryRefreshToken).toBe(previousValues.galleryRefreshToken);
expect(values.galleryImagesRefreshToken).toBeDefined();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index fd2fc2c5ca..35b50ccb60 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -24,9 +24,13 @@ import type {
ResultDestination,
WidgetFailure,
WidgetId,
+ WidgetInstanceContract,
+ WidgetInstanceId,
WidgetRegion,
WidgetRegionState,
WidgetStateContract,
+ WidgetStateMap,
+ WidgetTypeId,
WorkbenchNotification,
WorkbenchNotificationKind,
WorkbenchState,
@@ -75,14 +79,35 @@ type WorkbenchAction =
| { type: 'setInvocationDestination'; destination: ResultDestination }
| { type: 'toggleSourceLock' }
| { type: 'toggleDestinationLock' }
- | { type: 'openRegionWidget'; region: WidgetRegion; widgetId: WidgetId }
- | { type: 'selectRegionWidget'; region: WidgetRegion; widgetId: WidgetId }
- | { type: 'toggleRegionWidget'; region: WidgetRegion; widgetId: WidgetId }
+ | {
+ type: 'openRegionWidget';
+ region: WidgetRegion;
+ widgetId: WidgetTypeId;
+ createNew?: boolean;
+ initialValues?: Record<string, unknown>;
+ }
+ | { type: 'selectRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId }
+ | { type: 'toggleRegionWidget'; region: WidgetRegion; widgetId: WidgetInstanceId }
+ | {
+ type: 'moveWidgetInstance';
+ instanceId: WidgetInstanceId;
+ fromRegion: WidgetRegion;
+ toRegion: WidgetRegion;
+ toIndex: number;
+ }
+ | {
+ type: 'reorderWidgetInstances';
+ region: WidgetRegion;
+ activeInstanceId?: WidgetInstanceId;
+ instanceIds: WidgetInstanceId[];
+ }
| { type: 'setRegionWidgetCollapsed'; region: WidgetRegion; isCollapsed: boolean }
| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }
| { type: 'setGenerateSettings'; values: GenerateWidgetValues }
| { type: 'setGenerateBatchCount'; batchCount: number }
- | { type: 'patchWidgetValues'; widgetId: WidgetId; values: Record<string, unknown> }
+ | { 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: 'applyProjectGraphAction'; action: ProjectGraphAction }
| { type: 'replaceProjectGraph'; document: ProjectGraphState; label: string }
| { type: 'saveProjectGraphSnapshot' }
@@ -342,50 +367,93 @@ const cloneWidgetState = (widgetState: WidgetStateContract): WidgetStateContract
values: { ...widgetState.values },
});
-const cloneWidgetStates = (
- widgetStates: Record<WidgetId, WidgetStateContract>
-): Record<WidgetId, WidgetStateContract> => {
- const defaultWidgetStates = createWidgetStates();
+const cloneWidgetInstance = (widgetInstance: WidgetInstanceContract): WidgetInstanceContract => ({
+ ...widgetInstance,
+ state: cloneWidgetState(widgetInstance.state),
+});
+
+const cloneWidgetInstances = (
+ widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
+): Record<WidgetInstanceId, WidgetInstanceContract> =>
+ Object.fromEntries(
+ Object.entries({ ...createWidgetInstances(), ...widgetInstances }).map(([instanceId, widgetInstance]) => [
+ instanceId,
+ cloneWidgetInstance(widgetInstance),
+ ])
+ );
+
+const getWidgetStatesSnapshot = (widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>): WidgetStateMap => {
+ const widgetStates: WidgetStateMap = {};
+
+ for (const widgetInstance of Object.values(widgetInstances)) {
+ widgetStates[widgetInstance.typeId] ??= cloneWidgetState(widgetInstance.state);
+ }
+
+ return widgetStates;
+};
+
+const getWidgetState = (project: Project, widgetId: WidgetTypeId): WidgetStateContract => {
+ const widgetInstance =
+ project.widgetInstances[widgetId] ??
+ Object.values(project.widgetInstances).find((instance) => instance.typeId === widgetId);
+
+ return widgetInstance?.state ?? createWidgetState(widgetId);
+};
+
+const getWidgetValues = (project: Project, widgetId: WidgetTypeId): Record<string, unknown> =>
+ getWidgetState(project, widgetId).values;
+
+const updateProjectWidgetState = (
+ project: Project,
+ widgetId: WidgetTypeId,
+ getState: (state: WidgetStateContract) => WidgetStateContract
+): Project => {
+ const instance =
+ project.widgetInstances[widgetId] ??
+ Object.values(project.widgetInstances).find((candidate) => candidate.typeId === widgetId);
+ const instanceId = instance?.id ?? widgetId;
+ const currentInstance = instance ?? createWidgetInstance(widgetId, instanceId);
return {
- 'autosave-status': cloneWidgetState(widgetStates['autosave-status'] ?? defaultWidgetStates['autosave-status']),
- canvas: cloneWidgetState(widgetStates.canvas ?? defaultWidgetStates.canvas),
- diagnostics: cloneWidgetState(widgetStates.diagnostics ?? defaultWidgetStates.diagnostics),
- gallery: cloneWidgetState(widgetStates.gallery ?? defaultWidgetStates.gallery),
- generate: cloneWidgetState(widgetStates.generate ?? defaultWidgetStates.generate),
- 'history-controls': cloneWidgetState(widgetStates['history-controls'] ?? defaultWidgetStates['history-controls']),
- 'layout-actions': cloneWidgetState(widgetStates['layout-actions'] ?? defaultWidgetStates['layout-actions']),
- layers: cloneWidgetState(widgetStates.layers ?? defaultWidgetStates.layers),
- models: cloneWidgetState(widgetStates.models ?? defaultWidgetStates.models),
- notifications: cloneWidgetState(widgetStates.notifications ?? defaultWidgetStates.notifications),
- preview: cloneWidgetState(widgetStates.preview ?? defaultWidgetStates.preview),
- project: cloneWidgetState(widgetStates.project ?? defaultWidgetStates.project),
- queue: cloneWidgetState(widgetStates.queue ?? defaultWidgetStates.queue),
- 'server-status': cloneWidgetState(widgetStates['server-status'] ?? defaultWidgetStates['server-status']),
- users: cloneWidgetState(widgetStates.users ?? defaultWidgetStates.users),
- 'version-status': cloneWidgetState(widgetStates['version-status'] ?? defaultWidgetStates['version-status']),
- workflow: cloneWidgetState(widgetStates.workflow ?? defaultWidgetStates.workflow),
+ ...project,
+ widgetInstances: {
+ ...project.widgetInstances,
+ [instanceId]: {
+ ...currentInstance,
+ state: getState(currentInstance.state),
+ },
+ },
};
};
+const updateProjectWidgetValues = (
+ project: Project,
+ widgetId: WidgetTypeId,
+ getValues: (values: Record<string, unknown>) => Record<string, unknown>
+): Project =>
+ updateProjectWidgetState(project, widgetId, (widgetState) => ({
+ ...widgetState,
+ values: getValues(widgetState.values),
+ }));
+
const cloneWidgetRegions = (
widgetRegions: Record<WidgetRegion, WidgetRegionState>
): Record<WidgetRegion, WidgetRegionState> => ({
center: {
...widgetRegions.center,
- enabledWidgetIds: [...widgetRegions.center.enabledWidgetIds],
+ instanceIds: [...widgetRegions.center.instanceIds],
},
left: {
...widgetRegions.left,
- enabledWidgetIds: [...widgetRegions.left.enabledWidgetIds],
+ instanceIds: [...widgetRegions.left.instanceIds],
},
right: {
...widgetRegions.right,
- enabledWidgetIds: [...widgetRegions.right.enabledWidgetIds],
+ instanceIds: [...widgetRegions.right.instanceIds],
},
bottom: {
...widgetRegions.bottom,
- enabledWidgetIds: [...widgetRegions.bottom.enabledWidgetIds],
+ instanceIds: [...widgetRegions.bottom.instanceIds],
},
});
@@ -398,8 +466,8 @@ const createUndoSnapshot = (project: Project): ProjectUndoSnapshot => ({
layout: { ...project.layout, panels: { ...project.layout.panels } },
projectGraph: cloneProjectGraph(project.projectGraph),
widgetGraphs: cloneWidgetGraphs(project.widgetGraphs),
+ widgetInstances: cloneWidgetInstances(project.widgetInstances),
widgetRegions: cloneWidgetRegions(project.widgetRegions),
- widgetStates: cloneWidgetStates(project.widgetStates),
});
const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): Project => ({
@@ -409,8 +477,8 @@ const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): P
layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },
projectGraph: cloneProjectGraph(normalizeProjectGraph(snapshot.projectGraph)),
widgetGraphs: cloneWidgetGraphs(snapshot.widgetGraphs),
+ widgetInstances: cloneWidgetInstances(snapshot.widgetInstances),
widgetRegions: cloneWidgetRegions(snapshot.widgetRegions),
- widgetStates: cloneWidgetStates(snapshot.widgetStates),
});
const createGraphHistorySnapshot = (label: string, graph: GraphContract): GraphHistorySnapshot => ({
@@ -444,13 +512,12 @@ const pushUndo = (project: Project, label: string): Project => ({
},
});
-const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({
+const createWidgetStates = (): WidgetStateMap => ({
'autosave-status': { id: 'autosave-status', label: 'Autosave', values: {}, version: 1 },
canvas: { id: 'canvas', label: 'Canvas', values: {}, version: 1 },
diagnostics: { id: 'diagnostics', label: 'Diagnostics', values: {}, version: 1 },
gallery: { id: 'gallery', label: 'Gallery', values: {}, version: 1 },
generate: { graphId: 'generate-graph', id: 'generate', label: 'Generate', values: {}, version: 1 },
- 'history-controls': { id: 'history-controls', label: 'History Controls', values: {}, version: 1 },
'layout-actions': { id: 'layout-actions', label: 'Layout Actions', values: {}, version: 1 },
layers: { id: 'layers', label: 'Layers', values: {}, version: 1 },
models: { id: 'models', label: 'Models', values: {}, version: 1 },
@@ -464,39 +531,92 @@ const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({
workflow: { graphId: 'workflow-graph', id: 'workflow', label: 'Workflow', values: {}, version: 1 },
});
+const createWidgetState = (widgetId: WidgetTypeId): WidgetStateContract =>
+ cloneWidgetState(
+ createWidgetStates()[widgetId] ?? {
+ id: widgetId,
+ label: widgetId,
+ values: {},
+ version: 1,
+ }
+ );
+
+const createWidgetInstance = (
+ widgetId: WidgetTypeId,
+ instanceId: WidgetInstanceId = widgetId,
+ values?: Record<string, unknown>
+): WidgetInstanceContract => ({
+ createdAt: now(),
+ id: instanceId,
+ state: values ? { ...createWidgetState(widgetId), values } : createWidgetState(widgetId),
+ typeId: widgetId,
+});
+
+const defaultWidgetInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {
+ 'autosave-status': 'autosave-status',
+ canvas: 'canvas',
+ diagnostics: 'diagnostics',
+ 'diagnostics:bottom': 'diagnostics',
+ gallery: 'gallery',
+ 'gallery:bottom': 'gallery',
+ 'gallery:center': 'gallery',
+ generate: 'generate',
+ 'layout-actions': 'layout-actions',
+ layers: 'layers',
+ models: 'models',
+ 'models:center': 'models',
+ notifications: 'notifications',
+ preview: 'preview',
+ project: 'project',
+ queue: 'queue',
+ 'queue:bottom': 'queue',
+ 'server-status': 'server-status',
+ 'version-status': 'version-status',
+ workflow: 'workflow',
+ 'workflow:bottom': 'workflow',
+ 'workflow:center': 'workflow',
+};
+
+const createWidgetInstances = (): Record<WidgetInstanceId, WidgetInstanceContract> =>
+ Object.fromEntries(
+ Object.entries(defaultWidgetInstanceTypes).map(([instanceId, widgetId]) => [
+ instanceId,
+ createWidgetInstance(widgetId, instanceId),
+ ])
+ );
+
const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({
left: {
- activeWidgetId: 'generate',
- enabledWidgetIds: ['generate', 'workflow'],
+ activeInstanceId: 'generate',
+ instanceIds: ['generate', 'workflow'],
isCollapsed: false,
sizePx: 288,
},
right: {
- activeWidgetId: 'layers',
- enabledWidgetIds: ['queue', 'gallery', 'layers', 'models', 'diagnostics', 'project'],
+ activeInstanceId: 'layers',
+ instanceIds: ['queue', 'gallery', 'layers', 'models', 'diagnostics', 'project'],
isCollapsed: false,
sizePx: 240,
},
bottom: {
- activeWidgetId: 'queue',
- enabledWidgetIds: [
+ activeInstanceId: 'queue',
+ instanceIds: [
'server-status',
- 'diagnostics',
- 'queue',
- 'gallery',
+ 'diagnostics:bottom',
+ 'queue:bottom',
+ 'gallery:bottom',
'notifications',
'autosave-status',
- 'history-controls',
'layout-actions',
'version-status',
- 'workflow',
+ 'workflow:bottom',
],
isCollapsed: true,
sizePx: 180,
},
center: {
- activeWidgetId: 'canvas',
- enabledWidgetIds: ['canvas', 'gallery', 'preview', 'workflow', 'models'],
+ activeInstanceId: 'canvas',
+ instanceIds: ['canvas', 'gallery:center', 'preview', 'workflow:center', 'models:center'],
isCollapsed: false,
sizePx: 0,
},
@@ -505,8 +625,8 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({
const LEGACY_RIGHT_REGION_WIDGET_IDS: WidgetId[] = ['queue', 'gallery', 'layers'];
const isLegacyDefaultRightRegion = (region: WidgetRegionState): boolean =>
- region.enabledWidgetIds.length === LEGACY_RIGHT_REGION_WIDGET_IDS.length &&
- region.enabledWidgetIds.every((widgetId, index) => widgetId === LEGACY_RIGHT_REGION_WIDGET_IDS[index]);
+ region.instanceIds.length === LEGACY_RIGHT_REGION_WIDGET_IDS.length &&
+ region.instanceIds.every((widgetId, index) => widgetId === LEGACY_RIGHT_REGION_WIDGET_IDS[index]);
const ensureRightRegion = (rightRegion: WidgetRegionState | undefined): WidgetRegionState => {
const defaultRightRegion = createWidgetRegions().right;
@@ -516,40 +636,52 @@ const ensureRightRegion = (rightRegion: WidgetRegionState | undefined): WidgetRe
}
if (isLegacyDefaultRightRegion(rightRegion)) {
- return { ...rightRegion, enabledWidgetIds: defaultRightRegion.enabledWidgetIds };
+ return { ...rightRegion, instanceIds: defaultRightRegion.instanceIds };
}
return rightRegion;
};
-const getCenterWidgetIdFromViewId = (centerViewId: CenterViewId): WidgetId => centerViewId;
+const getCenterWidgetIdFromViewId = (centerViewId: CenterViewId): WidgetInstanceId => {
+ if (centerViewId === 'gallery') {
+ return 'gallery:center';
+ }
+
+ if (centerViewId === 'models') {
+ return 'models:center';
+ }
+
+ if (centerViewId === 'workflow') {
+ return 'workflow:center';
+ }
+
+ return centerViewId;
+};
const ensureCenterRegion = (
centerRegion: WidgetRegionState | undefined,
fallbackCenterViewId: CenterViewId
): WidgetRegionState => {
const defaultCenterRegion = createWidgetRegions().center;
- const activeWidgetId = centerRegion?.activeWidgetId ?? getCenterWidgetIdFromViewId(fallbackCenterViewId);
- const enabledWidgetIds = centerRegion?.enabledWidgetIds.length
- ? centerRegion.enabledWidgetIds
- : defaultCenterRegion.enabledWidgetIds;
- const normalizedActiveWidgetId = enabledWidgetIds.includes(activeWidgetId) ? activeWidgetId : enabledWidgetIds[0];
+ const activeInstanceId = centerRegion?.activeInstanceId ?? getCenterWidgetIdFromViewId(fallbackCenterViewId);
+ const instanceIds = centerRegion?.instanceIds.length ? centerRegion.instanceIds : defaultCenterRegion.instanceIds;
+ const normalizedActiveInstanceId = instanceIds.includes(activeInstanceId) ? activeInstanceId : instanceIds[0];
return {
...defaultCenterRegion,
...centerRegion,
- activeWidgetId: normalizedActiveWidgetId,
- enabledWidgetIds,
+ activeInstanceId: normalizedActiveInstanceId,
+ instanceIds,
isCollapsed: false,
};
};
const ensureProjectWidgetContracts = (project: Project): Project => {
const defaultWidgetRegions = createWidgetRegions();
- const defaultWidgetStates = createWidgetStates();
const legacyWidgetRegions = project.widgetRegions as
| Partial<Record<WidgetRegion | 'left-panel' | 'right-panel' | 'status-bar', WidgetRegionState>>
| undefined;
+ const widgetInstances = project.widgetInstances ?? createWidgetInstances();
return {
...project,
@@ -562,10 +694,7 @@ const ensureProjectWidgetContracts = (project: Project): Project => {
bottom: legacyWidgetRegions?.bottom ?? legacyWidgetRegions?.['status-bar'] ?? defaultWidgetRegions.bottom,
center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),
},
- widgetStates: {
- ...defaultWidgetStates,
- ...project.widgetStates,
- },
+ widgetInstances: cloneWidgetInstances(widgetInstances),
};
};
@@ -609,8 +738,8 @@ const createProject = (index: number, id = `project-${index}`): Project => ({
settings: normalizeProjectSettings(),
undoRedo: { future: [], past: [] },
widgetGraphs: {},
+ widgetInstances: createWidgetInstances(),
widgetRegions: createWidgetRegions(),
- widgetStates: createWidgetStates(),
});
const getNextProjectIndex = (projects: Project[]): number => {
@@ -634,12 +763,21 @@ const updateActiveProject = (state: WorkbenchState, getProject: (project: Projec
),
});
-const getNextEnabledWidgetId = (region: WidgetRegionState, widgetId: WidgetId): WidgetId | null => {
- if (region.activeWidgetId !== widgetId) {
- return region.activeWidgetId;
+const getNextInstanceId = (region: WidgetRegionState, instanceId: WidgetInstanceId): WidgetInstanceId | null => {
+ if (region.activeInstanceId !== instanceId) {
+ return region.activeInstanceId;
}
- return region.enabledWidgetIds.find((enabledWidgetId) => enabledWidgetId !== widgetId) ?? null;
+ return region.instanceIds.find((enabledInstanceId) => enabledInstanceId !== instanceId) ?? null;
+};
+
+const insertAt = <Value>(values: Value[], value: Value, index: number): Value[] => {
+ const nextValues = values.filter((candidate) => candidate !== value);
+ const nextIndex = Math.min(nextValues.length, Math.max(0, index));
+
+ nextValues.splice(nextIndex, 0, value);
+
+ return nextValues;
};
const updateActiveWidgetRegion = (
@@ -660,7 +798,7 @@ const applyPresetRegionFocus = (state: WorkbenchState, preset: LayoutPreset): Wo
const centerWidgetId = getCenterWidgetIdFromViewId(preset.initialLayout.centerViewId);
const nextState = updateActiveWidgetRegion(state, 'center', (region) => ({
...region,
- activeWidgetId: region.enabledWidgetIds.includes(centerWidgetId) ? centerWidgetId : region.activeWidgetId,
+ activeInstanceId: region.instanceIds.includes(centerWidgetId) ? centerWidgetId : region.activeInstanceId,
isCollapsed: false,
}));
const leftWidgetId = preset.leftRegionWidgetId;
@@ -671,7 +809,7 @@ const applyPresetRegionFocus = (state: WorkbenchState, preset: LayoutPreset): Wo
return updateActiveWidgetRegion(nextState, 'left', (region) => ({
...region,
- activeWidgetId: region.enabledWidgetIds.includes(leftWidgetId) ? leftWidgetId : region.activeWidgetId,
+ activeInstanceId: region.instanceIds.includes(leftWidgetId) ? leftWidgetId : region.activeInstanceId,
isCollapsed: false,
}));
};
@@ -744,8 +882,8 @@ const compileInvocationSnapshot = (
project: Project,
route: InvocationRoute,
models?: readonly ModelConfig[]
-): { graph: GraphContract; widgetStates: Record<WidgetId, WidgetStateContract> } | null => {
- const widgetStates = cloneWidgetStates(project.widgetStates);
+): { graph: GraphContract; widgetStates: WidgetStateMap } | null => {
+ const widgetStates = getWidgetStatesSnapshot(project.widgetInstances);
if (route.sourceId === 'project-graph') {
// Compiles the workflow document into an immutable snapshot. Templates are
@@ -760,12 +898,12 @@ const compileInvocationSnapshot = (
}
if (route.sourceId !== 'generate') {
- const widgetGraph = project.widgetGraphs[route.sourceId as WidgetId];
+ const widgetGraph = project.widgetGraphs[route.sourceId as WidgetTypeId];
return widgetGraph ? { graph: cloneGraph(widgetGraph), widgetStates } : null;
}
- const values = normalizeGenerateWidgetValues(project.widgetStates.generate.values);
+ const values = normalizeGenerateWidgetValues(getWidgetValues(project, 'generate'));
if (!values) {
return null;
@@ -816,7 +954,7 @@ const updateGalleryValues = (
getValues: (values: Record<string, unknown>) => Record<string, unknown>
): WorkbenchState => {
const activeProject = state.projects.find((project) => project.id === state.activeProjectId);
- const values = activeProject?.widgetStates.gallery.values;
+ const values = activeProject ? getWidgetValues(activeProject, 'gallery') : null;
if (!activeProject || !values) {
return state;
@@ -828,33 +966,15 @@ const updateGalleryValues = (
return state;
}
- return updateActiveProject(state, (project) => {
- return {
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: nextValues,
- },
- },
- };
- });
+ return updateActiveProject(state, (project) => updateProjectWidgetValues(project, 'gallery', () => nextValues));
};
const refreshProjectBackendData = (project: Project): Project => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: {
- ...project.widgetStates.gallery.values,
- galleryImagesRefreshToken: createId('gallery-images-refresh'),
- galleryRefreshToken: createId('gallery-refresh'),
- },
- },
- },
+ ...updateProjectWidgetValues(project, 'gallery', (values) => ({
+ ...values,
+ galleryImagesRefreshToken: createId('gallery-images-refresh'),
+ galleryRefreshToken: createId('gallery-refresh'),
+ })),
});
const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => ({
@@ -911,27 +1031,18 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageC
return project;
}
- const galleryValues = project.widgetStates.gallery.values;
+ const galleryValues = getWidgetValues(project, 'gallery');
const existingImages = getGalleryImages(galleryValues).filter(
(image) => !images.some((incomingImage) => incomingImage.imageName === image.imageName)
);
- return {
- ...project,
- widgetStates: {
- ...project.widgetStates,
- gallery: {
- ...project.widgetStates.gallery,
- values: {
- ...galleryValues,
- recentImages: [...images, ...existingImages],
- selectedImage: images[0] ?? galleryValues.selectedImage,
- selectedImageName: images[0]?.imageName ?? project.widgetStates.gallery.values.selectedImageName,
- selectedImageNames: images[0] ? [images[0].imageName] : getGallerySelectedImageNames(galleryValues),
- },
- },
- },
- };
+ return updateProjectWidgetValues(project, 'gallery', () => ({
+ ...galleryValues,
+ recentImages: [...images, ...existingImages],
+ selectedImage: images[0] ?? galleryValues.selectedImage,
+ selectedImageName: images[0]?.imageName ?? galleryValues.selectedImageName,
+ selectedImageNames: images[0] ? [images[0].imageName] : getGallerySelectedImageNames(galleryValues),
+ }));
};
const routeQueueItemPartialResults = (
@@ -1023,6 +1134,7 @@ const submitInvocationSnapshot = (
graph,
sourceId: route.sourceId,
submittedAt,
+ widgetInstances: cloneWidgetInstances(project.widgetInstances),
widgetStates,
},
status: 'pending',
@@ -1130,7 +1242,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
return updateActiveWidgetRegion(state, 'center', (region) => ({
...region,
- activeWidgetId: region.enabledWidgetIds.includes(widgetId) ? widgetId : region.activeWidgetId,
+ activeInstanceId: region.instanceIds.includes(widgetId) ? widgetId : region.activeInstanceId,
isCollapsed: false,
}));
}
@@ -1185,19 +1297,34 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
case 'openRegionWidget': {
return updateActiveProject(state, (project) => {
const region = project.widgetRegions[action.region];
- const enabledWidgetIds = region.enabledWidgetIds.includes(action.widgetId)
- ? region.enabledWidgetIds
- : [...region.enabledWidgetIds, action.widgetId];
+ const existingInstanceInRegion = region.instanceIds
+ .map((instanceId) => project.widgetInstances[instanceId])
+ .find((instance) => instance?.typeId === action.widgetId);
+ const existingInstance =
+ existingInstanceInRegion ??
+ Object.values(project.widgetInstances).find((instance) => instance.typeId === action.widgetId);
+ const instanceId =
+ action.createNew || !existingInstance ? createId(`widget-${action.widgetId}`) : existingInstance.id;
+ const instanceIds = region.instanceIds.includes(instanceId)
+ ? region.instanceIds
+ : [...region.instanceIds, instanceId];
+ const widgetInstances = project.widgetInstances[instanceId]
+ ? project.widgetInstances
+ : {
+ ...project.widgetInstances,
+ [instanceId]: createWidgetInstance(action.widgetId, instanceId, action.initialValues),
+ };
return {
...project,
layout: openPanelForRegion(project.layout, action.region),
+ widgetInstances,
widgetRegions: {
...project.widgetRegions,
[action.region]: {
...region,
- activeWidgetId: action.widgetId,
- enabledWidgetIds,
+ activeInstanceId: instanceId,
+ instanceIds,
isCollapsed: false,
},
},
@@ -1213,15 +1340,15 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
...project,
widgetRegions: {
...project.widgetRegions,
- center: { ...region, activeWidgetId: action.widgetId, isCollapsed: false },
+ center: { ...region, activeInstanceId: action.widgetId, isCollapsed: false },
},
};
}
const widgetRegion =
- region.activeWidgetId === action.widgetId
+ region.activeInstanceId === action.widgetId
? { ...region, isCollapsed: !region.isCollapsed }
- : { ...region, activeWidgetId: action.widgetId, isCollapsed: false };
+ : { ...region, activeInstanceId: action.widgetId, isCollapsed: false };
return {
...project,
@@ -1232,25 +1359,64 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
}
case 'toggleRegionWidget': {
return updateActiveWidgetRegion(state, action.region, (region) => {
- const isEnabled = region.enabledWidgetIds.includes(action.widgetId);
+ const isEnabled = region.instanceIds.includes(action.widgetId);
- if (action.region === 'center' && isEnabled && region.enabledWidgetIds.length === 1) {
+ if (action.region === 'center' && isEnabled && region.instanceIds.length === 1) {
return region;
}
- const enabledWidgetIds = isEnabled
- ? region.enabledWidgetIds.filter((widgetId) => widgetId !== action.widgetId)
- : [...region.enabledWidgetIds, action.widgetId];
- const fallbackWidgetId = getNextEnabledWidgetId(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,
- activeWidgetId: isEnabled && fallbackWidgetId ? fallbackWidgetId : action.widgetId,
- enabledWidgetIds,
- isCollapsed: action.region === 'center' ? false : enabledWidgetIds.length === 0 ? true : region.isCollapsed,
+ activeInstanceId: isEnabled && fallbackInstanceId ? fallbackInstanceId : action.widgetId,
+ instanceIds,
+ isCollapsed: action.region === 'center' ? false : instanceIds.length === 0 ? true : region.isCollapsed,
+ };
+ });
+ }
+ case 'moveWidgetInstance': {
+ return updateActiveProject(state, (project) => {
+ const fromRegion = project.widgetRegions[action.fromRegion];
+ const toRegion = project.widgetRegions[action.toRegion];
+ const nextFromInstanceIds = fromRegion.instanceIds.filter((instanceId) => instanceId !== action.instanceId);
+ const nextToInstanceIds = insertAt(toRegion.instanceIds, action.instanceId, action.toIndex);
+
+ return {
+ ...project,
+ layout: openPanelForRegion(project.layout, action.toRegion),
+ widgetRegions: {
+ ...project.widgetRegions,
+ [action.fromRegion]: {
+ ...fromRegion,
+ activeInstanceId:
+ fromRegion.activeInstanceId === action.instanceId
+ ? (nextFromInstanceIds[0] ?? fromRegion.activeInstanceId)
+ : fromRegion.activeInstanceId,
+ instanceIds: nextFromInstanceIds,
+ isCollapsed:
+ action.fromRegion === 'center' ? false : nextFromInstanceIds.length === 0 || fromRegion.isCollapsed,
+ },
+ [action.toRegion]: {
+ ...toRegion,
+ activeInstanceId: action.instanceId,
+ instanceIds: nextToInstanceIds,
+ isCollapsed: false,
+ },
+ },
};
});
}
+ case 'reorderWidgetInstances': {
+ return updateActiveWidgetRegion(state, action.region, (region) => ({
+ ...region,
+ activeInstanceId: action.activeInstanceId ?? region.activeInstanceId,
+ instanceIds: action.instanceIds,
+ }));
+ }
case 'setRegionWidgetCollapsed': {
if (action.region === 'center') {
return state;
@@ -1268,43 +1434,62 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
}));
}
case 'setGenerateSettings': {
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- generate: {
- ...project.widgetStates.generate,
- values: cloneGenerateWidgetValues(action.values),
- },
- },
- }));
+ return updateActiveProject(state, (project) =>
+ updateProjectWidgetValues(project, 'generate', () => cloneGenerateWidgetValues(action.values))
+ );
}
case 'setGenerateBatchCount': {
const batchCount = sanitizeBatchCount(action.batchCount);
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- generate: {
- ...project.widgetStates.generate,
- values: { ...project.widgetStates.generate.values, batchCount },
- },
- },
- }));
+ return updateActiveProject(state, (project) =>
+ updateProjectWidgetValues(project, 'generate', (values) => ({ ...values, batchCount }))
+ );
}
case 'patchWidgetValues': {
// Generic widget-owned UI state (panel modes, tabs, sizes). Not undoable.
- return updateActiveProject(state, (project) => ({
- ...project,
- widgetStates: {
- ...project.widgetStates,
- [action.widgetId]: {
- ...project.widgetStates[action.widgetId],
- values: { ...project.widgetStates[action.widgetId].values, ...action.values },
+ return updateActiveProject(state, (project) =>
+ updateProjectWidgetValues(project, action.widgetId, (values) => ({ ...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 } },
+ },
},
- },
- }));
+ };
+ });
+ }
+ case 'setWidgetInstanceValues': {
+ 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: action.values },
+ },
+ },
+ };
+ });
}
case 'applyProjectGraphAction': {
return updateActiveProject(state, (project) => {