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(settings): unify searchable dialog and widget controls

Josh Corbett7c44e2a4b3a8
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 75a00d95b5..c78c47c585 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -82,3 +82,17 @@ Feature interfaces remain ordinary module interfaces unless two adapters add lev
| Generation | Generation settings, validation, graph compilation and Generate UI; Workbench invocation, Queue, Gallery, Workflow, Upscale | Platform and public Models/Gallery/Queue interfaces; settings/validation, compiled submission envelope and widget contribution |
| Workflow | Workflow document, validation, compilation, preview/editor/library; App adapter, Workbench invocation, Nodes | Platform and public Nodes/Models/Gallery/Queue interfaces; document reads/commands, compiled submission envelope and widget contribution |
| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |
+
+## Settings contributions
+
+Settings are declared by their owners and presented by Workbench. Platform UI owns domain-neutral field metadata and controls; it does not own setting values or persistence. A widget manifest exposes a `settings` contribution containing localized field metadata, an ordered `quick` subset, and a deferred field binding loader. The full dialog includes every declared field. Bindings retain the owner's normalization and command path, including Gallery's size/density conversion and project/instance fencing.
+
+Workbench composes widget and application contributions into a metadata-only catalog. Search, dialog navigation, quick popovers, and command-palette destinations share that catalog. Features publish contribution metadata through registered public entries; loading metadata must not load their UI or start data queries. Application-owned additions can join a widget section without changing the owner of their values. Deferred resources cache code only; field subscriptions exist only while their controls are mounted.
+
+Section placement does not determine storage lifetime. Account/install preferences, project settings, widget-instance values, and server configuration retain their existing persistence and authorization. The shell resolves explicit project/instance targets, shows unavailable controls without constructing a widget, and disposes target-bound editing when projects change. Owner bindings fence writes against stale account/project lifetimes.
+
+The settings host owns the dialog's presence lifecycle and keeps its root mounted through closing. The body is deferred until first opening, remains present during exit, and unmounts afterward. Quick-popover handoff carries both the instance target and the original gear for focus restoration.
+
+Before section navigation becomes available, the deferred dialog prepares binding/editor code without mounting editors or starting their queries. Section and scroll position survive closing within the account lifetime. The shell renders a shared modified-setting indicator; bindings determine whether a value differs from the owner’s canonical default. Quick settings use the shared arrowed popover with an inner scroll area, and dialog selects keep their bounded scroll areas inside the modal focus scope.
+
+Production chunking keeps the catalog and manifest metadata separate from editor boot UI. The build gate checks that Launchpad’s palette and settings dialog do not statically include the editor application or widget renderer. Shared settings controls remain in the common UI chunk; owner field bindings and custom editors remain deferred.
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index f6585d52cd..1984d7fa39 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -30,7 +30,7 @@
"test:all": "pnpm run test && pnpm run test:browser && pnpm run test:fixtures",
"test:browser": "vitest run --config vitest.browser.config.mts",
"test:browser:update-goldens": "CANVAS_GOLDEN_UPDATE=1 vitest run --config vitest.browser.config.mts src/workbench/canvas-engine/render/golden",
- "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/run-project-file-journey.test.mjs",
+ "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs",
"test:performance:architecture": "pnpm run test:performance:build && pnpm run test:performance:browser",
"test:performance:browser": "node scripts/measure-architecture-performance.mjs",
"test:performance:browser:update-baseline": "node scripts/measure-architecture-performance.mjs --update-baseline",
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index f51db0caca..6841ee8f35 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -211,9 +211,11 @@
"source:src/platform/ui/MiddleTruncate.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -233,6 +235,7 @@
"source:src/platform/ui/hints/hintsContext.tsx",
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/theme/applyTheme.ts",
"source:src/platform/ui/theme/recipes.ts",
"source:src/platform/ui/theme/system.ts",
@@ -241,8 +244,10 @@
"source:src/platform/ui/useScrollAreaPhantomHeal.ts",
"source:src/workbench/canvasSchemaVersion.ts",
"source:src/workbench/components/WorkbenchSplashScreen.tsx",
+ "source:src/workbench/deferredResource.ts",
"source:src/workbench/hotkeys/catalog.ts",
"source:src/workbench/hotkeys/keys.ts",
+ "source:src/workbench/hotkeys/modalLayer.ts",
"source:src/workbench/hotkeys/resolve.ts",
"source:src/workbench/launchpad/HelpMenu.tsx",
"source:src/workbench/launchpad/KnownBrowserIssuesAlert.tsx",
@@ -291,6 +296,7 @@
"source:src/workbench/projects/useProjectFileActions.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts"
]
@@ -477,6 +483,7 @@
"source:src/features/gallery/picker.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
+ "source:src/features/gallery/settingsContribution.ts",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardRowShell.tsx",
"source:src/features/gallery/ui/GalleryDragCursor.tsx",
@@ -700,9 +707,11 @@
"source:src/platform/ui/MiddleTruncate.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -722,6 +731,7 @@
"source:src/platform/ui/hints/hintsContext.tsx",
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/theme/applyTheme.ts",
"source:src/platform/ui/theme/recipes.ts",
"source:src/platform/ui/theme/system.ts",
@@ -887,7 +897,11 @@
"source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/WidgetSettingsButton.tsx",
+ "source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts",
"source:src/workbench/shell/BottomPanel.tsx",
@@ -961,17 +975,23 @@
"source:src/workbench/widgetState.ts",
"source:src/workbench/widgets/autosave-status/manifest.ts",
"source:src/workbench/widgets/canvas/bboxGrid.ts",
+ "source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
+ "source:src/workbench/widgets/canvas/settingsContribution.ts",
"source:src/workbench/widgets/diagnostics/manifest.ts",
"source:src/workbench/widgets/gallery/manifest.ts",
"source:src/workbench/widgets/generate/manifest.ts",
"source:src/workbench/widgets/image-map/manifest.ts",
+ "source:src/workbench/widgets/image-map/settingsContribution.ts",
"source:src/workbench/widgets/layers/manifest.ts",
"source:src/workbench/widgets/layers/panes/editorPaneLayout.ts",
+ "source:src/workbench/widgets/manifests.ts",
"source:src/workbench/widgets/notifications/manifest.ts",
"source:src/workbench/widgets/preview/manifest.ts",
+ "source:src/workbench/widgets/preview/previewSettings.ts",
+ "source:src/workbench/widgets/preview/settingsContribution.ts",
"source:src/workbench/widgets/project/manifest.ts",
"source:src/workbench/widgets/queue-status/manifest.ts",
"source:src/workbench/widgets/queue/manifest.ts",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index beebf92560..4272586139 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -737,6 +737,7 @@
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/launchpad.ts",
+ "source:src/features/gallery/ui/GalleryUiContext.tsx",
"source:src/features/gallery/ui/galleryStateView.ts",
"source:src/features/gallery/ui/launchpad/RecentOutputs.tsx",
"source:src/features/identity/capabilities.ts",
@@ -841,9 +842,11 @@
"source:src/platform/ui/MiddleTruncate.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -863,6 +866,7 @@
"source:src/platform/ui/hints/hintsContext.tsx",
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/theme/applyTheme.ts",
"source:src/platform/ui/theme/recipes.ts",
"source:src/platform/ui/theme/system.ts",
@@ -871,8 +875,10 @@
"source:src/platform/ui/useScrollAreaPhantomHeal.ts",
"source:src/workbench/canvasSchemaVersion.ts",
"source:src/workbench/components/WorkbenchSplashScreen.tsx",
+ "source:src/workbench/deferredResource.ts",
"source:src/workbench/hotkeys/catalog.ts",
"source:src/workbench/hotkeys/keys.ts",
+ "source:src/workbench/hotkeys/modalLayer.ts",
"source:src/workbench/hotkeys/resolve.ts",
"source:src/workbench/launchpad/HelpMenu.tsx",
"source:src/workbench/launchpad/KnownBrowserIssuesAlert.tsx",
@@ -922,6 +928,7 @@
"source:src/workbench/projects/useProjectFileActions.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts"
],
@@ -1079,6 +1086,7 @@
"source:src/features/gallery/picker.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
+ "source:src/features/gallery/settingsContribution.ts",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -1095,7 +1103,6 @@
"source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
- "source:src/features/gallery/ui/GallerySettingsMenu.tsx",
"source:src/features/gallery/ui/GallerySplitHandle.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryThumbnail.tsx",
@@ -1432,10 +1439,12 @@
"source:src/platform/ui/ModelDefaultButton.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Picker.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -1456,6 +1465,7 @@
"source:src/platform/ui/hints/hintsContext.tsx",
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/streaming-image/StreamingImageFrame.tsx",
"source:src/platform/ui/streaming-image/streamingImageSource.ts",
"source:src/platform/ui/streaming-image/useStreamingImageSource.ts",
@@ -1779,7 +1789,11 @@
"source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/WidgetSettingsButton.tsx",
+ "source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts",
"source:src/workbench/shell/BottomPanel.tsx",
@@ -1855,19 +1869,23 @@
"source:src/workbench/widgets/autosave-status/implementation.ts",
"source:src/workbench/widgets/autosave-status/manifest.ts",
"source:src/workbench/widgets/canvas/bboxGrid.ts",
+ "source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
+ "source:src/workbench/widgets/canvas/settingsContribution.ts",
"source:src/workbench/widgets/diagnostics/manifest.ts",
"source:src/workbench/widgets/gallery/manifest.ts",
"source:src/workbench/widgets/generate/manifest.ts",
"source:src/workbench/widgets/image-map/ImageMapDataRuntime.tsx",
"source:src/workbench/widgets/image-map/manifest.ts",
+ "source:src/workbench/widgets/image-map/settingsContribution.ts",
"source:src/workbench/widgets/layers/controlModelOptions.ts",
"source:src/workbench/widgets/layers/layerOps.ts",
"source:src/workbench/widgets/layers/manifest.ts",
"source:src/workbench/widgets/layers/panes/editorPaneLayout.ts",
"source:src/workbench/widgets/layers/selectedModel.ts",
+ "source:src/workbench/widgets/manifests.ts",
"source:src/workbench/widgets/notifications/NotificationsHeaderActions.tsx",
"source:src/workbench/widgets/notifications/NotificationsWidgetView.tsx",
"source:src/workbench/widgets/notifications/implementation.ts",
@@ -1892,6 +1910,7 @@
"source:src/workbench/widgets/preview/previewMetadata.ts",
"source:src/workbench/widgets/preview/previewNavigation.ts",
"source:src/workbench/widgets/preview/previewSettings.ts",
+ "source:src/workbench/widgets/preview/settingsContribution.ts",
"source:src/workbench/widgets/preview/useCompareLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewNavigation.ts",
@@ -2064,6 +2083,7 @@
"source:src/features/gallery/picker.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
+ "source:src/features/gallery/settingsContribution.ts",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -2080,7 +2100,6 @@
"source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
- "source:src/features/gallery/ui/GallerySettingsMenu.tsx",
"source:src/features/gallery/ui/GallerySplitHandle.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryThumbnail.tsx",
@@ -2425,10 +2444,12 @@
"source:src/platform/ui/ModelDefaultButton.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Picker.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -2450,6 +2471,7 @@
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/hsv.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/streaming-image/StreamingImageFrame.tsx",
"source:src/platform/ui/streaming-image/streamingImageSource.ts",
"source:src/platform/ui/streaming-image/useStreamingImageSource.ts",
@@ -2777,7 +2799,11 @@
"source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/WidgetSettingsButton.tsx",
+ "source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts",
"source:src/workbench/shell/BottomPanel.tsx",
@@ -2895,6 +2921,7 @@
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
+ "source:src/workbench/widgets/canvas/settingsContribution.ts",
"source:src/workbench/widgets/canvas/stagingPreview.ts",
"source:src/workbench/widgets/canvas/surfaceFocus.ts",
"source:src/workbench/widgets/canvas/tool-options/BrushOptions.tsx",
@@ -2928,6 +2955,7 @@
"source:src/workbench/widgets/generate/manifest.ts",
"source:src/workbench/widgets/image-map/ImageMapDataRuntime.tsx",
"source:src/workbench/widgets/image-map/manifest.ts",
+ "source:src/workbench/widgets/image-map/settingsContribution.ts",
"source:src/workbench/widgets/layers/AdjustmentSettings.tsx",
"source:src/workbench/widgets/layers/ControlLayerSettings.tsx",
"source:src/workbench/widgets/layers/ControlLayerWarningIcon.tsx",
@@ -3001,6 +3029,7 @@
"source:src/workbench/widgets/layers/useLayerStackActions.ts",
"source:src/workbench/widgets/layers/useSelectedMainModel.ts",
"source:src/workbench/widgets/layers/useSelectedModelBase.ts",
+ "source:src/workbench/widgets/manifests.ts",
"source:src/workbench/widgets/notifications/NotificationsHeaderActions.tsx",
"source:src/workbench/widgets/notifications/NotificationsWidgetView.tsx",
"source:src/workbench/widgets/notifications/implementation.ts",
@@ -3025,6 +3054,7 @@
"source:src/workbench/widgets/preview/previewMetadata.ts",
"source:src/workbench/widgets/preview/previewNavigation.ts",
"source:src/workbench/widgets/preview/previewSettings.ts",
+ "source:src/workbench/widgets/preview/settingsContribution.ts",
"source:src/workbench/widgets/preview/useCompareLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewNavigation.ts",
@@ -3208,6 +3238,7 @@
"source:src/features/gallery/picker.ts",
"source:src/features/gallery/queries.ts",
"source:src/features/gallery/react.ts",
+ "source:src/features/gallery/settingsContribution.ts",
"source:src/features/gallery/ui/GalleryBoardCover.tsx",
"source:src/features/gallery/ui/GalleryBoardDragMonitor.tsx",
"source:src/features/gallery/ui/GalleryBoardFilters.tsx",
@@ -3224,7 +3255,6 @@
"source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",
"source:src/features/gallery/ui/GallerySearchField.tsx",
"source:src/features/gallery/ui/GallerySelectionBar.tsx",
- "source:src/features/gallery/ui/GallerySettingsMenu.tsx",
"source:src/features/gallery/ui/GallerySplitHandle.tsx",
"source:src/features/gallery/ui/GalleryStackedLayout.tsx",
"source:src/features/gallery/ui/GalleryThumbnail.tsx",
@@ -3625,10 +3655,12 @@
"source:src/platform/ui/ModelDefaultButton.tsx",
"source:src/platform/ui/PageShell.tsx",
"source:src/platform/ui/Panel.tsx",
+ "source:src/platform/ui/PanelHeader.tsx",
"source:src/platform/ui/Picker.tsx",
"source:src/platform/ui/Popover.tsx",
"source:src/platform/ui/RenameDialog.tsx",
"source:src/platform/ui/ResizableTextarea.tsx",
+ "source:src/platform/ui/RetryBoundary.tsx",
"source:src/platform/ui/Row.tsx",
"source:src/platform/ui/Scrollable.tsx",
"source:src/platform/ui/SegmentTabs.tsx",
@@ -3649,6 +3681,7 @@
"source:src/platform/ui/hints/hintsContext.tsx",
"source:src/platform/ui/hints/index.ts",
"source:src/platform/ui/index.ts",
+ "source:src/platform/ui/settings/contracts.ts",
"source:src/platform/ui/streaming-image/StreamingImageFrame.tsx",
"source:src/platform/ui/streaming-image/streamingImageSource.ts",
"source:src/platform/ui/streaming-image/useStreamingImageSource.ts",
@@ -3972,7 +4005,11 @@
"source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
+ "source:src/workbench/settings/WidgetSettingsButton.tsx",
+ "source:src/workbench/settings/applicationContributions.ts",
+ "source:src/workbench/settings/catalog.ts",
"source:src/workbench/settings/clearWorkspaceData.ts",
+ "source:src/workbench/settings/dialogResource.ts",
"source:src/workbench/settings/settingsDialogStore.ts",
"source:src/workbench/settings/store.ts",
"source:src/workbench/shell/BottomPanel.tsx",
@@ -4048,19 +4085,23 @@
"source:src/workbench/widgets/autosave-status/implementation.ts",
"source:src/workbench/widgets/autosave-status/manifest.ts",
"source:src/workbench/widgets/canvas/bboxGrid.ts",
+ "source:src/workbench/widgets/canvas/canvasSettings.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
"source:src/workbench/widgets/canvas/invoke/canvasStrength.ts",
"source:src/workbench/widgets/canvas/manifest.ts",
+ "source:src/workbench/widgets/canvas/settingsContribution.ts",
"source:src/workbench/widgets/diagnostics/manifest.ts",
"source:src/workbench/widgets/gallery/manifest.ts",
"source:src/workbench/widgets/generate/manifest.ts",
"source:src/workbench/widgets/image-map/ImageMapDataRuntime.tsx",
"source:src/workbench/widgets/image-map/manifest.ts",
+ "source:src/workbench/widgets/image-map/settingsContribution.ts",
"source:src/workbench/widgets/layers/controlModelOptions.ts",
"source:src/workbench/widgets/layers/layerOps.ts",
"source:src/workbench/widgets/layers/manifest.ts",
"source:src/workbench/widgets/layers/panes/editorPaneLayout.ts",
"source:src/workbench/widgets/layers/selectedModel.ts",
+ "source:src/workbench/widgets/manifests.ts",
"source:src/workbench/widgets/notifications/NotificationsHeaderActions.tsx",
"source:src/workbench/widgets/notifications/NotificationsWidgetView.tsx",
"source:src/workbench/widgets/notifications/implementation.ts",
@@ -4085,6 +4126,7 @@
"source:src/workbench/widgets/preview/previewMetadata.ts",
"source:src/workbench/widgets/preview/previewNavigation.ts",
"source:src/workbench/widgets/preview/previewSettings.ts",
+ "source:src/workbench/widgets/preview/settingsContribution.ts",
"source:src/workbench/widgets/preview/useCompareLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewLoupe.ts",
"source:src/workbench/widgets/preview/usePreviewNavigation.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 6c87afd0c3..174b26ec8e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -249,7 +249,8 @@
"unknownTime": "Unknown time",
"view": "View",
"viewJson": "View JSON",
- "widgetViewUnavailable": "Widget view unavailable."
+ "widgetViewUnavailable": "Widget view unavailable.",
+ "loading": "Loading…"
},
"app": {
"name": "Invoke AI",
@@ -1484,6 +1485,141 @@
"indexOff": "The image index is not running. Terms are saved and will apply when it is next enabled.",
"saveFailed": "Could not save the vocabulary.",
"loadFailed": "Could not load the vocabulary."
+ },
+ "catalog": {
+ "themeId": {
+ "label": "Theme",
+ "description": "Choose the workbench colors."
+ },
+ "reduceMotion": {
+ "label": "Reduce motion",
+ "description": "Disable transitions and animations across the workbench."
+ },
+ "showFocusRegionHighlight": {
+ "label": "Highlight focused regions",
+ "description": "Highlight the region receiving keyboard shortcuts."
+ },
+ "autoSwitchInvocationRoute": {
+ "label": "Auto-switch Invoke route",
+ "description": "Match the Invoke source and destination to the surface you are editing. Locked routes are never changed."
+ },
+ "enableInformationalPopovers": {
+ "label": "Enable informational popovers",
+ "description": "Show educational popovers on controls that have extra guidance."
+ },
+ "enableModelDescriptions": {
+ "label": "Show model descriptions",
+ "description": "Include model descriptions in model dropdowns where available."
+ },
+ "notifyOnEnqueue": {
+ "label": "Notify when queued",
+ "description": "Show a toast for each successful enqueue. Enqueues are always recorded in the notification center."
+ },
+ "preferNumericAttentionStyle": {
+ "label": "Prefer numeric attention style",
+ "description": "Use numeric prompt attention syntax when inserting attention weights."
+ },
+ "showPromptSyntaxHighlighting": {
+ "label": "Highlight prompt syntax",
+ "description": "Color syntax in prompt fields without changing their text or validation."
+ },
+ "hotkeys": {
+ "label": "Keyboard shortcuts",
+ "description": "Find and customize keyboard shortcuts."
+ },
+ "useCpuNoise": {
+ "label": "Use CPU noise",
+ "description": "Use CPU noise generation for deterministic legacy-compatible outputs."
+ },
+ "confirmImageDeletion": {
+ "label": "Confirm image deletion",
+ "description": "Ask for confirmation before permanently deleting images."
+ },
+ "antialiasProgressImages": {
+ "label": "Antialias progress images",
+ "description": "Smooth progress previews instead of rendering them pixelated."
+ },
+ "workflowSnapToGrid": {
+ "label": "Always snap to grid",
+ "description": "Snap nodes to the grid while dragging. When off, hold Ctrl to snap temporarily."
+ },
+ "workflowShowMinimap": {
+ "label": "Show minimap",
+ "description": "Show an overview in the corner of the workflow editor."
+ },
+ "workflowValidateConnections": {
+ "label": "Validate connections",
+ "description": "Reject incompatible field connections. Disabling validation allows connections that may fail during a run."
+ },
+ "imageMapVocabulary": {
+ "label": "Vocabulary",
+ "description": "Manage the vocabulary used to organize the Image Map."
+ },
+ "developerLogEnabled": {
+ "label": "Record diagnostic logs",
+ "description": "Record selected diagnostic events in the Diagnostics widget."
+ },
+ "developerPerformanceTimingsEnabled": {
+ "label": "Collect performance timings",
+ "description": "Record workflow editing and project serialization measurements."
+ },
+ "developerLogNamespaces": {
+ "label": "Log namespaces",
+ "description": "Choose which diagnostic sources to record."
+ },
+ "generationDevices": {
+ "label": "Generation devices",
+ "description": "Server-wide accelerator selection. Changes require a server restart."
+ },
+ "workspaceActions": {
+ "label": "Data & workspace",
+ "description": "Reset the layout or permanently delete saved projects and settings."
+ },
+ "about": {
+ "label": "About InvokeAI",
+ "description": "Version, build, and server information."
+ },
+ "language": {
+ "label": "Language"
+ },
+ "workflowEdgeStyle": {
+ "label": "Connection style",
+ "description": "How connections between nodes are drawn."
+ },
+ "options": {
+ "curved": "Curved",
+ "square": "Square",
+ "activeProject": "Active project",
+ "all": "All projects",
+ "trace": "Trace",
+ "debug": "Debug",
+ "info": "Info",
+ "warn": "Warn",
+ "error": "Error",
+ "fatal": "Fatal"
+ },
+ "queueJobsScope": {
+ "label": "Show jobs from",
+ "description": "Choose which jobs the Queue widget includes in counts and lists."
+ },
+ "developerLogLevel": {
+ "label": "Log level"
+ },
+ "sections": {
+ "appearance": "Appearance",
+ "behavior": "Behavior",
+ "hotkeys": "Keyboard shortcuts",
+ "project": "Project",
+ "gallery": "Gallery",
+ "preview": "Preview",
+ "workflow": "Workflow",
+ "queue": "Queue",
+ "imageMap": "Image Map",
+ "developer": "Developer",
+ "server": "Server",
+ "workspace": "Data & workspace",
+ "about": "About"
+ }
}
},
"shell": {
@@ -3433,7 +3569,8 @@
"windowAnchored": "Showing this board from item {{index}}.",
"backToBoardTop": "Back to top",
"windowLimit": "Showing the first {{count}} items. Narrow the search or switch to Pages to reach the rest.",
- "windowLimitFrom": "Showing {{count}} items from item {{index}}. Narrow the search or switch to Pages to reach the rest."
+ "windowLimitFrom": "Showing {{count}} items from item {{index}}. Narrow the search or switch to Pages to reach the rest.",
+ "boardOrder": "Board order"
},
"queueStatus": {
"idle": "Queue idle",
@@ -3605,5 +3742,41 @@
"title": "Workflows",
"untitled": "Untitled Workflow",
"yours": "Yours"
+ },
+ "settingsDialog": {
+ "search": "Search settings…",
+ "clearSearch": "Clear search",
+ "section": "Settings section",
+ "allResults": "All results",
+ "results": "Search results",
+ "resultCount_one": "{{count}} setting found",
+ "resultCount_other": "{{count}} settings found",
+ "noResults": "No settings match your search.",
+ "openEditor": "Open editor",
+ "showInSection": "Show in section",
+ "allWidgetSettings": "All {{widget}} settings…",
+ "loadFailed": "These settings could not be loaded. Try again.",
+ "instanceUnavailable": "Open a project containing this widget to edit its settings.",
+ "projectUnavailable": "Open a project to edit these settings.",
+ "groups": {
+ "application": "Application",
+ "project": "Project",
+ "widgets": "Widgets",
+ "system": "System"
+ },
+ "scope": {
+ "preference": "Saved in your preferences",
+ "project": "Saved with this project",
+ "instance": "Saved with this widget in this project",
+ "server": "Applies to the whole server",
+ "install": "Saved for this install"
+ },
+ "fields": {
+ "comparisonMode": "Comparison mode",
+ "showClusterLabels": "Show cluster labels",
+ "clickSelectsCluster": "Select clusters on click"
+ },
+ "changedFromDefault": "Changed from default",
+ "changedSetting": "{{setting}}: changed from default"
}
}
diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
index 474fe3b984..f3b366e4eb 100644
--- a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
@@ -108,6 +108,16 @@ const failures = measurements.flatMap((measurement) =>
);
const launchpad = measurements.find((measurement) => measurement.routeId === 'launchpad');
const editor = measurements.find((measurement) => measurement.routeId === 'editor');
+// Shared settings metadata must not turn Launchpad overlays into editor boot paths.
+for (const source of [
+ 'src/workbench/palette/LaunchpadCommandPaletteDialog.tsx',
+ 'src/workbench/settings/SettingsDialog.tsx',
+]) {
+ const overlay = measureRouteBuild(manifest, chunkSourceManifest, source, source, (file) => assetCache.get(file));
+ for (const owner of ['src/app/WorkbenchApp.tsx', 'src/workbench/widget-frame/WidgetRenderer.tsx']) {
+ assert.ok(!overlay.sourceOwners.includes(`source:${owner}`), `${source} eagerly includes editor runtime ${owner}.`);
+ }
+}
const widgetImplementationSources = [...WIDGET_SOURCES.keys()];
for (const source of widgetImplementationSources) {
assert.ok(manifest[source], `Registered widget implementation ${source} is missing from the build manifest.`);
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
new file mode 100644
index 0000000000..c79c7e2f99
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
@@ -0,0 +1,26 @@
+import { readFile, readdir } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+/** Keep source locales readable while serving compact JSON at their existing URLs. */
+export const localeAssetsPlugin = ({ projectRoot }) => ({
+ apply: 'build',
+ name: 'invokeai-locale-assets',
+ async generateBundle() {
+ const directory = resolve(projectRoot, 'public/locales');
+ const entries = await readdir(directory, { withFileTypes: true });
+ for (const entry of entries) {
+ if (!entry.isFile() || !entry.name.endsWith('.json')) {
+ continue;
+ }
+ const source = await readFile(resolve(directory, entry.name), 'utf8');
+ let parsed;
+ try {
+ parsed = JSON.parse(source);
+ } catch (error) {
+ throw new Error(`Invalid locale JSON: ${entry.name}`, { cause: error });
+ }
+ // Vite copies public files before generateBundle; this replaces only the emitted locale copy.
+ this.emitFile({ type: 'asset', fileName: `locales/${entry.name}`, source: JSON.stringify(parsed) });
+ }
+ },
+});
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
new file mode 100644
index 0000000000..3d667a8beb
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import test from 'node:test';
+import { build } from 'vite';
+
+import { localeAssetsPlugin } from './locale-assets-plugin.mjs';
+
+const createFixture = async (context) => {
+ const projectRoot = await mkdtemp(resolve(tmpdir(), 'invokeai-locale-build-'));
+ context.after(() => rm(projectRoot, { recursive: true, force: true }));
+ await mkdir(resolve(projectRoot, 'public/locales'), { recursive: true });
+ await writeFile(
+ resolve(projectRoot, 'index.html'),
+ '<html><body><script type="module" src="/main.js"></script></body></html>'
+ );
+ await writeFile(resolve(projectRoot, 'main.js'), 'document.body.dataset.ready = "true";');
+ return projectRoot;
+};
+
+const buildFixture = (projectRoot) =>
+ build({
+ root: projectRoot,
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [localeAssetsPlugin({ projectRoot })],
+ });
+
+test('production locale assets replace public copies without changing Unicode, values, or source files', async (context) => {
+ const projectRoot = await createFixture(context);
+ const translations = {
+ settings: { title: '設定 🎨', description: 'Réglages — العربية', escaped: 'Line one\n"Line two"\\' },
+ list: ['中文', '{{count}} settings', ''],
+ enabled: true,
+ count: 42,
+ optional: null,
+ };
+ const formatted = `${JSON.stringify(translations, null, 2)}\n`;
+ await writeFile(resolve(projectRoot, 'public/locales/en.json'), formatted);
+ await writeFile(resolve(projectRoot, 'public/locales/ja.json'), formatted);
+ await writeFile(resolve(projectRoot, 'public/keep.txt'), ' Keep public whitespace.\n');
+
+ await buildFixture(projectRoot);
+
+ for (const language of ['en', 'ja']) {
+ const built = await readFile(resolve(projectRoot, `dist/locales/${language}.json`), 'utf8');
+ assert.deepEqual(JSON.parse(built), translations);
+ assert.equal(built, JSON.stringify(translations));
+ assert.ok(Buffer.byteLength(built) < Buffer.byteLength(formatted));
+ assert.equal(await readFile(resolve(projectRoot, `public/locales/${language}.json`), 'utf8'), formatted);
+ }
+ assert.equal(await readFile(resolve(projectRoot, 'dist/keep.txt'), 'utf8'), ' Keep public whitespace.\n');
+});
+
+test('invalid locale JSON fails the production build with the failing filename', async (context) => {
+ const projectRoot = await createFixture(context);
+ await writeFile(resolve(projectRoot, 'public/locales/broken.json'), '{ invalid');
+
+ await assert.rejects(buildFixture(projectRoot), /Invalid locale JSON: broken\.json/);
+});
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 952cc78e43..161970b31e 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -885,6 +885,73 @@ const runLayersPanesJourney = async (browser) => {
}
};
+const SETTINGS_DIALOG_SCOPE = { include: ['[data-scope="dialog"][data-part="content"]'] };
+
+const runSettingsJourney = async (browser) => {
+ const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
+ const id = 'workbench-settings';
+
+ try {
+ await waitForWorkbench(page);
+ const gear = page.getByRole('button', { exact: true, name: 'Gallery settings' });
+ await gear.click();
+ await page.getByRole('button', { exact: true, name: 'All Gallery settings…' }).click();
+ const dialog = page.getByRole('dialog', { name: /^Settings:/ });
+ await dialog.waitFor();
+ const navigation = dialog.getByRole('navigation', { exact: true, name: 'Settings' });
+ const sectionNames = await navigation.getByRole('button').allTextContents();
+ assert.equal(
+ sectionNames.length,
+ 14,
+ 'All application, project, widget, and system sections must be discoverable.'
+ );
+ for (const name of sectionNames) {
+ await navigation.getByRole('button', { exact: true, name }).click();
+ await page.getByRole('dialog', { exact: true, name: `Settings: ${name}` }).waitFor();
+ await page.waitForLoadState('networkidle');
+ await waitForSettledDocument(page);
+ // Certify the settings surface; representative surface scans retain page-wide workbench coverage.
+ await assertNoAxeViolations(page, `${id}:${name}`, SETTINGS_DIALOG_SCOPE);
+ }
+
+ const search = dialog.getByRole('textbox', { exact: true, name: 'Search settings…' });
+ await search.focus();
+ await search.pressSequentially('numeric attention');
+ const numericAttention = dialog.getByRole('checkbox', { exact: true, name: 'Prefer numeric attention style' });
+ await numericAttention.waitFor();
+ await expectFocused(search, 'Filtering settings should keep keyboard focus in search.');
+ await numericAttention.focus();
+ await numericAttention.press('Space');
+ assert.equal(await numericAttention.isChecked(), true);
+ await assertNoAxeViolations(page, `${id}:search`, SETTINGS_DIALOG_SCOPE);
+ await dialog.getByRole('button', { exact: true, name: 'Show in section' }).click();
+ await expectFocused(numericAttention, 'Revealing a setting should focus its control.');
+ await page.keyboard.press('Escape');
+ await dialog.waitFor({ state: 'hidden' });
+ await expectFocused(gear, 'Closing settings should return focus to its widget gear.');
+
+ await gear.press('Enter');
+ const popover = page.locator('[data-scope="popover"][data-part="content"][data-state="open"]');
+ await popover.waitFor();
+ await popover.evaluate(async (element) => {
+ await Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished));
+ });
+ await waitForSettledDocument(page);
+ // Quick settings are nonmodal; scan their popup independently of the workbench behind it.
+ await assertNoAxeViolations(page, `${id}:quick`, { include: ['[data-scope="popover"][data-part="content"]'] });
+ await page.keyboard.press('Escape');
+ await popover.waitFor({ state: 'hidden' });
+ await expectFocused(gear, 'Closing quick settings should restore focus to its widget gear.');
+
+ if (pageErrors.length > 0) {
+ throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
+ }
+ return { id, status: 'passed' };
+ } finally {
+ await context.close();
+ }
+};
+
const mockBackend = await startMockBackend(backendPort, { profile: 'representative' });
const preview = spawn(
'pnpm',
@@ -930,6 +997,9 @@ try {
if (!requestedJourney || requestedJourney === 'workbench-layers-panes') {
reports.push(await runLayersPanesJourney(browser));
}
+ if (!requestedJourney || requestedJourney === 'workbench-settings') {
+ reports.push(await runSettingsJourney(browser));
+ }
if (reports.length === 0) {
throw new Error(`Unknown accessibility journey ${JSON.stringify(requestedJourney)}.`);
}
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx
new file mode 100644
index 0000000000..aece24120f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx
@@ -0,0 +1,107 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
+import type { Project } from '@workbench/projectContracts';
+import type { ReactNode } from 'react';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GalleryUiAdapterProvider } from './GalleryUiAdapter';
+
+let store: ReturnType<typeof createWorkbenchStore>;
+let adapter: GalleryUiAdapter;
+let renderCount: number;
+let host: HTMLDivElement;
+let root: Root;
+const noop = () => undefined;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock('@features/gallery/react', () => ({
+ GalleryUiProvider: ({ adapter: next, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => {
+ adapter = next;
+ renderCount += 1;
+ return children;
+ },
+}));
+vi.mock('@features/queue/react', () => ({ useActiveProgressTarget: () => null }));
+vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));
+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));
+vi.mock('./GalleryImageActionsBridge', () => ({
+ GalleryItemActionsAdapter: () => null,
+ GalleryImageContextMenu: () => null,
+}));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) =>
+ useExternalStoreSelector(
+ store.subscribe,
+ store.getSnapshot,
+ (snapshot) => selector(snapshot.activeProject),
+ shallowEqual
+ ),
+ useWorkbenchCommands: () => store.commands,
+ useWorkbenchQueries: () => store.queries,
+}));
+
+const renderAdapter = async (absent: string[] = []) => {
+ const state = createInitialWorkbenchState();
+ const project = state.projects[0]!;
+ project.widgetInstances = Object.fromEntries(
+ Object.entries(project.widgetInstances).filter(([, instance]) => !absent.includes(instance.typeId))
+ );
+ store = createWorkbenchStore(state);
+ await act(() => root.render(<GalleryUiAdapterProvider>{null}</GalleryUiAdapterProvider>));
+};
+
+beforeEach(() => {
+ accountLifecycle.activate('gallery-subscription-test');
+ renderCount = 0;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+});
+
+describe('Gallery adapter subscriptions', () => {
+ it.each([['gallery'], ['generate'], ['gallery', 'generate']])(
+ 'retains the adapter during unrelated layout updates with absent widgets %j',
+ async (...absent) => {
+ await renderAdapter(absent);
+ const previousAdapter = adapter;
+ const previousRenderCount = renderCount;
+ const previousSnapshot = store.getSnapshot();
+ const nextWidth = previousSnapshot.activeProject.widgetRegions.left.sizePx + 20;
+
+ await act(() => store.commands.layout.setRegionSize('left', nextWidth));
+
+ expect(store.getSnapshot()).not.toBe(previousSnapshot);
+ expect(store.getSnapshot().activeProject.widgetRegions.left.sizePx).toBe(nextWidth);
+ expect(adapter).toBe(previousAdapter);
+ expect(renderCount).toBe(previousRenderCount);
+ }
+ );
+
+ it('publishes relevant Gallery and Generate value changes through the subscribed adapter', async () => {
+ await renderAdapter();
+ const previousAdapter = adapter;
+
+ await act(() => store.commands.gallery.updateSettings({ imageDensityPercent: 24 }));
+
+ expect(adapter).not.toBe(previousAdapter);
+ expect(adapter.galleryValues.imageDensityPercent).toBe(24);
+ const galleryAdapter = adapter;
+
+ await act(() => store.commands.widgets.patchValues('generate', { positivePrompt: 'Updated prompt' }));
+
+ expect(adapter).not.toBe(galleryAdapter);
+ expect(adapter.generateValues.positivePrompt).toBe('Updated prompt');
+ expect(adapter.galleryValues).toBe(galleryAdapter.galleryValues);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx
new file mode 100644
index 0000000000..74d613d074
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx
@@ -0,0 +1,79 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
+import type { Project } from '@workbench/projectContracts';
+import type { ReactNode } from 'react';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GalleryUiAdapterProvider } from './GalleryUiAdapter';
+
+let store: ReturnType<typeof createWorkbenchStore>;
+let adapter: GalleryUiAdapter;
+const noop = () => undefined;
+
+vi.mock('@features/gallery/react', () => ({
+ GalleryUiProvider: ({ adapter: next, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => {
+ adapter = next;
+ return children;
+ },
+}));
+vi.mock('@features/queue/react', () => ({ useActiveProgressTarget: () => null }));
+vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));
+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(store.getSnapshot().activeProject),
+ useWorkbenchCommands: () => store.commands,
+ useWorkbenchQueries: () => store.queries,
+}));
+
+const renderAdapter = () => {
+ renderToStaticMarkup(<GalleryUiAdapterProvider>{null}</GalleryUiAdapterProvider>);
+ return adapter;
+};
+const values = (projectId: string) => getProjectWidgetValues(store.queries.getProject(projectId)!, 'gallery');
+
+beforeEach(() => {
+ accountLifecycle.activate('gallery-adapter-test');
+ store = createWorkbenchStore();
+});
+afterEach(() => accountLifecycle.invalidate());
+
+describe('Gallery settings adapter ownership', () => {
+ it('updates the captured active project through the Gallery command', () => {
+ const owner = renderAdapter();
+ owner.gallery.updateSettings({ imageDensityPercent: 24, paginationMode: 'paginated' });
+
+ expect(values(owner.projectId)).toMatchObject({ imageDensityPercent: 24, paginationMode: 'paginated' });
+ });
+
+ it('rejects a retained callback after switching projects and accepts the new project binding', () => {
+ const first = renderAdapter();
+ const firstValues = values(first.projectId);
+ const secondProject = store.commands.projects.create();
+ const secondValues = values(secondProject.id);
+
+ first.gallery.updateSettings({ imageDensityPercent: 24 });
+ expect(values(first.projectId)).toEqual(firstValues);
+ expect(values(secondProject.id)).toEqual(secondValues);
+
+ const second = renderAdapter();
+ second.gallery.updateSettings({ imageDensityPercent: 12 });
+ expect(values(secondProject.id).imageDensityPercent).toBe(12);
+ expect(values(first.projectId)).toEqual(firstValues);
+ });
+
+ it('rejects retained callbacks after the account lifetime changes even with the same project id', () => {
+ const previous = renderAdapter();
+ const before = values(previous.projectId);
+ accountLifecycle.activate('gallery-adapter-test');
+
+ previous.gallery.updateSettings({ showImageDimensions: true });
+ expect(values(previous.projectId)).toEqual(before);
+
+ renderAdapter().gallery.updateSettings({ showImageDimensions: true });
+ expect(values(previous.projectId).showImageDimensions).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
index 4c4f25f7c4..aaa5d0516c 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
@@ -4,19 +4,14 @@ import type { ReactNode } from 'react';
import { GalleryUiProvider } from '@features/gallery/react';
import { useActiveProgressTarget } from '@features/queue/react';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
-import { getProjectWidgetValues } from '@workbench/widgetState';
-import {
- useActiveProjectId,
- useActiveProjectName,
- useActiveProjectSelector,
- useWidgetValuesSelector,
- useWorkbenchCommands,
-} from '@workbench/WorkbenchContext';
+import { getProjectWidgetInstance } from '@workbench/widgetState';
+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { lazy, useMemo } from 'react';
-const selectWidgetValues = (values: Record<string, unknown>): Record<string, unknown> => values;
+const EMPTY_WIDGET_VALUES: Record<string, unknown> = Object.freeze({});
const GalleryItemActionsAdapter = lazy(() =>
import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryItemActionsAdapter }))
@@ -30,15 +25,27 @@ const GalleryImageContextMenu = lazy(() =>
* the Workbench aggregate. No second adapter is expected.
*/
export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {
- const projectId = useActiveProjectId();
- const projectName = useActiveProjectName();
- const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
- const generateValues = useWidgetValuesSelector('generate', selectWidgetValues);
- const queueItems = useActiveProjectSelector((project) => project.queue.items);
- const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);
- const liveFollowEnabled = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
+ const {
+ projectId,
+ projectName,
+ galleryValues,
+ generateValues,
+ queueItems,
+ antialiasProgressImages,
+ liveFollowEnabled,
+ } = useActiveProjectSelector((project) => ({
+ projectId: project.id,
+ projectName: project.name,
+ galleryValues: getProjectWidgetInstance(project, 'gallery')?.state?.values ?? EMPTY_WIDGET_VALUES,
+ generateValues: getProjectWidgetInstance(project, 'generate')?.state?.values ?? EMPTY_WIDGET_VALUES,
+ queueItems: project.queue.items,
+ antialiasProgressImages: project.settings.antialiasProgressImages,
+ liveFollowEnabled: project.settings.showProgressImagesInViewer,
+ }));
const liveProgressTarget = useActiveProgressTarget();
const { account, gallery, notifications, widgets } = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
+ const accountScope = captureAccountScope();
const exportProject = useExportLibraryProject();
const openWorkbenchWidget = useOpenWorkbenchWidget();
// These are `lazy()` children of an adapter that only ever mounts in the
@@ -55,7 +62,14 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
},
antialiasProgressImages,
exportProject,
- gallery,
+ gallery: {
+ ...gallery,
+ updateSettings: (settings) => {
+ if (isAccountScopeCurrent(accountScope) && queries.isActiveProject(projectId)) {
+ gallery.updateSettings(settings, projectId);
+ }
+ },
+ },
galleryValues,
generateValues,
ItemActionsProvider: GalleryItemActionsAdapter,
@@ -73,6 +87,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
}),
[
account,
+ accountScope,
antialiasProgressImages,
exportProject,
gallery,
@@ -85,6 +100,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
projectId,
projectName,
queueItems,
+ queries,
widgets,
]
);
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index e4b6508f40..95af060607 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -5,7 +5,18 @@
* To publish a new entry module, add it here and cover it in dependencyPolicy.test.ts.
*/
export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[]>> = {
- gallery: ['contracts', 'launchpad', 'mediaSlot', 'paletteSearch', 'picker', 'queries', 'react', 'utility', 'widget'],
+ gallery: [
+ 'settingsContribution',
+ 'contracts',
+ 'launchpad',
+ 'mediaSlot',
+ 'paletteSearch',
+ 'picker',
+ 'queries',
+ 'react',
+ 'utility',
+ 'widget',
+ ],
generation: [
'canvasGraph',
'components',
diff --git a/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts b/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts
new file mode 100644
index 0000000000..ff1528511a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts
@@ -0,0 +1,113 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
+
+export const gallerySettingsContribution: SettingsContribution = {
+ id: 'gallery',
+ label: (t) => t('widgets.labels.gallery'),
+ fields: [
+ {
+ id: 'imageSize',
+ kind: 'slider',
+ label: (t) => t('widgets.gallery.imageSize'),
+ group: (t) => t('widgets.gallery.settingsGridSize'),
+ keywords: 'density thumbnails zoom',
+ min: 0,
+ max: 100,
+ step: 1,
+ scope: 'instance',
+ },
+ {
+ id: 'thumbnailFit',
+ kind: 'select',
+ label: (t) => t('widgets.gallery.settingsThumbnails'),
+ group: (t) => t('widgets.gallery.settingsThumbnails'),
+ options: [
+ { value: 'square', label: (t) => t('widgets.gallery.thumbnailFitSquare') },
+ { value: 'aspect', label: (t) => t('widgets.gallery.thumbnailFitAspect') },
+ ],
+ scope: 'instance',
+ },
+ {
+ id: 'showImageDimensions',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.alwaysShowDimensions'),
+ group: (t) => t('widgets.gallery.settingsThumbnails'),
+ keywords: 'width height pixels',
+ scope: 'instance',
+ },
+ {
+ id: 'showPendingItems',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.showPendingItems'),
+ group: (t) => t('widgets.gallery.settingsThumbnails'),
+ keywords: 'queue progress placeholders',
+ scope: 'instance',
+ },
+ {
+ id: 'paginationMode',
+ kind: 'select',
+ label: (t) => t('widgets.gallery.pagination'),
+ group: (t) => t('widgets.gallery.pagination'),
+ options: [
+ { value: 'infinite', label: (t) => t('widgets.gallery.infinite') },
+ { value: 'paginated', label: (t) => t('common.pages') },
+ ],
+ scope: 'instance',
+ },
+ {
+ id: 'imageOrderDir',
+ kind: 'select',
+ label: (t) => t('widgets.gallery.imageSort'),
+ group: (t) => t('widgets.gallery.pagination'),
+ options: [
+ { value: 'DESC', label: (t) => t('widgets.gallery.newest') },
+ { value: 'ASC', label: (t) => t('widgets.gallery.oldest') },
+ ],
+ scope: 'instance',
+ },
+ {
+ id: 'showDateBoards',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.dateBoards'),
+ group: (t) => t('widgets.gallery.boardVisibility'),
+ scope: 'instance',
+ },
+ {
+ id: 'showArchivedBoards',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.archivedBoards'),
+ group: (t) => t('widgets.gallery.boardVisibility'),
+ scope: 'instance',
+ },
+ {
+ id: 'showOtherProjectBoards',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.otherProjectBoards'),
+ group: (t) => t('widgets.gallery.boardVisibility'),
+ scope: 'instance',
+ },
+ {
+ id: 'boardOrderBy',
+ kind: 'select',
+ label: (t) => t('widgets.gallery.sortBoardsBy'),
+ group: (t) => t('widgets.gallery.filterAndSortBoards'),
+ options: [
+ { value: 'created_at', label: (t) => t('common.created') },
+ { value: 'board_name', label: (t) => t('common.name') },
+ ],
+ scope: 'instance',
+ },
+ {
+ id: 'boardOrderDir',
+ kind: 'select',
+ label: (t) => t('widgets.gallery.boardOrder', { defaultValue: 'Board order' }),
+ group: (t) => t('widgets.gallery.filterAndSortBoards'),
+ options: [
+ { value: 'DESC', label: (t) => t('widgets.gallery.sortBoardsDescending') },
+ { value: 'ASC', label: (t) => t('widgets.gallery.sortBoardsAscending') },
+ ],
+ scope: 'instance',
+ },
+ ],
+ quick: ['imageSize', 'thumbnailFit', 'showImageDimensions', 'showPendingItems', 'paginationMode'],
+ load: () => import('./ui/GallerySettingField').then((module) => ({ Field: module.GallerySettingField })),
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx
new file mode 100644
index 0000000000..140b81dbf7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx
@@ -0,0 +1,119 @@
+import type { GalleryUiAdapter } from '@features/gallery/react';
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { GalleryUiProvider } from '@features/gallery/react';
+import { gallerySettingsContribution } from '@features/gallery/settingsContribution';
+import { system } from '@theme/system';
+import { act, useCallback, useMemo, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { GallerySettingField } from './GallerySettingField';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ 'widgets.gallery.imageSize': 'Image size',
+ 'widgets.gallery.showPendingItems': 'Show pending items',
+ })[key] ?? key,
+ }),
+}));
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+const STALE_TARGET = { projectId: 'old-project' };
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Harness = ({ id, target }: { id: string; target?: SettingFieldProps['target'] }) => {
+ const [values, setValues] = useState<Record<string, unknown>>({ imageDensityPercent: 25 });
+ const updateSettings = useCallback(
+ (patch: Record<string, unknown>) => setValues((current) => ({ ...current, ...patch })),
+ []
+ );
+ const adapter = useMemo(
+ () => ({ gallery: { updateSettings }, galleryValues: values, projectId: 'project' }) as unknown as GalleryUiAdapter,
+ [updateSettings, values]
+ );
+ const field = gallerySettingsContribution.fields.find((entry) => entry.id === id)!;
+
+ return (
+ <ChakraProvider value={system}>
+ <GalleryUiProvider adapter={adapter}>
+ <div data-surface="quick">
+ <GallerySettingField field={field} surface="quick" target={target} />
+ </div>
+ <div data-surface="dialog">
+ <GallerySettingField field={field} surface="dialog" target={target} />
+ </div>
+ <output>{JSON.stringify(values)}</output>
+ </GalleryUiProvider>
+ </ChakraProvider>
+ );
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('Gallery settings contribution bindings', () => {
+ it('inverts persisted density and synchronizes image size across quick and dialog controls', async () => {
+ await act(() => root?.render(<Harness id="imageSize" />));
+ const quick = host?.querySelector<HTMLElement>('[data-surface="quick"] [role="slider"]');
+ const dialog = host?.querySelector<HTMLElement>('[data-surface="dialog"] [role="slider"]');
+
+ expect(quick?.getAttribute('aria-valuenow')).toBe('75');
+ expect(dialog?.getAttribute('aria-valuenow')).toBe('75');
+
+ await act(() => quick?.focus());
+ await act(() => userEvent.keyboard('{ArrowRight}'));
+
+ expect(host?.querySelector('output')?.textContent).toContain('"imageDensityPercent":24');
+ expect(dialog?.getAttribute('aria-valuenow')).toBe('76');
+ });
+
+ it('synchronizes toggle changes across presentations through the existing settings command', async () => {
+ await act(() => root?.render(<Harness id="showPendingItems" />));
+ const quick = host?.querySelector<HTMLInputElement>('[data-surface="quick"] input');
+ const dialog = host?.querySelector<HTMLInputElement>('[data-surface="dialog"] input');
+
+ expect(quick?.checked).toBe(true);
+ expect(dialog?.checked).toBe(true);
+ await act(() => quick?.click());
+
+ expect(dialog?.checked).toBe(false);
+ expect(host?.querySelector('output')?.textContent).toContain('"showPendingItems":false');
+ });
+
+ it('disables edits for a target belonging to another project', async () => {
+ await act(() => root?.render(<Harness id="showPendingItems" target={STALE_TARGET} />));
+ const quick = host?.querySelector<HTMLInputElement>('[data-surface="quick"] input');
+
+ expect(quick?.disabled).toBe(true);
+ await act(() => quick?.click());
+ expect(host?.querySelector('output')?.textContent).not.toContain('showPendingItems');
+ });
+
+ it('applies pagination changes from the quick selector to the dialog selector', async () => {
+ await act(() => root?.render(<Harness id="paginationMode" />));
+ const trigger = host?.querySelector<HTMLButtonElement>('[data-surface="quick"] [role="combobox"]');
+ await act(() => trigger?.click());
+ const option = host?.querySelector<HTMLElement>('[data-surface="quick"] [role="option"][data-value="paginated"]');
+ expect(option).not.toBeNull();
+ await act(() => option?.click());
+
+ expect(host?.querySelector('output')?.textContent).toContain('"paginationMode":"paginated"');
+ expect(host?.querySelector('[data-surface="dialog"] [role="combobox"]')?.textContent).toContain('common.pages');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx
new file mode 100644
index 0000000000..125624ca46
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx
@@ -0,0 +1,66 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { DEFAULT_GALLERY_SETTINGS, getGallerySettings } from '@features/gallery/core/settings';
+import { SettingControl } from '@platform/ui/settings/SettingControl';
+import { useCallback } from 'react';
+
+import { useGalleryUi } from './GalleryUiContext';
+
+export const GallerySettingField = ({ field, surface, target }: SettingFieldProps) => {
+ const { gallery, galleryValues, projectId } = useGalleryUi();
+ const settings = getGallerySettings(galleryValues);
+ const disabled = target?.projectId !== undefined && target.projectId !== projectId;
+ const handleChange = useCallback(
+ (value: boolean | number | string) => {
+ if (disabled) {
+ return;
+ }
+
+ if (field.id === 'imageSize' && typeof value === 'number') {
+ gallery.updateSettings({ imageDensityPercent: 100 - value });
+ } else if (field.id === 'thumbnailFit' && (value === 'square' || value === 'aspect')) {
+ gallery.updateSettings({ thumbnailFit: value });
+ } else if (field.id === 'paginationMode' && (value === 'infinite' || value === 'paginated')) {
+ gallery.updateSettings({ paginationMode: value });
+ } else if (field.id === 'boardOrderBy' && (value === 'created_at' || value === 'board_name')) {
+ gallery.updateSettings({ boardOrderBy: value });
+ } else if (
+ (field.id === 'boardOrderDir' || field.id === 'imageOrderDir') &&
+ (value === 'ASC' || value === 'DESC')
+ ) {
+ gallery.updateSettings({ [field.id]: value });
+ } else if (
+ (field.id === 'showImageDimensions' ||
+ field.id === 'showPendingItems' ||
+ field.id === 'showDateBoards' ||
+ field.id === 'showArchivedBoards' ||
+ field.id === 'showOtherProjectBoards') &&
+ typeof value === 'boolean'
+ ) {
+ gallery.updateSettings({ [field.id]: value });
+ }
+ },
+ [disabled, field.id, gallery]
+ );
+ const value =
+ field.id === 'imageSize' ? 100 - settings.imageDensityPercent : settings[field.id as keyof typeof settings];
+
+ if (typeof value !== 'boolean' && typeof value !== 'number' && typeof value !== 'string') {
+ return null;
+ }
+
+ const defaultValue =
+ field.id === 'imageSize'
+ ? 100 - DEFAULT_GALLERY_SETTINGS.imageDensityPercent
+ : DEFAULT_GALLERY_SETTINGS[field.id as keyof typeof DEFAULT_GALLERY_SETTINGS];
+ return (
+ <SettingControl
+ isModified={value !== defaultValue}
+ disabled={disabled}
+ field={field}
+ surface={surface}
+ value={value}
+ onChange={handleChange}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx
deleted file mode 100644
index 7d5151531e..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.browser.test.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { ChakraProvider } from '@chakra-ui/react';
-import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
-import { system } from '@theme/system';
-import { act } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { userEvent } from 'vitest/browser';
-
-import { GallerySettingsMenu } from './GallerySettingsMenu';
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) =>
- ({
- 'widgets.gallery.imageSize': 'Image size',
- 'widgets.gallery.settings': 'Settings',
- 'widgets.gallery.settingsGridSize': 'Grid Size',
- })[key] ?? key,
- }),
-}));
-
-const settings = { ...DEFAULT_GALLERY_SETTINGS, imageDensityPercent: 25 };
-const onUpdateSettings = vi.fn();
-let host: HTMLDivElement | null = null;
-let root: Root | null = null;
-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-const renderMenu = async () => {
- await act(() =>
- root?.render(
- <ChakraProvider value={system}>
- <GallerySettingsMenu settings={settings} onUpdateSettings={onUpdateSettings} />
- </ChakraProvider>
- )
- );
-
- const trigger = host?.querySelector<HTMLButtonElement>('button[aria-label="Settings"]');
-
- await act(async () => {
- trigger?.click();
- await Promise.resolve();
- });
-
- return trigger;
-};
-
-beforeEach(() => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- onUpdateSettings.mockClear();
-});
-
-afterEach(async () => {
- await act(() => root?.unmount());
- host?.remove();
- host = null;
- root = null;
-});
-
-describe('GallerySettingsMenu grid size', () => {
- it('presents the inverse of persisted density so higher values mean larger items', async () => {
- const trigger = await renderMenu();
- const menuContentId = trigger?.getAttribute('data-controls');
- const menuContent = menuContentId ? document.getElementById(menuContentId) : null;
-
- const slider = menuContent?.querySelector<HTMLElement>('[role="slider"][aria-label="Image size"]');
-
- expect(menuContent?.textContent).toContain('Grid Size');
- expect(menuContent?.textContent).toContain('75%');
- expect(slider?.getAttribute('aria-valuenow')).toBe('75');
-
- slider?.focus();
- await act(() => userEvent.keyboard('{ArrowRight}'));
-
- expect(onUpdateSettings).toHaveBeenLastCalledWith({ imageDensityPercent: 24 });
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx
deleted file mode 100644
index c7995b3531..0000000000
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingsMenu.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import type { GallerySettings } from '@features/gallery/core/settings';
-
-import { HStack, Icon, Menu, Portal, Slider, Stack, Switch, Text } from '@chakra-ui/react';
-import { Button, IconButton } from '@platform/ui/Button';
-import { MenuContent } from '@platform/ui/Menu';
-import { Tooltip } from '@platform/ui/Tooltip';
-import { SettingsIcon } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useMenuTriggerIds } from './galleryMenuIds';
-
-const SETTINGS_POSITIONING = { placement: 'bottom-end' } as const;
-
-/**
- * Presentation settings for the grid. Sort moved out to its own header control
- * — it is a per-look decision, not something to go hunting in a popover for.
- *
- * Driven by props rather than the widget context: the widget frame renders
- * header chrome outside the view, so in panel regions this menu mounts where
- * `useGalleryWidget` does not reach.
- */
-export const GallerySettingsMenu = ({
- settings,
- onUpdateSettings,
-}: {
- settings: GallerySettings;
- onUpdateSettings: (settings: Partial<Omit<GallerySettings, 'starredFirst'>>) => void;
-}) => {
- const { t } = useTranslation();
- const { imageDensityPercent, paginationMode, showImageDimensions, showPendingItems, thumbnailFit } = settings;
- const imageSizePercent = 100 - imageDensityPercent;
-
- const handleSizeKeyDown = useCallback((event: React.KeyboardEvent) => event.stopPropagation(), []);
- const handleSizeChange = useCallback(
- (event: { value: number[] }) =>
- onUpdateSettings({ imageDensityPercent: 100 - (event.value[0] ?? imageSizePercent) }),
- [imageSizePercent, onUpdateSettings]
- );
- const handleSquareFit = useCallback(() => onUpdateSettings({ thumbnailFit: 'square' }), [onUpdateSettings]);
- const handleAspectFit = useCallback(() => onUpdateSettings({ thumbnailFit: 'aspect' }), [onUpdateSettings]);
- const handleShowDimensionsChange = useCallback(
- (showImageDimensions: boolean) => onUpdateSettings({ showImageDimensions }),
- [onUpdateSettings]
- );
- const handleShowPendingItemsChange = useCallback(
- (showPendingItems: boolean) => onUpdateSettings({ showPendingItems }),
- [onUpdateSettings]
- );
- const handleInfinitePagination = useCallback(
- () => onUpdateSettings({ paginationMode: 'infinite' }),
- [onUpdateSettings]
- );
- const handlePaginatedPagination = useCallback(
- () => onUpdateSettings({ paginationMode: 'paginated' }),
- [onUpdateSettings]
- );
- const sizeAriaLabel = useMemo(() => [t('widgets.gallery.imageSize')], [t]);
- const sizeValue = useMemo(() => [imageSizePercent], [imageSizePercent]);
- const triggerIds = useMenuTriggerIds();
-
- return (
- <Menu.Root ids={triggerIds} positioning={SETTINGS_POSITIONING}>
- <Tooltip content={t('widgets.gallery.settings')} ids={triggerIds}>
- <Menu.Trigger asChild>
- <IconButton aria-label={t('widgets.gallery.settings')} color="fg.muted" size="2xs" variant="ghost">
- <Icon as={SettingsIcon} boxSize="3.5" />
- </IconButton>
- </Menu.Trigger>
- </Tooltip>
- <Portal>
- <Menu.Positioner>
- <MenuContent minW="14rem" p="3">
- <Stack gap="3">
- <Stack gap="2">
- <HStack justify="space-between">
- <SettingLabel>{t('widgets.gallery.settingsGridSize')}</SettingLabel>
- <Text color="fg.subtle" fontSize="2xs">
- {imageSizePercent}%
- </Text>
- </HStack>
- <Slider.Root
- aria-label={sizeAriaLabel}
- max={100}
- min={0}
- step={1}
- value={sizeValue}
- onKeyDown={handleSizeKeyDown}
- onValueChange={handleSizeChange}
- >
- <Slider.Control>
- <Slider.Track>
- <Slider.Range />
- </Slider.Track>
- <Slider.Thumbs />
- </Slider.Control>
- </Slider.Root>
- </Stack>
- <Stack gap="2">
- <SettingLabel>{t('widgets.gallery.settingsThumbnails')}</SettingLabel>
- <HStack gap="1">
- <Button
- flex="1"
- size="2xs"
- variant={thumbnailFit === 'square' ? 'solid' : 'outline'}
- onClick={handleSquareFit}
- >
- {t('widgets.gallery.thumbnailFitSquare')}
- </Button>
- <Button
- flex="1"
- size="2xs"
- variant={thumbnailFit === 'aspect' ? 'solid' : 'outline'}
- onClick={handleAspectFit}
- >
- {t('widgets.gallery.thumbnailFitAspect')}
- </Button>
- </HStack>
- <SettingSwitch
- checked={showImageDimensions}
- label={t('widgets.gallery.alwaysShowDimensions')}
- onChange={handleShowDimensionsChange}
- />
- <SettingSwitch
- checked={showPendingItems}
- label={t('widgets.gallery.showPendingItems')}
- onChange={handleShowPendingItemsChange}
- />
- </Stack>
- <Stack gap="2">
- <SettingLabel>{t('widgets.gallery.pagination')}</SettingLabel>
- <HStack gap="1">
- <Button
- flex="1"
- size="2xs"
- variant={paginationMode === 'infinite' ? 'solid' : 'outline'}
- onClick={handleInfinitePagination}
- >
- {t('widgets.gallery.infinite')}
- </Button>
- <Button
- flex="1"
- size="2xs"
- variant={paginationMode === 'paginated' ? 'solid' : 'outline'}
- onClick={handlePaginatedPagination}
- >
- {t('common.pages')}
- </Button>
- </HStack>
- </Stack>
- </Stack>
- </MenuContent>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
- );
-};
-
-const SettingSwitch = ({
- checked,
- label,
- onChange,
-}: {
- checked: boolean;
- label: string;
- onChange: (checked: boolean) => void;
-}) => {
- const handleCheckedChange = useCallback((event: { checked: boolean }) => onChange(event.checked), [onChange]);
-
- return (
- <Switch.Root checked={checked} size="sm" onCheckedChange={handleCheckedChange}>
- <Switch.HiddenInput />
- <Switch.Control>
- <Switch.Thumb />
- </Switch.Control>
- <Switch.Label fontSize="2xs">{label}</Switch.Label>
- </Switch.Root>
- );
-};
-
-const SettingLabel = ({ children }: { children: string }) => (
- <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
- {children}
- </Text>
-);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx
index c1ebf8630c..7fd48a1ccb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.browser.test.tsx
@@ -9,7 +9,7 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { GalleryWidgetHeaderActions, GalleryWidgetLabel } from './GalleryWidgetChrome';
+import { GalleryWidgetLabel } from './GalleryWidgetChrome';
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -56,7 +56,7 @@ const createAdapter = (values: Record<string, unknown>) =>
}) as unknown as GalleryUiAdapter;
const renderChrome = async (
- Component: typeof GalleryWidgetLabel | typeof GalleryWidgetHeaderActions,
+ Component: typeof GalleryWidgetLabel,
values: Record<string, unknown> = {},
region: 'center' | 'right' = 'right'
) => {
@@ -137,14 +137,3 @@ describe('GalleryWidgetLabel', () => {
expect(updateSettings).toHaveBeenCalledWith({ boardPanelCollapsed: true });
});
});
-
-describe('GalleryWidgetHeaderActions', () => {
- it('offers settings in every region, since the body renders neither (upload now lives in the toolbar)', async () => {
- for (const region of ['center', 'right'] as const) {
- await renderChrome(GalleryWidgetHeaderActions, { selectedBoardId: 'dogs' }, region);
-
- expect(host?.querySelector('button[aria-label="widgets.gallery.settings"]'), region).not.toBeNull();
- expect(host?.querySelector('button[aria-label^="widgets.gallery.upload"]'), region).toBeNull();
- }
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx
index 1b181dc301..90eac123b1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx
@@ -12,7 +12,6 @@ import { useTranslation } from 'react-i18next';
import type { GalleryWidgetProps } from './GalleryUiContext';
import { BoardCover, BoardCoverIcon } from './GalleryBoardCover';
-import { GallerySettingsMenu } from './GallerySettingsMenu';
import { getGallerySelectedBoardId } from './galleryStateView';
import { useGalleryUi } from './GalleryUiContext';
@@ -86,13 +85,3 @@ export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {
</HStack>
);
};
-
-export const GalleryWidgetHeaderActions = (_props: GalleryChromeProps) => {
- const { gallery, settings } = useGalleryChromeBoards();
-
- return (
- <HStack gap="0.5">
- <GallerySettingsMenu settings={settings} onUpdateSettings={gallery.updateSettings} />
- </HStack>
- );
-};
diff --git a/invokeai/frontend/webv2/src/features/gallery/widget.ts b/invokeai/frontend/webv2/src/features/gallery/widget.ts
index 08480b6b20..6e9059b0d2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/widget.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/widget.ts
@@ -1,3 +1,3 @@
export { GalleryWidgetFooter } from './ui/GalleryWidgetFooter';
-export { GalleryWidgetHeaderActions, GalleryWidgetLabel } from './ui/GalleryWidgetChrome';
+export { GalleryWidgetLabel } from './ui/GalleryWidgetChrome';
export { GalleryWidgetView } from './ui/GalleryWidgetView';
diff --git a/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx b/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx
new file mode 100644
index 0000000000..0d1b8c3693
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx
@@ -0,0 +1,17 @@
+import type { StackProps } from '@chakra-ui/react';
+
+import { HStack } from '@chakra-ui/react';
+
+/** Shared desktop panel chrome; callers supply identity and surface-specific actions. */
+export const PanelHeader = (props: StackProps) => (
+ <HStack
+ justify="space-between"
+ borderBottomWidth="1px"
+ borderColor="border.subtle"
+ h="10"
+ minH="10"
+ ps="3"
+ pe="2"
+ {...props}
+ />
+);
diff --git a/invokeai/frontend/webv2/src/platform/ui/RetryBoundary.tsx b/invokeai/frontend/webv2/src/platform/ui/RetryBoundary.tsx
new file mode 100644
index 0000000000..cb7ca65b87
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/RetryBoundary.tsx
@@ -0,0 +1,45 @@
+import type { ReactNode } from 'react';
+
+import { Stack, Text } from '@chakra-ui/react';
+import { Component } from 'react';
+
+import { Button } from './Button';
+
+/** Isolates a deferred editor and lets its owner reset a failed code resource. */
+export class RetryBoundary extends Component<
+ { children: ReactNode; retry: () => Promise<unknown>; message: string; retryLabel: string },
+ { failed: boolean; retrying: boolean }
+> {
+ state = { failed: false, retrying: false };
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+ handleRetry = () => {
+ if (this.state.retrying) {
+ return;
+ }
+ this.setState({ retrying: true });
+ // Enter through a promise so synchronous loader errors follow the same recovery path.
+ void Promise.resolve()
+ .then(() => this.props.retry())
+ .then(
+ () => this.setState({ failed: false, retrying: false }),
+ () => this.setState({ retrying: false })
+ );
+ };
+ render() {
+ if (!this.state.failed) {
+ return this.props.children;
+ }
+ return (
+ <Stack role="alert" gap="2" aria-busy={this.state.retrying}>
+ <Text fontSize="xs" color="fg.error">
+ {this.props.message}
+ </Text>
+ <Button size="xs" loading={this.state.retrying} onClick={this.handleRetry}>
+ {this.props.retryLabel}
+ </Button>
+ </Stack>
+ );
+ }
+}
diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/ModifiedSettingIndicator.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/ModifiedSettingIndicator.tsx
new file mode 100644
index 0000000000..58403d6a45
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/settings/ModifiedSettingIndicator.tsx
@@ -0,0 +1,21 @@
+import { Box } from '@chakra-ui/react';
+import { useTranslation } from 'react-i18next';
+
+export const ModifiedSettingIndicator = ({ label }: { label?: string }) => {
+ const { t } = useTranslation();
+ const description = label
+ ? t('settingsDialog.changedSetting', { setting: label })
+ : t('settingsDialog.changedFromDefault');
+ return (
+ <Box
+ as="span"
+ role="img"
+ aria-label={description}
+ title={description}
+ boxSize="1.5"
+ flexShrink={0}
+ borderRadius="full"
+ bg="accent.fg"
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx
new file mode 100644
index 0000000000..b884e1bcfd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx
@@ -0,0 +1,177 @@
+import { createListCollection, Field, HStack, Input, Slider, Stack, Switch, Text } from '@chakra-ui/react';
+import { Select } from '@platform/ui/Select';
+import { useCallback, useId, useMemo, type ChangeEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { SettingFieldProps } from './contracts';
+
+import { resolveSettingsText } from './contracts';
+import { ModifiedSettingIndicator } from './ModifiedSettingIndicator';
+
+export interface SettingControlProps extends Pick<SettingFieldProps, 'field' | 'surface'> {
+ value: boolean | number | string;
+ onChange: (value: boolean | number | string) => void;
+ disabled?: boolean;
+ isModified?: boolean;
+}
+
+const DIALOG_DIRECTION = { base: 'column', md: 'row' } as const;
+const DIALOG_ALIGNMENT = { base: 'stretch', md: 'center' } as const;
+const DIALOG_CONTROL_WIDTH = { base: 'full', md: '52' } as const;
+const SELECT_POSITIONING = { strategy: 'fixed', sameWidth: true, hideWhenDetached: true } as const;
+
+/** Presentation only. Normalization, persistence and side effects belong to the binding. */
+export const SettingControl = ({ field, surface, value, onChange, disabled, isModified }: SettingControlProps) => {
+ const { t } = useTranslation();
+ const descriptionId = useId();
+ const label = resolveSettingsText(field.label, t);
+ const description = surface === 'dialog' && field.description ? resolveSettingsText(field.description, t) : undefined;
+ const items = useMemo(
+ () =>
+ field.kind === 'select'
+ ? field.options.map((option) => ({ ...option, label: resolveSettingsText(option.label, t) }))
+ : [],
+ [field, t]
+ );
+ const collection = useMemo(() => createListCollection({ items }), [items]);
+ const selectValue = useMemo(() => [String(value)], [value]);
+ const sliderValue = useMemo(() => [Number(value)], [value]);
+ const sliderLabel = useMemo(() => [label], [label]);
+ const handleCheckedChange = useCallback(({ checked }: { checked: boolean }) => onChange(checked), [onChange]);
+ const handleSelectChange = useCallback(
+ ({ value: next }: { value: string[] }) => {
+ if (next[0] !== undefined) {
+ onChange(next[0]);
+ }
+ },
+ [onChange]
+ );
+ const handleSliderChange = useCallback(
+ ({ value: next }: { value: number[] }) => {
+ if (next[0] !== undefined) {
+ onChange(next[0]);
+ }
+ },
+ [onChange]
+ );
+ const handleNumberChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const next = event.currentTarget.valueAsNumber;
+ if (Number.isFinite(next)) {
+ onChange(next);
+ }
+ },
+ [onChange]
+ );
+
+ if (field.kind === 'boolean') {
+ return (
+ <Switch.Root
+ checked={value === true}
+ disabled={disabled}
+ display="flex"
+ justifyContent="space-between"
+ alignItems="center"
+ gap="4"
+ w="full"
+ size="sm"
+ onCheckedChange={handleCheckedChange}
+ >
+ <Stack gap="1">
+ <HStack gap="2">
+ <Switch.Label fontSize={surface === 'quick' ? 'xs' : 'sm'} fontWeight="500">
+ {label}
+ </Switch.Label>
+ {isModified ? <ModifiedSettingIndicator label={label} /> : null}
+ </HStack>
+ {description ? (
+ <Text id={descriptionId} color="fg.muted" fontSize="xs">
+ {description}
+ </Text>
+ ) : null}
+ </Stack>
+ <Switch.HiddenInput aria-describedby={description ? descriptionId : undefined} />
+ <Switch.Control flexShrink={0}>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Root>
+ );
+ }
+
+ return (
+ <Field.Root
+ disabled={disabled}
+ display="flex"
+ flexDirection={surface === 'quick' ? 'column' : DIALOG_DIRECTION}
+ alignItems={surface === 'quick' ? 'stretch' : DIALOG_ALIGNMENT}
+ justifyContent="space-between"
+ gap="3"
+ >
+ <Stack gap="1" flex="1">
+ <HStack gap="2">
+ <Field.Label fontSize={surface === 'quick' ? 'xs' : 'sm'} fontWeight="500">
+ {label}
+ </Field.Label>
+ {isModified ? <ModifiedSettingIndicator label={label} /> : null}
+ </HStack>
+ {description ? (
+ <Field.HelperText color="fg.muted" fontSize="xs">
+ {description}
+ </Field.HelperText>
+ ) : null}
+ </Stack>
+ {field.kind === 'select' ? (
+ <Select
+ collection={collection}
+ value={selectValue}
+ disabled={disabled}
+ size="sm"
+ w={surface === 'quick' ? 'full' : DIALOG_CONTROL_WIDTH}
+ flexShrink={0}
+ portalled={false}
+ // Fixed positioning escapes scrolling/clipped surfaces; staying inline preserves modal focus and ARIA.
+ positioning={SELECT_POSITIONING}
+ itemsMaxH="min(18rem, calc(var(--available-height) - 0.5rem))"
+ onValueChange={handleSelectChange}
+ />
+ ) : field.kind === 'slider' ? (
+ <HStack w={surface === 'quick' ? 'full' : DIALOG_CONTROL_WIDTH} gap="3" flexShrink={0}>
+ <Slider.Root
+ aria-label={sliderLabel}
+ disabled={disabled}
+ value={sliderValue}
+ min={field.min}
+ max={field.max}
+ step={field.step ?? 1}
+ flex="1"
+ size="sm"
+ onValueChange={handleSliderChange}
+ >
+ <Slider.Control>
+ <Slider.Track>
+ <Slider.Range />
+ </Slider.Track>
+ <Slider.Thumbs />
+ </Slider.Control>
+ </Slider.Root>
+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums" minW="6" textAlign="end">
+ {value}
+ </Text>
+ </HStack>
+ ) : field.kind === 'number' ? (
+ <Input
+ aria-label={label}
+ type="number"
+ min={field.min}
+ max={field.max}
+ step={field.step ?? 1}
+ value={String(value)}
+ disabled={disabled}
+ size="sm"
+ w="24"
+ onChange={handleNumberChange}
+ />
+ ) : null}
+ </Field.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx
new file mode 100644
index 0000000000..91de0439ac
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/settings/SettingsSelect.browser.test.tsx
@@ -0,0 +1,118 @@
+import { ChakraProvider, Dialog, Portal } from '@chakra-ui/react';
+import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { system } from '@theme/system';
+import { act, useCallback, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import type { SettingDefinition } from './contracts';
+
+import { SettingControl } from './SettingControl';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const LANGUAGE_FIELD: SettingDefinition = {
+ id: 'language',
+ kind: 'select',
+ label: 'Language',
+ options: WORKBENCH_LANGUAGE_OPTIONS,
+ scope: 'preference',
+};
+
+const SettingsDialog = () => {
+ const [value, setValue] = useState<boolean | number | string>('en');
+ const [open, setOpen] = useState(true);
+ const handleOpenChange = useCallback(({ open: next }: { open: boolean }) => setOpen(next), []);
+ return (
+ <ChakraProvider value={system}>
+ <button type="button">Outside dialog</button>
+ <Dialog.Root open={open} onOpenChange={handleOpenChange}>
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content h="10rem" w="26rem" overflow="hidden">
+ <Dialog.Header>
+ <Dialog.Title>Settings</Dialog.Title>
+ </Dialog.Header>
+ <Dialog.Body>
+ <Scrollable h="full">
+ <SettingControl field={LANGUAGE_FIELD} surface="dialog" value={value} onChange={setValue} />
+ <output>{value}</output>
+ </Scrollable>
+ </Dialog.Body>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ </ChakraProvider>
+ );
+};
+
+let host: HTMLDivElement;
+let root: Root;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const dialogContent = () => document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]');
+const listbox = () => document.querySelector<HTMLElement>('[data-scope="select"][data-part="content"]');
+const scrollViewport = () => listbox()?.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]');
+const language = () => page.getByRole('combobox', { name: 'Language', exact: true });
+
+beforeEach(async () => {
+ await page.viewport(900, 420);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => root.render(<SettingsDialog />));
+ await expect.element(language()).toBeVisible();
+ await expect.poll(() => dialogContent()?.getAnimations().length).toBe(0);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('settings language select', () => {
+ it('escapes a clipped dialog and bounds long options in a ScrollArea', async () => {
+ await act(() => language().click());
+ await expect.element(page.getByRole('listbox', { name: 'Language', exact: true })).toBeVisible();
+ await expect.poll(() => scrollViewport()?.clientHeight).toBeGreaterThan(0);
+ const viewport = scrollViewport()!;
+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);
+ expect(viewport.clientHeight).toBeLessThanOrEqual(288);
+ const dialogRect = dialogContent()!.getBoundingClientRect();
+ const menuRect = listbox()!.getBoundingClientRect();
+ expect(menuRect.top >= 0 && menuRect.bottom <= window.innerHeight).toBe(true);
+ expect(menuRect.top < dialogRect.top || menuRect.bottom > dialogRect.bottom).toBe(true);
+ const visiblePoint = document.elementFromPoint(menuRect.x + menuRect.width / 2, menuRect.bottom - 12);
+ expect(listbox()?.contains(visiblePoint)).toBe(true);
+ });
+
+ it('scrolls to and selects the last language with the keyboard without dismissing the dialog', async () => {
+ await act(() => language().click());
+ await expect.element(page.getByRole('listbox', { name: 'Language', exact: true })).toBeVisible();
+ await act(() => userEvent.keyboard('{End}'));
+ await expect.poll(() => scrollViewport()?.scrollTop).toBeGreaterThan(0);
+ await expect.element(page.getByRole('option', { name: '漢語', exact: true })).toBeVisible();
+ const lastOption = listbox()!.querySelector<HTMLElement>('[role="option"][data-value="zh-Hant"]')!;
+ expect(lastOption.getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ scrollViewport()!.getBoundingClientRect().bottom + 1
+ );
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.element(page.getByRole('dialog', { name: 'Settings', exact: true })).toBeVisible();
+ await expect.poll(() => dialogContent()?.querySelector('output')?.textContent).toBe('zh-Hant');
+ await expect.element(language()).toHaveFocus();
+ await act(() => userEvent.keyboard('{Tab}'));
+ expect(dialogContent()?.contains(document.activeElement)).toBe(true);
+ });
+
+ it('dismisses only the language list with Escape and retains dialog focus', async () => {
+ await act(() => language().click());
+ await expect.element(page.getByRole('listbox', { name: 'Language', exact: true })).toBeVisible();
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => listbox()?.checkVisibility() ?? false).toBe(false);
+ await expect.element(page.getByRole('dialog', { name: 'Settings', exact: true })).toBeVisible();
+ await expect.element(language()).toHaveFocus();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts b/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts
new file mode 100644
index 0000000000..7d226d71ab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/settings/contracts.ts
@@ -0,0 +1,43 @@
+import type { TFunction } from 'i18next';
+import type { ComponentType } from 'react';
+
+export type SettingsText = string | ((t: TFunction) => string);
+export const resolveSettingsText = (text: SettingsText, t: TFunction): string =>
+ typeof text === 'function' ? text(t) : text;
+
+interface SettingBase {
+ id: string;
+ label: SettingsText;
+ description?: SettingsText;
+ group?: SettingsText;
+ keywords?: string;
+ scope: 'preference' | 'project' | 'instance' | 'server' | 'none';
+}
+
+export type SettingDefinition = SettingBase &
+ (
+ | { kind: 'boolean' }
+ | { kind: 'select'; options: readonly { label: SettingsText; value: string }[] }
+ | { kind: 'number' | 'slider'; min: number; max: number; step?: number }
+ | { kind: 'custom' }
+ );
+
+export interface SettingsTarget {
+ projectId: string;
+ instanceId?: string;
+}
+
+export interface SettingFieldProps {
+ field: SettingDefinition;
+ surface: 'quick' | 'dialog';
+ target?: SettingsTarget;
+}
+
+export interface SettingsContribution {
+ id: string;
+ label: SettingsText;
+ fields: readonly SettingDefinition[];
+ /** Ordered subset of field ids. Omitted fields remain available in the dialog. */
+ quick?: readonly string[];
+ load: () => Promise<{ Field: ComponentType<SettingFieldProps> }>;
+}
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
index 8a4586615a..233675c8e1 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
@@ -1017,7 +1017,7 @@ export const themeCardRecipe = defineSlotRecipe({
gap: '0.5',
},
name: { color: 'fg', fontSize: 'sm', fontWeight: '600' },
- description: { color: 'fg.subtle', fontSize: '2xs', lineHeight: '1.3' },
+ description: { color: 'fg.muted', fontSize: '2xs', lineHeight: '1.3' },
indicator: {
alignItems: 'center',
borderRadius: 'full',
diff --git a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
index 8388753d76..eaaff167e0 100644
--- a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
@@ -6,14 +6,14 @@ import type { ImageMapPoints } from './image-map/api';
import { isHotkeyModalLayerActive, registerHotkeyModalLayer } from './hotkeys/modalLayer';
import { imageMapStore } from './image-map/imageMapStore';
import { commandPaletteStore } from './palette/paletteStore';
-import { settingsDialogStore } from './settings/settingsDialogStore';
+import { openWorkbenchSettings, settingsDialogStore } from './settings/settingsDialogStore';
import { getLayerPropertiesRequest, requestLayerProperties } from './widgets/layers/layerPropertiesRequestStore';
describe('account-owned workbench UI stores', () => {
it('synchronously removes transient UI state on account invalidation', () => {
accountLifecycle.activate('user-a');
commandPaletteStore.setSnapshot({ isOpen: true });
- settingsDialogStore.setSnapshot({ isOpen: true, sectionId: 'developer' });
+ openWorkbenchSettings('developer');
const unregisterModal = registerHotkeyModalLayer('settings');
requestLayerProperties('user-a-layer');
// Partial stand-in: the snapshot only needs to be observably non-empty.
@@ -27,7 +27,13 @@ describe('account-owned workbench UI stores', () => {
accountLifecycle.invalidate();
expect(commandPaletteStore.getSnapshot().isOpen).toBe(false);
- expect(settingsDialogStore.getSnapshot()).toEqual({ isOpen: false, sectionId: 'appearance' });
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({
+ isOpen: false,
+ sectionId: 'appearance',
+ query: '',
+ returnFocus: null,
+ });
+ expect(settingsDialogStore.getSnapshot().target).toBeUndefined();
expect(isHotkeyModalLayerActive()).toBe(false);
expect(getLayerPropertiesRequest()).toBeNull();
const imageMapSnapshot = imageMapStore.getSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/extensions/README.md b/invokeai/frontend/webv2/src/workbench/extensions/README.md
index 9714c35fc9..4ff85642dc 100644
--- a/invokeai/frontend/webv2/src/workbench/extensions/README.md
+++ b/invokeai/frontend/webv2/src/workbench/extensions/README.md
@@ -12,13 +12,14 @@ The workbench shell is now structured around widget types and widget instances.
Widgets should provide component icons, not icon IDs or import strings:
```tsx
+import type { WidgetManifest } from '@workbench/widgetContracts';
import { LayersIcon } from 'lucide-react';
+import { layerSettingsContribution } from './settingsContribution';
-export const manifest = {
+export const manifest: WidgetManifest = {
id: 'invoke.layers',
version: 1,
label: 'Layers',
- labelText: 'Layers',
icon: LayersIcon,
allowedRegions: ['right'],
allowMultiple: false,
@@ -27,12 +28,24 @@ export const manifest = {
persistence: 'project',
createInitial: () => ({}),
},
- view: LayersWidgetView,
+ load: () => import('./implementation'),
+ settings: layerSettingsContribution,
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
};
```
Third-party widgets should ship icons as JSX/SVG components in their compiled widget bundle.
+## Settings contributions
+
+The optional `settings` contribution declares fields once and exposes a `quick` array of field IDs for the compact popover. All fields appear in the widget's full settings section and participate in search. A manifest with quick fields gets a shell-rendered popover and an “All settings” link; one without quick fields opens the full section directly. Widgets without preferences omit the contribution and the gear.
+
+Field metadata includes stable IDs, localized labels, optional descriptions/groups/search aliases, control type/options, and storage scope. The deferred `load` returns a `Field` binding, which receives the field, presentation surface, and resolved project/instance target. Bindings use the owning module's reads and commands and the shared Platform `SettingControl`. They must not create a widget view or engine merely to edit a preference. Complex editors use the custom field kind and remain searchable as destinations.
+
+Optional `WidgetImplementation.settingsActions` contributes owner-rendered actions below quick preferences, such as Canvas diagnostics. These remain actions with their own availability checks rather than persisted fields. Ordinary widget header actions remain available independently of settings.
+
+The settings catalog is composed from first-party manifests, not live instance registration, so preferences remain discoverable when a widget is closed. A missing project or instance is an explicit unavailable state, not a request to create one. Settings navigation carries the originating instance and returns focus to its gear after closing.
+
## 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.
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
index ebe5c2ecd7..4157af5574 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
@@ -3,6 +3,7 @@ import type { TFunction } from 'i18next';
import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { getLayoutPresetCommandTitleOverrides } from '@workbench/layoutPresetSnapshots';
+import { settingsCatalog } from '@workbench/settings/catalog';
import { DEFAULT_PREFERENCES } from '@workbench/settings/store';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { describe, expect, it, vi } from 'vitest';
@@ -185,12 +186,58 @@ describe('buildSettingsEntries', () => {
expect(theme?.subtitle).toBe('Classic');
theme?.run();
- expect(openSettingsSection).toHaveBeenCalledWith('appearance');
+ expect(openSettingsSection).toHaveBeenCalledWith({ entryId: 'themeId', sectionId: 'appearance' });
workflowSection?.run();
expect(openSettingsSection).toHaveBeenCalledWith('workflow');
});
+ it('links deletion confirmation to Gallery while keeping its direct toggle', () => {
+ const openSettingsSection = vi.fn();
+ const patchPreferences = vi.fn();
+ const entries = buildSettingsEntries(
+ { ...DEFAULT_PREFERENCES, confirmImageDeletion: true },
+ { ...settingsEntryDeps, openSettingsSection, patchPreferences },
+ t
+ );
+ const confirmation = entries.find((entry) => entry.id === 'setting.confirmImageDeletion');
+
+ confirmation?.run();
+ expect(patchPreferences).toHaveBeenCalledWith({ confirmImageDeletion: false });
+ confirmation?.secondary?.run();
+ expect(openSettingsSection).toHaveBeenCalledWith({ entryId: 'confirmImageDeletion', sectionId: 'gallery' });
+ });
+
+ it('finds widget fields by catalog aliases and navigates to the exact entry', () => {
+ const openSettingsSection = vi.fn();
+ const entries = buildSettingsEntries(DEFAULT_PREFERENCES, { ...settingsEntryDeps, openSettingsSection }, t);
+ const rows = searchPaletteRows(entries, 'density', []);
+ const imageSize = rows.find((row) => row.kind === 'entry' && row.entry.id === 'setting.gallery.imageSize');
+
+ expect(imageSize?.kind).toBe('entry');
+ if (imageSize?.kind === 'entry') {
+ imageSize.entry.run();
+ }
+ expect(openSettingsSection).toHaveBeenCalledWith({ entryId: 'imageSize', sectionId: 'gallery' });
+ expect(entries.some((entry) => entry.id === 'settings.section.canvas')).toBe(true);
+ });
+
+ it('uses catalog translations for preference labels without loading editor resources', () => {
+ const resources = [
+ ...new Set(settingsCatalog.flatMap((section) => section.entries.map((entry) => entry.resource))),
+ ];
+ const loadSpies = resources.map((resource) => vi.spyOn(resource, 'load'));
+ const localized = ((key: string, options?: Record<string, unknown>) =>
+ key === 'settings.catalog.reduceMotion.label' ? 'Minimize animation' : t(key, options)) as TFunction;
+ const entries = buildSettingsEntries(DEFAULT_PREFERENCES, settingsEntryDeps, localized);
+
+ expect(entries.find((entry) => entry.id === 'setting.reduceMotion')?.title).toBe('Minimize animation');
+ for (const spy of loadSpies) {
+ expect(spy).not.toHaveBeenCalled();
+ spy.mockRestore();
+ }
+ });
+
it('carries a value-picker stage on enum preferences that applies and marks the current value', () => {
const patchPreferences = vi.fn();
const entries = buildSettingsEntries(
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
index c85ae39c9a..240637b464 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
@@ -1,9 +1,11 @@
import type { DateRange } from '@platform/search/dateTokens';
import type { CustomHotkeys, HotkeyDefinition } from '@workbench/hotkeys/types';
-import type { WorkbenchPreferences } from '@workbench/settings/contracts';
-import type { SettingsSectionId } from '@workbench/widgetContracts';
+import type { SettingsDestination, SettingsSectionId, WorkbenchPreferences } from '@workbench/settings/contracts';
import type { TFunction } from 'i18next';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { preferenceSettingsFields } from '@workbench/settings/applicationContributions';
+import { settingsCatalog } from '@workbench/settings/catalog';
import fuzzysort from 'fuzzysort';
import { getPaletteContributionKey } from './contributionKey';
@@ -282,37 +284,8 @@ export const buildCatalogCommandEntries = ({
// Settings source
// ---------------------------------------------------------------------------
-type BooleanPreferenceKey = {
- [Key in keyof WorkbenchPreferences]: WorkbenchPreferences[Key] extends boolean ? Key : never;
-}[keyof WorkbenchPreferences];
-
-const SETTING_TOGGLES: ReadonlyArray<{ key: BooleanPreferenceKey; keywords?: string; title: string }> = [
- { key: 'reduceMotion', keywords: 'animation appearance', title: 'Reduce Motion' },
- { key: 'confirmImageDeletion', keywords: 'delete safety', title: 'Confirm Image Deletion' },
- { key: 'showFocusRegionHighlight', keywords: 'panel outline', title: 'Show Focus Region Highlight' },
- { key: 'enableInformationalPopovers', keywords: 'help tooltips', title: 'Informational Popovers' },
- { key: 'enableModelDescriptions', keywords: 'model manager', title: 'Model Descriptions' },
- { key: 'developerLogEnabled', keywords: 'debug console', title: 'Developer Logging' },
- { key: 'workflowSnapToGrid', keywords: 'workflow editor nodes', title: 'Snap Workflow Nodes to Grid' },
- { key: 'workflowShowMinimap', keywords: 'workflow editor', title: 'Show Workflow Minimap' },
- { key: 'workflowValidateConnections', keywords: 'workflow editor edges', title: 'Validate Workflow Connections' },
-];
-
-const SETTINGS_SECTIONS: ReadonlyArray<{ id: SettingsSectionId; title: string }> = [
- { id: 'appearance', title: 'Appearance' },
- { id: 'behavior', title: 'Behavior' },
- { id: 'hotkeys', title: 'Hotkeys' },
- { id: 'project', title: 'Project' },
- { id: 'queue', title: 'Queue' },
- { id: 'workflow', title: 'Workflow' },
- { id: 'imageMap', title: 'Image Map' },
- { id: 'developer', title: 'Developer' },
- { id: 'workspace', title: 'Workspace' },
- { id: 'about', title: 'About' },
-];
-
export interface SettingsEntryDeps {
- openSettingsSection: (sectionId: SettingsSectionId) => void;
+ openSettingsSection: (destination: SettingsSectionId | SettingsDestination) => void;
patchPreferences: (patch: Partial<WorkbenchPreferences>) => unknown;
/** Transient theme preview while the Theme stage is open (no persistence). */
previewTheme?: (themeId: string) => void;
@@ -344,132 +317,119 @@ export const buildSettingsEntries = (
deps: SettingsEntryDeps,
t: TFunction
): PaletteEntry[] => {
- const toggles = SETTING_TOGGLES.map<PaletteEntry>(({ key, keywords, title }) => ({
- group: 'Settings',
- groupLabel: t('commandPalette.groups.settings'),
- id: `setting.${key}`,
- isPersistentRecent: true,
- keepOpen: true,
- keywords: keywords ? `${keywords} toggle` : 'toggle',
- run: () => deps.patchPreferences({ [key]: !preferences[key] }),
- subtitle: preferences[key] ? t('commandPalette.settings.on') : t('commandPalette.settings.off'),
- title: t(`commandPalette.settings.toggles.${key}`, { defaultValue: title }),
- }));
+ const directPreferenceIds = new Set(preferenceSettingsFields.map(({ field }) => field.id));
+ directPreferenceIds.add('themeId');
+ const preferenceEntries = preferenceSettingsFields.map<PaletteEntry>(({ field, sectionId }) => {
+ const title = resolveSettingsText(field.label, t);
+ const section = settingsCatalog.find((candidate) => candidate.id === sectionId);
+ const open = () => deps.openSettingsSection({ entryId: field.id, sectionId });
+ const value = preferences[field.id as keyof WorkbenchPreferences];
+ const entry: PaletteEntry = {
+ group: 'Settings',
+ groupLabel: t('commandPalette.groups.settings'),
+ id: `setting.${field.id}`,
+ isPersistentRecent: true,
+ keywords: [
+ section ? resolveSettingsText(section.label, t) : '',
+ field.description ? resolveSettingsText(field.description, t) : '',
+ field.keywords ?? '',
+ ].join(' '),
+ run: open,
+ secondary: { label: t('commandPalette.actions.openInSettings'), run: open },
+ title,
+ };
+ if (field.kind === 'boolean' && typeof value === 'boolean') {
+ return {
+ ...entry,
+ keepOpen: true,
+ keywords: `${entry.keywords} toggle`,
+ run: () => deps.patchPreferences({ [field.id]: !value }),
+ subtitle: value ? t('commandPalette.settings.on') : t('commandPalette.settings.off'),
+ };
+ }
+ if (field.kind === 'select') {
+ const options =
+ field.id === 'language'
+ ? deps.languageOptions
+ : field.options.map((option) => ({ ...option, label: resolveSettingsText(option.label, t) }));
+ return {
+ ...entry,
+ keywords: `${entry.keywords} ${options.map((option) => option.label).join(' ')}`,
+ stage: {
+ options: options.map((option) => ({
+ apply: () => deps.patchPreferences({ [field.id]: option.value }),
+ id: option.value,
+ isCurrent: value === option.value,
+ label: option.label,
+ })),
+ title,
+ },
+ subtitle: options.find((option) => option.value === value)?.label ?? String(value),
+ };
+ }
+ return entry;
+ });
- // Multi-value preferences push an inline value-picker stage; mod+Enter (or
- // the section deep-link rows) still reaches the full settings dialog.
- const enumEntry = ({
- id,
- keywords,
- options,
- sectionId,
- stagePreview,
- subtitle,
- title,
- }: {
- id: string;
- keywords: string;
- options: PaletteStageOption[];
- sectionId: SettingsSectionId;
- stagePreview?: Pick<PaletteStage, 'clearPreview' | 'preview'>;
- subtitle: string;
- title: string;
- }): PaletteEntry => ({
+ const themeField = settingsCatalog
+ .find((section) => section.id === 'appearance')
+ ?.entries.find(({ field }) => field.id === 'themeId')?.field;
+ const themeTitle = themeField ? resolveSettingsText(themeField.label, t) : t('commandPalette.settings.values.theme');
+ const openTheme = () => deps.openSettingsSection({ entryId: 'themeId', sectionId: 'appearance' });
+ const themeEntry: PaletteEntry = {
group: 'Settings',
groupLabel: t('commandPalette.groups.settings'),
- id,
+ id: 'setting.themeId',
isPersistentRecent: true,
- keywords,
- run: () => deps.openSettingsSection(sectionId),
- secondary: { label: t('commandPalette.actions.openInSettings'), run: () => deps.openSettingsSection(sectionId) },
- stage: { options, title, ...stagePreview },
- subtitle,
- title,
- });
-
- const enums: PaletteEntry[] = [
- enumEntry({
- id: 'setting.themeId',
- keywords: 'appearance color dark light',
+ keywords: `${themeField?.keywords ?? ''} ${themeField?.description ? resolveSettingsText(themeField.description, t) : ''} ${deps.themes.map((theme) => theme.label).join(' ')}`,
+ run: openTheme,
+ secondary: { label: t('commandPalette.actions.openInSettings'), run: openTheme },
+ stage: {
options: deps.themes.map((theme) => ({
apply: () => deps.patchPreferences({ themeId: theme.id }),
id: theme.id,
isCurrent: theme.id === preferences.themeId,
label: theme.label,
})),
- sectionId: 'appearance',
- stagePreview:
- deps.previewTheme && deps.clearThemePreview
- ? { clearPreview: deps.clearThemePreview, preview: deps.previewTheme }
- : undefined,
- subtitle: deps.themes.find((theme) => theme.id === preferences.themeId)?.label ?? preferences.themeId,
- title: t('commandPalette.settings.values.theme'),
- }),
- enumEntry({
- id: 'setting.language',
- keywords: 'locale translation',
- options: deps.languageOptions.map((language) => ({
- apply: () => deps.patchPreferences({ language: language.value }),
- id: language.value,
- isCurrent: language.value === preferences.language,
- label: language.label,
- })),
- sectionId: 'appearance',
- subtitle:
- deps.languageOptions.find((language) => language.value === preferences.language)?.label ?? preferences.language,
- title: t('commandPalette.settings.values.language'),
- }),
- enumEntry({
- id: 'setting.workflowEdgeStyle',
- keywords: 'workflow editor connections',
- options: (['curved', 'square'] as const).map((style) => ({
- apply: () => deps.patchPreferences({ workflowEdgeStyle: style }),
- id: style,
- isCurrent: style === preferences.workflowEdgeStyle,
- label:
- style === 'square' ? t('commandPalette.settings.values.square') : t('commandPalette.settings.values.curved'),
- })),
- sectionId: 'workflow',
- subtitle:
- preferences.workflowEdgeStyle === 'square'
- ? t('commandPalette.settings.values.square')
- : t('commandPalette.settings.values.curved'),
- title: t('commandPalette.settings.values.workflowEdgeStyle'),
- }),
- enumEntry({
- id: 'setting.queueJobsScope',
- keywords: 'queue filter',
- options: (['active-project', 'all'] as const).map((scope) => ({
- apply: () => deps.patchPreferences({ queueJobsScope: scope }),
- id: scope,
- isCurrent: scope === preferences.queueJobsScope,
- label:
- scope === 'all'
- ? t('commandPalette.settings.values.allProjects')
- : t('commandPalette.settings.values.activeProject'),
- })),
- sectionId: 'queue',
- subtitle:
- preferences.queueJobsScope === 'all'
- ? t('commandPalette.settings.values.allProjects')
- : t('commandPalette.settings.values.activeProject'),
- title: t('commandPalette.settings.values.queueJobsScope'),
- }),
- ];
+ title: themeTitle,
+ ...(deps.previewTheme && deps.clearThemePreview
+ ? { clearPreview: deps.clearThemePreview, preview: deps.previewTheme }
+ : {}),
+ },
+ subtitle: deps.themes.find((theme) => theme.id === preferences.themeId)?.label ?? preferences.themeId,
+ title: themeTitle,
+ };
- const sections = SETTINGS_SECTIONS.map<PaletteEntry>(({ id, title }) => ({
+ const sections = settingsCatalog.map<PaletteEntry>(({ id, label }) => ({
group: 'Settings',
groupLabel: t('commandPalette.groups.settings'),
id: `settings.section.${id}`,
isPersistentRecent: true,
keywords: 'settings preferences open',
run: () => deps.openSettingsSection(id),
- title: t('commandPalette.settings.settingsSection', {
- section: t(`commandPalette.settings.sections.${id}`, { defaultValue: title }),
- }),
+ title: t('commandPalette.settings.settingsSection', { section: resolveSettingsText(label, t) }),
}));
+ const fields = settingsCatalog.flatMap((section) =>
+ section.entries
+ .filter(({ field }) => field.scope !== 'preference' || !directPreferenceIds.has(field.id))
+ .map<PaletteEntry>(({ field }) => ({
+ group: 'Settings',
+ groupLabel: t('commandPalette.groups.settings'),
+ id: `setting.${section.id}.${field.id}`,
+ isPersistentRecent: true,
+ keywords: [
+ resolveSettingsText(section.label, t),
+ field.description ? resolveSettingsText(field.description, t) : '',
+ field.group ? resolveSettingsText(field.group, t) : '',
+ field.keywords ?? '',
+ field.kind === 'select' ? field.options.map((option) => resolveSettingsText(option.label, t)).join(' ') : '',
+ ].join(' '),
+ run: () => deps.openSettingsSection({ entryId: field.id, sectionId: section.id }),
+ subtitle: resolveSettingsText(section.label, t),
+ title: resolveSettingsText(field.label, t),
+ }))
+ );
- return [...toggles, ...enums, ...sections];
+ return [...preferenceEntries, themeEntry, ...sections, ...fields];
};
// ---------------------------------------------------------------------------
diff --git a/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx
index 1798df2947..57b59d24f7 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/AboutSettings.tsx
@@ -54,7 +54,7 @@ export const AboutSettings = () => {
</HStack>
{info.loadState === 'loading' || info.loadState === 'idle' ? (
- <HStack color="fg.subtle" gap="2">
+ <HStack color="fg.muted" gap="2">
<Spinner size="xs" />
<Text fontSize="xs">{t('settings.about.loading')}</Text>
</HStack>
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.browser.test.tsx
new file mode 100644
index 0000000000..3c143438a5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.browser.test.tsx
@@ -0,0 +1,99 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { SettingDefinition, SettingsTarget } from '@platform/ui/settings/contracts';
+import type { WorkbenchInternalStore, WorkbenchSnapshot } from '@workbench/workbenchStore';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+import { system } from '@theme/system';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ApplicationSettingField } from './ApplicationSettingField';
+
+const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useOptionalWorkbenchSelector: (selector: (snapshot: WorkbenchSnapshot) => unknown) => {
+ const store = storeRef.current!;
+ return useExternalStoreSelector(store.subscribe, store.getSnapshot, selector);
+ },
+ useOptionalWorkbenchCommands: () => storeRef.current!.commands,
+ useOptionalWorkbenchQueries: () => storeRef.current!.queries,
+}));
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({ lng: 'en', resources: {} });
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const field: SettingDefinition = { id: 'useCpuNoise', kind: 'boolean', label: 'Use CPU noise', scope: 'project' };
+let host: HTMLDivElement;
+let root: Root;
+const interact = (run: () => void) =>
+ act(async () => {
+ run();
+ await Promise.resolve();
+ });
+const renderField = async (target?: SettingsTarget) => {
+ await interact(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <ApplicationSettingField field={field} surface="dialog" target={target} />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ return host.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
+};
+
+beforeEach(() => {
+ accountLifecycle.activate('application-settings-test');
+ storeRef.current = createWorkbenchStore();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await interact(() => root.unmount());
+ host.remove();
+});
+
+describe('project settings bindings', () => {
+ it('writes to the current project and disables a field with no project target', async () => {
+ const store = storeRef.current!;
+ const target = { projectId: store.getSnapshot().activeProject.id };
+ const control = await renderField(target);
+ const initial = store.getSnapshot().activeProject.settings.useCpuNoise;
+ await interact(() => control.click());
+ expect(store.getSnapshot().activeProject.settings.useCpuNoise).toBe(!initial);
+ const unavailable = await renderField();
+ expect(unavailable.disabled).toBe(true);
+ });
+
+ it('rejects a click delivered after project switching but before the old control commits its unmount', async () => {
+ const store = storeRef.current!;
+ const target = { projectId: store.getSnapshot().activeProject.id };
+ const control = await renderField(target);
+ await interact(() => {
+ store.commands.projects.create();
+ const beforeClick = store.getSnapshot();
+ control.click();
+ expect(store.getSnapshot()).toBe(beforeClick);
+ });
+ expect(control.disabled).toBe(true);
+ });
+
+ it('rejects a click from a control owned by an expired account session', async () => {
+ const store = storeRef.current!;
+ const control = await renderField({ projectId: store.getSnapshot().activeProject.id });
+ await interact(() => {
+ accountLifecycle.activate('next-account');
+ const beforeClick = store.getSnapshot();
+ control.click();
+ expect(store.getSnapshot()).toBe(beforeClick);
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.tsx b/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.tsx
new file mode 100644
index 0000000000..9666ab41f5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/ApplicationSettingField.tsx
@@ -0,0 +1,119 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { Text } from '@chakra-ui/react';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { RetryBoundary } from '@platform/ui/RetryBoundary';
+import { SettingControl } from '@platform/ui/settings/SettingControl';
+import { createDeferredResource } from '@workbench/deferredResource';
+import {
+ useOptionalWorkbenchCommands,
+ useOptionalWorkbenchQueries,
+ useOptionalWorkbenchSelector,
+} from '@workbench/WorkbenchContext';
+import { Suspense, use, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ProjectSettings, WorkbenchPreferences } from './contracts';
+
+import {
+ DEFAULT_PREFERENCES,
+ DEFAULT_PROJECT_SETTINGS,
+ patchWorkbenchPreferences,
+ useWorkbenchPreferenceSelector,
+} from './store';
+
+const customEditorResource = createDeferredResource(() => import('./CustomSettingsEditors'));
+
+export const prepareApplicationSettings = () => customEditorResource.load();
+
+const CustomSettingField = (props: SettingFieldProps) => {
+ const { default: Editor } = use(customEditorResource.load());
+ return <Editor {...props} />;
+};
+
+export const ApplicationSettingField = (props: SettingFieldProps) => {
+ const { t } = useTranslation();
+ const fallback = useMemo(
+ () => (
+ <Text role="status" fontSize="xs" color="fg.muted">
+ {t('common.loading')}
+ </Text>
+ ),
+ [t]
+ );
+ if (props.field.kind === 'custom') {
+ return (
+ <RetryBoundary
+ retry={customEditorResource.retry}
+ message={t('settingsDialog.loadFailed')}
+ retryLabel={t('common.retry')}
+ >
+ <Suspense fallback={fallback}>
+ <CustomSettingField {...props} />
+ </Suspense>
+ </RetryBoundary>
+ );
+ }
+ return props.field.scope === 'project' ? <ProjectSettingField {...props} /> : <PreferenceSettingField {...props} />;
+};
+
+const PreferenceSettingField = ({ field, surface }: SettingFieldProps) => {
+ const [accountScope] = useState(captureAccountScope);
+ const value = useWorkbenchPreferenceSelector((preferences) => preferences[field.id as keyof WorkbenchPreferences]);
+ const onChange = useCallback(
+ (next: boolean | number | string) => {
+ if (isAccountScopeCurrent(accountScope)) {
+ void patchWorkbenchPreferences({ [field.id]: next });
+ }
+ },
+ [accountScope, field.id]
+ );
+ if (typeof value !== 'boolean' && typeof value !== 'string' && typeof value !== 'number') {
+ return null;
+ }
+ return (
+ <SettingControl
+ isModified={value !== DEFAULT_PREFERENCES[field.id as keyof WorkbenchPreferences]}
+ field={field}
+ surface={surface}
+ value={value}
+ onChange={onChange}
+ />
+ );
+};
+
+const ProjectSettingField = ({ field, surface, target }: SettingFieldProps) => {
+ const [accountScope] = useState(captureAccountScope);
+ const commands = useOptionalWorkbenchCommands();
+ const queries = useOptionalWorkbenchQueries();
+ const projectId = useOptionalWorkbenchSelector((snapshot) => snapshot.activeProject.id, null);
+ const value = useOptionalWorkbenchSelector(
+ (snapshot) => snapshot.activeProject.settings[field.id as keyof ProjectSettings],
+ false
+ );
+ const onChange = useCallback(
+ (next: boolean | number | string) => {
+ if (
+ commands &&
+ projectId &&
+ target?.projectId === projectId &&
+ queries?.isActiveProject(projectId) &&
+ isAccountScopeCurrent(accountScope) &&
+ typeof next === 'boolean'
+ ) {
+ commands.account.updateProjectPreferences({ [field.id]: next });
+ }
+ },
+ [accountScope, commands, field.id, projectId, queries, target?.projectId]
+ );
+ return (
+ <SettingControl
+ isModified={value !== DEFAULT_PROJECT_SETTINGS[field.id as keyof ProjectSettings]}
+ field={field}
+ surface={surface}
+ value={value}
+ disabled={!commands || target?.projectId !== projectId}
+ onChange={onChange}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx
new file mode 100644
index 0000000000..d65e871467
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.browser.test.tsx
@@ -0,0 +1,112 @@
+import type { SettingDefinition } from '@platform/ui/settings/contracts';
+import type * as projectsApi from '@workbench/projects/api';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { system, THEMES } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { appearanceSettings, developerSettings, hotkeysSettings } from './applicationContributions';
+import CustomSettingField from './CustomSettingsEditors';
+import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from './store';
+
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof projectsApi>()),
+ setClientStateValue: async () => {},
+}));
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ resources: { en: { translation: { settingsDialog: { changedSetting: '{{setting}} differs from its default' } } } },
+});
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement;
+let root: Root;
+const render = async (field: SettingDefinition) => {
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <CustomSettingField field={field} surface="dialog" />
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+};
+const modifiedIndicators = () => host.querySelectorAll('[role="img"][aria-label$="differs from its default"]');
+
+beforeEach(async () => {
+ accountLifecycle.activate('custom-settings-test');
+ await patchWorkbenchPreferences(DEFAULT_PREFERENCES);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+});
+
+describe('custom setting modified indicators', () => {
+ it('marks a changed theme and clears the marker when the default theme is selected', async () => {
+ await render(appearanceSettings.fields.find((field) => field.id === 'themeId')!);
+ expect(modifiedIndicators()).toHaveLength(0);
+ const alternate = THEMES.find((theme) => theme.id !== DEFAULT_PREFERENCES.themeId)!;
+ const selectTheme = async (label: string) => {
+ const button = Array.from(host.querySelectorAll('button')).find((candidate) =>
+ candidate.textContent?.startsWith(label)
+ )!;
+ await act(async () => {
+ button.click();
+ await Promise.resolve();
+ });
+ };
+ await selectTheme(alternate.label);
+ expect(getWorkbenchPreferences().themeId).toBe(alternate.id);
+ expect(modifiedIndicators()).toHaveLength(1);
+ await selectTheme(THEMES.find((theme) => theme.id === DEFAULT_PREFERENCES.themeId)!.label);
+ expect(modifiedIndicators()).toHaveLength(0);
+ });
+
+ it('marks a changed namespace selection and clears the marker after restoring that checkbox', async () => {
+ await render(developerSettings.fields.find((field) => field.id === 'developerLogNamespaces')!);
+ expect(modifiedIndicators()).toHaveLength(0);
+ const checkbox = host.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
+ const initial = checkbox.checked;
+ await act(async () => {
+ checkbox.click();
+ await Promise.resolve();
+ });
+ expect(checkbox.checked).toBe(!initial);
+ expect(modifiedIndicators()).toHaveLength(1);
+ await act(async () => {
+ checkbox.click();
+ await Promise.resolve();
+ });
+ expect(modifiedIndicators()).toHaveLength(0);
+ });
+
+ it('marks a disabled shortcut but does not mark an explicit binding equal to its declared default', async () => {
+ const errorSpy = vi.spyOn(console, 'error');
+ await patchWorkbenchPreferences({ customHotkeys: { 'app.openCommandPalette': ['mod+k'] } });
+ await render(hotkeysSettings.fields[0]!);
+ await expect.poll(() => host.textContent).toContain('Open Command Palette');
+ expect(modifiedIndicators()).toHaveLength(0);
+ await act(() => patchWorkbenchPreferences({ customHotkeys: { 'app.openCommandPalette': [] } }));
+ await expect.poll(() => modifiedIndicators().length).toBe(1);
+ expect(modifiedIndicators()[0]!.getAttribute('aria-label')).toBe('Open Command Palette differs from its default');
+ await act(() => patchWorkbenchPreferences({ customHotkeys: {} }));
+ expect(modifiedIndicators()).toHaveLength(0);
+ const snapshotWarnings = errorSpy.mock.calls.filter(([message]) =>
+ String(message).includes('getSnapshot should be cached')
+ );
+ errorSpy.mockRestore();
+ expect(snapshotWarnings).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
new file mode 100644
index 0000000000..4f70443e76
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
@@ -0,0 +1,276 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+import type { WorkbenchThemeId } from '@theme/themes';
+import type { DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
+
+import { Box, chakra, Checkbox, Flex, HStack, Icon, SimpleGrid, Stack, Text, useSlotRecipe } from '@chakra-ui/react';
+import { Button, ConfirmDialog } from '@platform/ui';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';
+import { themeCardRecipe } from '@theme/recipes';
+import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';
+import { clearAllWorkbenchData } from '@workbench/projects/syncedPersistence';
+import { useOptionalWorkbenchCommands, useOptionalWorkbenchPersistenceService } from '@workbench/WorkbenchContext';
+import { CheckIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';
+import { useCallback, useMemo, useState, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AboutSettings } from './AboutSettings';
+import { clearWorkspaceData, rememberWorkspaceClearFailure } from './clearWorkspaceData';
+import { GenerationDevicesSettings } from './GenerationDevicesSettings';
+import { HotkeysSettingsSection } from './HotkeysSettingsSection';
+import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';
+import {
+ clearWorkbenchSettings,
+ DEFAULT_PREFERENCES,
+ DEVELOPER_LOG_NAMESPACES,
+ patchWorkbenchPreferences,
+ useWorkbenchPreferenceSelector,
+ useWorkbenchSettingsSelector,
+} from './store';
+
+const THEME_GRID_COLUMNS = { base: 2, md: 3 };
+const DEVELOPER_GRID_COLUMNS = { base: 1, md: 2 };
+const DANGER_BUTTON_HOVER_STYLES = { bg: 'fg.error', color: 'bg.subtle' };
+
+export const ThemeSettings = () => {
+ const themeId = useWorkbenchPreferenceSelector((preferences) => preferences.themeId);
+ const selectTheme = useCallback((nextThemeId: WorkbenchThemeId) => {
+ void patchWorkbenchPreferences({ themeId: nextThemeId });
+ }, []);
+
+ return (
+ <SimpleGrid columns={THEME_GRID_COLUMNS} gap="3">
+ {THEMES.map((theme) => (
+ <ThemeCard key={theme.id} selected={theme.id === themeId} theme={theme} onSelect={selectTheme} />
+ ))}
+ </SimpleGrid>
+ );
+};
+
+const ThemeCard = ({
+ onSelect,
+ selected,
+ theme,
+}: {
+ onSelect: (themeId: WorkbenchThemeId) => void;
+ selected: boolean;
+ theme: ThemeDefinition;
+}) => {
+ const recipe = useSlotRecipe({ recipe: themeCardRecipe });
+ const styles = recipe({ selected });
+ const [surface, control, brandColor, accentColor] = previewSwatches(theme);
+ const handleSelect = useCallback(() => onSelect(theme.id), [onSelect, theme.id]);
+
+ return (
+ <chakra.button type="button" aria-pressed={selected} css={styles.root} onClick={handleSelect}>
+ <Flex css={styles.preview}>
+ <Box css={styles.swatch} bg={surface} />
+ <Box css={styles.swatch} bg={control} />
+ <Box css={styles.swatch} bg={brandColor} />
+ <Box css={styles.swatch} bg={accentColor} />
+ </Flex>
+ <Box css={styles.body}>
+ <HStack justify="space-between" w="full">
+ <Text css={styles.name}>{theme.label}</Text>
+ <Box css={styles.indicator}>
+ <Icon as={CheckIcon} boxSize="3" />
+ </Box>
+ </HStack>
+ <Text css={styles.description}>{theme.description}</Text>
+ </Box>
+ </chakra.button>
+ );
+};
+
+export const DeveloperNamespacesSettings = () => {
+ const developerLogNamespaces = useWorkbenchPreferenceSelector((preferences) => preferences.developerLogNamespaces);
+ const enabledNamespaces = useMemo(() => new Set(developerLogNamespaces), [developerLogNamespaces]);
+ const toggleNamespace = useCallback(
+ (namespace: DeveloperLogNamespace, checked: boolean) => {
+ const next = checked
+ ? [...developerLogNamespaces, namespace]
+ : developerLogNamespaces.filter((candidate) => candidate !== namespace);
+
+ void patchWorkbenchPreferences({
+ developerLogNamespaces: DEVELOPER_LOG_NAMESPACES.filter((candidate) => next.includes(candidate)),
+ });
+ },
+ [developerLogNamespaces]
+ );
+
+ return (
+ <SimpleGrid columns={DEVELOPER_GRID_COLUMNS} gap="2">
+ {DEVELOPER_LOG_NAMESPACES.map((namespace) => (
+ <DeveloperNamespaceCheckbox
+ key={namespace}
+ checked={enabledNamespaces.has(namespace)}
+ namespace={namespace}
+ toggleNamespace={toggleNamespace}
+ />
+ ))}
+ </SimpleGrid>
+ );
+};
+
+const DeveloperNamespaceCheckbox = ({
+ checked,
+ namespace,
+ toggleNamespace,
+}: {
+ checked: boolean;
+ namespace: DeveloperLogNamespace;
+ toggleNamespace: (namespace: DeveloperLogNamespace, checked: boolean) => void;
+}) => {
+ const handleCheckedChange = useCallback(
+ (event: { checked: boolean | 'indeterminate' }) => toggleNamespace(namespace, event.checked === true),
+ [namespace, toggleNamespace]
+ );
+
+ return (
+ <Checkbox.Root checked={checked} size="sm" onCheckedChange={handleCheckedChange}>
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label color="fg.muted" fontSize="xs">
+ {formatSettingLabel(namespace)}
+ </Checkbox.Label>
+ </Checkbox.Root>
+ );
+};
+
+export const WorkspaceSettings = () => {
+ const commands = useOptionalWorkbenchCommands();
+ const mountedPersistence = useOptionalWorkbenchPersistenceService();
+ const scope = useWorkbenchSettingsSelector((snapshot) => snapshot.scope);
+ const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);
+
+ const clearSavedData = useCallback(async () => {
+ const failures = await clearWorkspaceData(
+ () => (mountedPersistence ? mountedPersistence.clearWorkbench() : clearAllWorkbenchData()),
+ clearWorkbenchSettings
+ );
+ if (failures.length === 0) {
+ window.location.reload();
+ return;
+ }
+ const message = failures.includes('projects')
+ ? 'Saved project data could not be fully cleared. Reloading to restore a consistent workspace.'
+ : 'Projects were cleared, but some local settings could not be. Reloading the workspace.';
+ rememberWorkspaceClearFailure(message, window.sessionStorage);
+ commands?.notifications.reportError({ area: 'workspace-clear', message, namespace: 'system' });
+ window.location.reload();
+ }, [commands, mountedPersistence]);
+ const resetLayout = useCallback(() => commands?.layout.reset(), [commands]);
+ const openClearConfirm = useCallback(() => setIsClearConfirmOpen(true), []);
+ const closeClearConfirm = useCallback(() => setIsClearConfirmOpen(false), []);
+
+ return (
+ <Stack gap="3">
+ <HStack gap="2" wrap="wrap">
+ {commands ? (
+ <Button size="sm" variant="outline" onClick={resetLayout}>
+ <RotateCcwIcon />
+ Reset layout
+ </Button>
+ ) : null}
+ <Button
+ borderColor="border.emphasized"
+ color="fg.error"
+ size="sm"
+ variant="outline"
+ _hover={DANGER_BUTTON_HOVER_STYLES}
+ onClick={openClearConfirm}
+ >
+ <Trash2Icon />
+ Clear saved data…
+ </Button>
+ </HStack>
+ <ConfirmDialog
+ body={
+ scope === 'user'
+ ? 'This permanently deletes all projects and settings for your account on this server. It cannot be undone.'
+ : 'This permanently deletes all projects and settings for this install. It cannot be undone.'
+ }
+ confirmLabel="Delete everything"
+ isOpen={isClearConfirmOpen}
+ title="Clear saved data?"
+ onClose={closeClearConfirm}
+ onConfirm={clearSavedData}
+ />
+ </Stack>
+ );
+};
+
+const formatSettingLabel = (value: string): string =>
+ value
+ .split('-')
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ');
+
+const CustomSettingField = ({ field }: SettingFieldProps) => {
+ const { t } = useTranslation();
+ const isModified = useWorkbenchPreferenceSelector((preferences) => {
+ if (field.id === 'themeId') {
+ return preferences.themeId !== DEFAULT_PREFERENCES.themeId;
+ }
+ if (field.id === 'developerLogNamespaces') {
+ return DEVELOPER_LOG_NAMESPACES.some(
+ (namespace) =>
+ preferences.developerLogNamespaces.includes(namespace) !==
+ DEFAULT_PREFERENCES.developerLogNamespaces.includes(namespace)
+ );
+ }
+ return false;
+ });
+ let editor: ReactNode;
+
+ switch (field.id) {
+ case 'themeId':
+ editor = <ThemeSettings />;
+ break;
+ case 'developerLogNamespaces':
+ editor = <DeveloperNamespacesSettings />;
+ break;
+ case 'workspaceActions':
+ editor = <WorkspaceSettings />;
+ break;
+ case 'about':
+ editor = <AboutSettings />;
+ break;
+ case 'generationDevices':
+ editor = <GenerationDevicesSettings />;
+ break;
+ case 'hotkeys':
+ // The hotkey editor owns its heading and needs a bounded viewport for its virtual list.
+ return (
+ <Box h="32rem" maxH="calc(100dvh - 15rem)" minH="16rem">
+ <HotkeysSettingsSection />
+ </Box>
+ );
+ case 'imageMapVocabulary':
+ editor = <ImageMapVocabularySettings />;
+ break;
+ default:
+ return null;
+ }
+
+ return (
+ <Stack gap="3" w="full">
+ <Stack gap="1">
+ <HStack gap="2">
+ <Text color="fg" fontSize="sm" fontWeight="500">
+ {resolveSettingsText(field.label, t)}
+ </Text>
+ {isModified ? <ModifiedSettingIndicator label={resolveSettingsText(field.label, t)} /> : null}
+ </HStack>
+ {field.description ? (
+ <Text color="fg.muted" fontSize="xs">
+ {resolveSettingsText(field.description, t)}
+ </Text>
+ ) : null}
+ </Stack>
+ {editor}
+ </Stack>
+ );
+};
+
+export default CustomSettingField;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx
index 1ae64d82c2..b4d2f31b5d 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.browser.test.tsx
@@ -2,8 +2,10 @@ import type { GenerationDevicesSnapshot } from '@features/queue/devices';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
+import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
@@ -43,6 +45,12 @@ const TWO_GPUS = [
{ device: 'cuda:1', name: 'RTX 4090' },
];
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ resources: { en: { translation: { settingsDialog: { changedSetting: '{{setting}} differs from its default' } } } },
+});
+
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -53,7 +61,9 @@ const render = async (snapshot: Partial<GenerationDevicesSnapshot>): Promise<voi
await act(() => {
root?.render(
<ChakraProvider value={system}>
- <GenerationDevicesSettings />
+ <I18nextProvider i18n={i18n}>
+ <GenerationDevicesSettings />
+ </I18nextProvider>
</ChakraProvider>
);
});
@@ -109,10 +119,19 @@ describe('GenerationDevicesSettings', () => {
expect(host?.querySelectorAll('input[type="checkbox"]')).toHaveLength(3);
});
+ it('marks explicit device lists as changed and removes the marker when auto is restored', async () => {
+ await render({ options: TWO_GPUS, setting: ['cuda:0', 'cuda:1'] });
+ expect(host?.querySelectorAll('[role="img"][aria-label$="differs from its default"]')).toHaveLength(1);
+ await render({ options: TWO_GPUS, setting: 'auto' });
+ expect(host?.querySelector('[role="img"][aria-label$="differs from its default"]')).toBeNull();
+ await render({ loadState: 'loading', options: TWO_GPUS, setting: ['cuda:0'] });
+ expect(host?.querySelector('[role="img"][aria-label$="differs from its default"]')).toBeNull();
+ });
+
it('saves the devices in effect when auto is turned off, changing nothing else', async () => {
await render({ options: TWO_GPUS, setting: 'auto' });
- await userEvent.click(switchControls()[0]!);
+ await act(() => userEvent.click(switchControls()[0]!));
// Leaving auto must not silently narrow the device set.
expect(mocks.updateGenerationDevices).toHaveBeenCalledWith(['cuda:0', 'cuda:1']);
@@ -123,7 +142,7 @@ describe('GenerationDevicesSettings', () => {
expect(host?.textContent).not.toContain('Restart InvokeAI');
- await userEvent.click(switchControls()[0]!);
+ await act(() => userEvent.click(switchControls()[0]!));
expect(host?.textContent).toContain('Restart InvokeAI for changes to take effect.');
});
@@ -134,7 +153,7 @@ describe('GenerationDevicesSettings', () => {
// Index 0 is the auto switch; the per-device switches follow in device order, so
// index 2 is cuda:1 — the only selected device. Turning it off would write an
// empty list, which the backend rejects and which would fail the next startup.
- await userEvent.click(switchControls()[2]!);
+ await act(() => userEvent.click(switchControls()[2]!));
expect(mocks.updateGenerationDevices).not.toHaveBeenCalled();
expect(host?.textContent).toContain('Select at least one generation device.');
@@ -147,6 +166,9 @@ describe('GenerationDevicesSettings', () => {
expect(host?.textContent).toContain('RTX 4090');
expect(host?.textContent).toContain('Only an administrator can change which accelerators are used.');
expect(host?.querySelectorAll('input[type="checkbox"]')).toHaveLength(0);
+ expect(
+ host?.querySelector('[role="img"][aria-label="Generation devices differs from its default"]')
+ ).not.toBeNull();
});
it('surfaces a load failure instead of rendering empty controls', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx
index 10ee31fb0a..e7ad0bee5f 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/GenerationDevicesSettings.tsx
@@ -1,6 +1,6 @@
import type { GenerationDevicesSetting } from '@features/queue/devices';
-import { Spinner, Stack, Switch, Text } from '@chakra-ui/react';
+import { HStack, Spinner, Stack, Switch, Text } from '@chakra-ui/react';
import { useCapabilities } from '@features/identity';
import {
getDeviceNameLabels,
@@ -9,6 +9,7 @@ import {
useGenerationDevices,
} from '@features/queue/devices';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';
import { useCallback, useMemo, useState } from 'react';
/**
@@ -88,23 +89,29 @@ export const GenerationDevicesSettings = () => {
if (options.length <= 1) {
return (
- <Text color="fg.subtle" fontSize="xs">
- {options.length === 1
- ? `Generation runs on ${labels[options[0].device] ?? options[0].device}. Parallel generation needs more than one accelerator.`
- : 'No accelerators were detected, so generation runs on a single device.'}
- </Text>
+ <HStack align="start" gap="2">
+ <Text color="fg.muted" fontSize="xs">
+ {options.length === 1
+ ? `Generation runs on ${labels[options[0].device] ?? options[0].device}. Parallel generation needs more than one accelerator.`
+ : 'No accelerators were detected, so generation runs on a single device.'}
+ </Text>
+ {!isAuto ? <ModifiedSettingIndicator label="Generation devices" /> : null}
+ </HStack>
);
}
if (!canManageAppConfig) {
return (
<Stack gap="1">
- <Text color="fg" fontSize="xs">
- {isAuto
- ? 'Every available accelerator is used for generation.'
- : selectedDevices.map((device) => labels[device] ?? device).join(', ')}
- </Text>
- <Text color="fg.subtle" fontSize="xs">
+ <HStack gap="2">
+ <Text color="fg" fontSize="xs">
+ {isAuto
+ ? 'Every available accelerator is used for generation.'
+ : selectedDevices.map((device) => labels[device] ?? device).join(', ')}
+ </Text>
+ {!isAuto ? <ModifiedSettingIndicator label="Generation devices" /> : null}
+ </HStack>
+ <Text color="fg.muted" fontSize="xs">
Only an administrator can change which accelerators are used.
</Text>
</Stack>
@@ -117,6 +124,7 @@ export const GenerationDevicesSettings = () => {
checked={isAuto}
description="New accelerators are picked up automatically."
label="Use every available accelerator"
+ isModified={!isAuto}
onChange={toggleAuto}
/>
{isAuto ? null : (
@@ -138,7 +146,7 @@ export const GenerationDevicesSettings = () => {
</Text>
) : null}
{didChange ? (
- <Text color="fg.subtle" fontSize="xs">
+ <Text color="fg.muted" fontSize="xs">
Restart InvokeAI for changes to take effect.
</Text>
) : null}
@@ -175,11 +183,13 @@ const DeviceSwitch = ({
checked,
description,
label,
+ isModified,
onChange,
}: {
checked: boolean;
description?: string;
label: string;
+ isModified?: boolean;
onChange: (checked: boolean) => void;
}) => {
const handleCheckedChange = useCallback(
@@ -198,11 +208,14 @@ const DeviceSwitch = ({
onCheckedChange={handleCheckedChange}
>
<Stack gap="0.5">
- <Switch.Label color="fg" fontSize="sm" fontWeight="500">
- {label}
- </Switch.Label>
+ <HStack gap="2">
+ <Switch.Label color="fg" fontSize="sm" fontWeight="500">
+ {label}
+ </Switch.Label>
+ {isModified ? <ModifiedSettingIndicator label={label} /> : null}
+ </HStack>
{description ? (
- <Text color="fg.subtle" fontSize="xs">
+ <Text color="fg.muted" fontSize="xs">
{description}
</Text>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx
index b215fae051..1ad7c126c8 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx
@@ -2,6 +2,7 @@ import type { HotkeyCategory, HotkeyDefinition } from '@workbench/hotkeys';
import { Badge, Box, Flex, HStack, Icon, Input, InputGroup, Kbd, ScrollArea, Stack, Text } from '@chakra-ui/react';
import { Button, IconButton } from '@platform/ui';
+import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';
import {
firstPartyHotkeyCatalog,
formatHotkeyForPlatform,
@@ -10,7 +11,7 @@ import {
useExtensionHotkeyDefinitions,
} from '@workbench/hotkeys';
import { ShortcutKeyGlyph } from '@workbench/hotkeys/keyGlyphs';
-import { patchWorkbenchPreferences, useWorkbenchPreferences } from '@workbench/settings/store';
+import { patchWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { CheckIcon, PlusIcon, RotateCcwIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';
import { Fragment, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
import { useVirtualizer } from 'react-hook-tanstack-virtual';
@@ -34,6 +35,13 @@ const CATEGORY_ORDER: HotkeyCategory[] = ['app', 'canvas', 'workflows', 'viewer'
const SEARCH_START_ELEMENT = <Icon as={SearchIcon} boxSize="3.5" />;
+// Virtualizer internals mutate while computing a range; subscribe only to rendered values.
+const selectVirtualRows = ({
+ measureElement,
+ totalSize,
+ virtualItems,
+}: ReturnType<typeof useVirtualizer<HTMLDivElement, HTMLElement>>) => ({ measureElement, totalSize, virtualItems });
+
const normalizeKeys = (keys: string[]): string[] => keys.map(normalizeHotkeyString).filter(Boolean);
const titleFromId = (id: string): string =>
@@ -164,7 +172,7 @@ const buildRows = ({
export const HotkeysSettingsSection = () => {
const { t } = useTranslation();
- const { customHotkeys } = useWorkbenchPreferences();
+ const customHotkeys = useWorkbenchPreferenceSelector((preferences) => preferences.customHotkeys);
const extensionHotkeys = useExtensionHotkeyDefinitions();
const [searchTerm, setSearchTerm] = useState('');
const deferredSearchTerm = useDeferredValue(searchTerm);
@@ -176,13 +184,16 @@ export const HotkeysSettingsSection = () => {
);
const conflictMap = useMemo(() => buildConflictMap(catalog, customHotkeys), [catalog, customHotkeys]);
const modifiedCount = Object.keys(customHotkeys).length;
- const virtualizer = useVirtualizer({
- count: rows.length,
- estimateSize: (index) => (rows[index]?.kind === 'category' ? 36 : 86),
- getScrollElement: () => scrollRef.current,
- measureElement: (element) => element.getBoundingClientRect().height,
- overscan: 8,
- });
+ const virtualizer = useVirtualizer(
+ {
+ count: rows.length,
+ estimateSize: (index) => (rows[index]?.kind === 'category' ? 36 : 86),
+ getScrollElement: () => scrollRef.current,
+ measureElement: (element) => element.getBoundingClientRect().height,
+ overscan: 8,
+ },
+ selectVirtualRows
+ );
const saveHotkey = useCallback(
(hotkeyId: string, keys: string[]) => {
@@ -217,7 +228,7 @@ export const HotkeysSettingsSection = () => {
<Text color="fg" fontSize="sm" fontWeight="600">
{t('hotkeys.title')}
</Text>
- <Text color="fg.subtle" fontSize="xs">
+ <Text color="fg.muted" fontSize="xs">
{t('hotkeys.description')}
</Text>
</Stack>
@@ -359,6 +370,9 @@ const HotkeyListRow = ({
.flatMap((key) => conflictMap.get(key) ?? [])
.find((entry) => entry.hotkey.id !== hotkey.id && canScopesOverlap(hotkey, entry.hotkey));
const canSave = !hasDuplicate && !conflict && (isDirty || isEditing);
+ const defaultKeys = normalizeKeys(hotkey.defaultKeys);
+ const isModified =
+ effectiveKeys.length !== defaultKeys.length || effectiveKeys.some((key) => !defaultKeys.includes(key));
const updateDraftKey = useCallback((index: number, key: string) => {
setDraftKeys((current) => current.map((candidate, candidateIndex) => (candidateIndex === index ? key : candidate)));
@@ -407,13 +421,9 @@ const HotkeyListRow = ({
{t('hotkeys.pending')}
</Badge>
) : null}
- {isCustomized ? (
- <Badge colorPalette="blue" size="xs" variant="surface">
- {t('hotkeys.custom')}
- </Badge>
- ) : null}
+ {isModified ? <ModifiedSettingIndicator label={getHotkeyTitle(hotkey)} /> : null}
</HStack>
- <Text color="fg.subtle" fontSize="2xs" truncate>
+ <Text color="fg.muted" fontSize="2xs" truncate>
{hotkey.description ?? hotkey.id}
</Text>
{conflict ? (
@@ -442,7 +452,7 @@ const HotkeyListRow = ({
/>
))
) : (
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{t('hotkeys.disabled')}
</Text>
)}
@@ -561,7 +571,7 @@ const HotkeyChip = ({
<ShortcutKeyGlyph fallback={part} part={part} />
</Kbd>
{index < parts.length - 1 ? (
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
+
</Text>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
index 00903afdc7..5439de0622 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
@@ -225,7 +225,7 @@ export const ImageMapVocabularySettings = () => {
</HStack>
</Field>
) : (
- <Text color="fg.subtle" fontSize="xs">
+ <Text color="fg.muted" fontSize="xs">
{t('settings.imageMapVocabulary.adminOnly')}
</Text>
)}
@@ -252,7 +252,7 @@ export const ImageMapVocabularySettings = () => {
))}
</Wrap>
) : (
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{t('settings.imageMapVocabulary.noTermsYet')}
</Text>
)}
@@ -295,13 +295,13 @@ const VocabularyStatusLine = ({
return (
<Stack gap="1">
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{t('settings.imageMapVocabulary.count', { count: vocab.terms.length, max: vocab.maxTerms })}
</Text>
{vocab.state === 'building' ? (
<HStack gap="1.5">
<Spinner size="xs" />
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{progress
? t('settings.imageMapVocabulary.rebuildingQueued', { progress: progress.counts })
: t('settings.imageMapVocabulary.rebuilding')}
@@ -321,7 +321,7 @@ const VocabularyStatusLine = ({
</HStack>
) : null}
{vocab.state === 'unavailable' ? (
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{t('settings.imageMapVocabulary.indexOff')}
</Text>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx
index a7b4d0b6f2..1a378455c9 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsButton.tsx
@@ -1,19 +1,18 @@
import { IconButton } from '@platform/ui/Button';
import { Tooltip } from '@platform/ui/Tooltip';
import { SettingsIcon } from 'lucide-react';
-import { useCallback } from 'react';
import { SettingsDialogHost } from './SettingsDialogHost';
import { openWorkbenchSettings } from './settingsDialogStore';
+const handleOpen = () => openWorkbenchSettings();
+
/**
* The Launchpad's settings entry point, kept deliberately thin. The workbench
* shell opens settings from its app menu instead and mounts
* {@link SettingsDialogHost} on its own.
*/
export const SettingsButton = () => {
- const handleOpen = useCallback(() => openWorkbenchSettings(), []);
-
return (
<>
<Tooltip content="Settings">
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx
new file mode 100644
index 0000000000..4f49f2c164
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx
@@ -0,0 +1,315 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+import type * as projectsApi from '@workbench/projects/api';
+import type { WidgetRuntimeApi, WidgetViewProps } from '@workbench/widgetContracts';
+import type * as workbenchContext from '@workbench/WorkbenchContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { system } from '@theme/system';
+import { queueWidgetManifest } from '@workbench/widgets/queue/manifest';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+import { appearanceSettings } from './applicationContributions';
+import { SettingsDialogHost } from './SettingsDialogHost';
+import {
+ closeWorkbenchSettings,
+ getSettingsSectionScroll,
+ openWorkbenchSettings,
+ settingsDialogStore,
+} from './settingsDialogStore';
+import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from './store';
+import { WidgetSettingsButton } from './WidgetSettingsButton';
+
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof projectsApi>()),
+ setClientStateValue: async () => {},
+}));
+
+vi.mock('./CustomSettingsEditors', () => ({
+ default: ({ field }: SettingFieldProps) => <div data-custom-editor={field.id}>Custom settings editor</div>,
+}));
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
+ useActiveProjectId: () => 'settings-test-project',
+ useWorkbenchQueries: () => ({
+ isActiveProject: (projectId: string) => projectId === 'settings-test-project',
+ getProject: () => ({ widgetInstances: { 'settings-test-widget': { typeId: 'queue' } } }),
+ }),
+}));
+
+const translations = await fetch('/locales/en.json').then((response) => response.json());
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: translations } },
+ interpolation: { escapeValue: false },
+});
+
+let host: HTMLDivElement;
+let root: Root;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const quickWidgetProps: WidgetViewProps = {
+ instance: { id: 'settings-test-widget', typeId: 'queue', createdAt: '2026-01-01T00:00:00.000Z' },
+ manifest: {
+ ...queueWidgetManifest,
+ settings: { ...appearanceSettings, quick: ['showFocusRegionHighlight'] },
+ },
+ region: 'right',
+ runtime: {} as WidgetRuntimeApi,
+};
+
+const render = async (quick = false) => {
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <button type="button" onClick={() => openWorkbenchSettings('behavior')}>
+ Open settings
+ </button>
+ {quick ? <WidgetSettingsButton {...quickWidgetProps} /> : null}
+ <SettingsDialogHost />
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+};
+
+const dialogContent = () => document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]');
+const search = () => page.getByRole('textbox', { name: i18n.t('settingsDialog.search'), exact: true });
+const closeButton = () => page.getByRole('button', { name: i18n.t('common.close'), exact: true });
+const waitForOpen = async () => {
+ await expect.element(search()).toBeVisible();
+ await expect.poll(() => dialogContent()?.getAnimations().length).toBe(0);
+};
+const open = async () => {
+ await act(() => page.getByRole('button', { name: 'Open settings', exact: true }).click());
+ await waitForOpen();
+};
+
+beforeEach(async () => {
+ await page.viewport(1280, 900);
+ delete document.documentElement.dataset.reduceMotion;
+ accountLifecycle.activate('settings-test');
+ settingsDialogStore.patchSnapshot({
+ isOpen: false,
+ sectionId: 'appearance',
+ query: '',
+ searchSection: null,
+ target: undefined,
+ entryId: undefined,
+ returnFocus: null,
+ });
+ await patchWorkbenchPreferences(DEFAULT_PREFERENCES);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ delete document.documentElement.dataset.reduceMotion;
+ closeWorkbenchSettings();
+ accountLifecycle.invalidate();
+});
+
+describe('settings dialog', () => {
+ it('edits a matching preference and reveals it in its section without losing its value', async () => {
+ await render();
+ await open();
+ await act(() => search().fill('numeric attention'));
+ await expect.element(page.getByText('Prefer numeric attention style', { exact: true })).toBeVisible();
+ await expect.element(search()).toHaveFocus();
+ const modifiedIndicator = page.getByRole('img', {
+ name: 'Prefer numeric attention style: changed from default',
+ exact: true,
+ });
+ await expect.element(modifiedIndicator).not.toBeInTheDocument();
+ await act(() => page.getByText('Prefer numeric attention style', { exact: true }).click());
+ await expect.poll(() => getWorkbenchPreferences().preferNumericAttentionStyle).toBe(true);
+ await expect.element(modifiedIndicator).toBeVisible();
+ await act(() => page.getByRole('button', { name: i18n.t('settingsDialog.showInSection'), exact: true }).click());
+ await expect.element(search()).toHaveValue('');
+ await expect.element(page.getByRole('dialog', { name: 'Settings: Behavior', exact: true })).toBeVisible();
+ await expect
+ .element(page.getByRole('checkbox', { name: 'Prefer numeric attention style', exact: true }))
+ .toBeChecked();
+ await expect
+ .element(page.getByRole('button', { name: 'Behavior', exact: true }))
+ .toHaveAttribute('aria-current', 'page');
+ await expect.element(modifiedIndicator).toBeVisible();
+ await act(() => page.getByText('Prefer numeric attention style', { exact: true }).click());
+ await expect.poll(() => getWorkbenchPreferences().preferNumericAttentionStyle).toBe(false);
+ await expect.element(modifiedIndicator).not.toBeInTheDocument();
+ });
+
+ it('switches prepared sections without loading placeholders or mounting unselected custom editors', async () => {
+ await render();
+ const mountedCustomEditors: string[] = [];
+ const loadingPlaceholders: string[] = [];
+ let opened = false;
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.addedNodes) {
+ if (!(node instanceof Element)) {
+ continue;
+ }
+ const addedElements = [node, ...node.querySelectorAll('[role="status"], [data-custom-editor]')];
+ for (const element of addedElements) {
+ const editorId = element.getAttribute('data-custom-editor');
+ if (editorId) {
+ mountedCustomEditors.push(editorId);
+ }
+ if (
+ opened &&
+ element.getAttribute('role') === 'status' &&
+ element.textContent?.includes(i18n.t('common.loading'))
+ ) {
+ loadingPlaceholders.push(element.textContent);
+ }
+ }
+ }
+ }
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ try {
+ await open();
+ expect(mountedCustomEditors).toEqual([]);
+ opened = true;
+ for (const section of ['Workflow', 'Queue', 'Appearance', 'Behavior']) {
+ await act(() => page.getByRole('button', { name: section, exact: true }).click());
+ await expect.element(page.getByRole('dialog', { name: `Settings: ${section}`, exact: true })).toBeVisible();
+ expect(dialogContent()?.querySelector('[data-custom-editor]')?.getAttribute('data-custom-editor') ?? null).toBe(
+ section === 'Appearance' ? 'themeId' : null
+ );
+ }
+ expect(loadingPlaceholders).toEqual([]);
+ expect(mountedCustomEditors).toEqual(['themeId']);
+ } finally {
+ observer.disconnect();
+ }
+ });
+
+ it('reveals a search result through the section selector in a narrow window', async () => {
+ await page.viewport(360, 780);
+ await render();
+ await open();
+ await act(() => search().fill('numeric attention'));
+ await expect.element(page.getByText('Prefer numeric attention style', { exact: true })).toBeVisible();
+ await act(() => page.getByRole('button', { name: i18n.t('settingsDialog.showInSection'), exact: true }).click());
+ await expect
+ .element(page.getByRole('combobox', { name: i18n.t('settingsDialog.section'), exact: true }))
+ .toHaveValue('behavior');
+ await expect.element(page.getByRole('dialog', { name: 'Settings: Behavior', exact: true })).toBeVisible();
+ await expect
+ .element(page.getByRole('checkbox', { name: 'Prefer numeric attention style', exact: true }))
+ .toHaveFocus();
+ });
+
+ it('restores section scroll after searching, switching sections, and reopening', async () => {
+ await page.viewport(1280, 480);
+ await render();
+ await open();
+ const body = () => {
+ const label = page.getByText('Prefer numeric attention style', { exact: true }).element();
+ let element = label.parentElement;
+ while (element && getComputedStyle(element).overflowY !== 'auto') {
+ element = element.parentElement;
+ }
+ return element!;
+ };
+ await act(() => {
+ body().scrollTop = 100;
+ });
+ await expect.poll(() => getSettingsSectionScroll('behavior')).toBe(100);
+ await act(() => search().fill('numeric attention'));
+ await act(() => search().fill(''));
+ await expect.poll(() => body().scrollTop).toBe(100);
+ await act(() => page.getByRole('button', { name: 'Queue', exact: true }).click());
+ await act(() => page.getByRole('button', { name: 'Behavior', exact: true }).click());
+ await expect.poll(() => body().scrollTop).toBe(100);
+ await act(() => closeButton().click());
+ await expect.poll(dialogContent).toBeNull();
+ await open();
+ await expect.poll(() => body().scrollTop).toBe(100);
+ });
+
+ it('keeps closing content present for animation, supports reopening, and restores trigger focus', async () => {
+ await render();
+ await open();
+ const content = dialogContent()!;
+ await act(() => closeWorkbenchSettings());
+ expect(content.isConnected).toBe(true);
+ expect(content.dataset.state).toBe('closed');
+ expect(getComputedStyle(content).animationName).not.toBe('none');
+ await act(() => openWorkbenchSettings('behavior', host.querySelector('button')!));
+ await waitForOpen();
+ expect(dialogContent()).toBe(content);
+ await act(() => closeButton().click());
+ await expect.poll(dialogContent).toBeNull();
+ await expect.element(page.getByRole('button', { name: 'Open settings', exact: true })).toHaveFocus();
+ });
+
+ it('dismisses with Escape without retained content under reduced motion', async () => {
+ document.documentElement.dataset.reduceMotion = 'true';
+ await render();
+ await open();
+ const content = dialogContent()!;
+ expect(parseFloat(getComputedStyle(content).animationDuration)).toBeLessThanOrEqual(0.001);
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(dialogContent).toBeNull();
+ await expect.element(page.getByRole('button', { name: 'Open settings', exact: true })).toHaveFocus();
+ });
+
+ it('returns focus to the widget gear when quick settings close with Escape', async () => {
+ await render(true);
+ const gear = page.getByRole('button', {
+ name: i18n.t('widgets.settingsLabel', { label: 'Appearance' }),
+ exact: true,
+ });
+ await act(() => gear.click());
+ await expect.element(page.getByText('Highlight focused regions', { exact: true })).toBeVisible();
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.querySelector('[data-scope="popover"][data-part="content"]')).toBeNull();
+ await expect.element(gear).toHaveFocus();
+ });
+
+ it('hands quick settings to the full section and restores the widget gear', async () => {
+ await render(true);
+ const gear = page.getByRole('button', {
+ name: i18n.t('widgets.settingsLabel', { label: 'Appearance' }),
+ exact: true,
+ });
+ await act(() => gear.click());
+ const quickLabel = page.getByText('Highlight focused regions', { exact: true });
+ await expect.element(quickLabel).toBeVisible();
+ await act(() => quickLabel.click());
+ await expect.poll(() => getWorkbenchPreferences().showFocusRegionHighlight).toBe(false);
+ await page
+ .getByRole('button', { name: i18n.t('settingsDialog.allWidgetSettings', { widget: 'Appearance' }), exact: true })
+ .click();
+ await waitForOpen();
+ await expect.element(page.getByRole('dialog', { name: 'Settings: Appearance', exact: true })).toBeVisible();
+ expect(settingsDialogStore.getSnapshot().target).toEqual({
+ projectId: 'settings-test-project',
+ instanceId: 'settings-test-widget',
+ });
+ await expect.poll(() => dialogContent()?.contains(document.activeElement)).toBe(true);
+ await expect
+ .element(page.getByRole('checkbox', { name: 'Highlight focused regions', exact: true }))
+ .not.toBeChecked();
+ await expect.poll(() => document.querySelector('[data-scope="popover"][data-part="content"]')).toBeNull();
+ await act(() => closeButton().click());
+ await expect.poll(dialogContent).toBeNull();
+ await expect.element(gear).toHaveFocus();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
index 2ff4bb6de6..ae1748ffab 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
@@ -1,914 +1,350 @@
-import type { WorkbenchThemeId } from '@theme/themes';
-import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
-import type { Project } from '@workbench/projectContracts';
-import type { ProjectSettings, WorkbenchLanguage, WorkbenchPreferences } from '@workbench/settings/contracts';
-import type { SettingsSectionId } from '@workbench/widgetContracts';
-
-import {
- Box,
- chakra,
- Checkbox,
- createListCollection,
- Dialog,
- Flex,
- HStack,
- Icon,
- Portal,
- SimpleGrid,
- Stack,
- Switch,
- Text,
- Field,
- useSlotRecipe,
-} from '@chakra-ui/react';
-import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
-import { Button, CloseButton, ConfirmDialog, Select, Tabs } from '@platform/ui';
-import { themeCardRecipe } from '@theme/recipes';
-import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';
-import { registerHotkeyModalLayer } from '@workbench/hotkeys';
-import { clearAllWorkbenchData } from '@workbench/projects/syncedPersistence';
+import type { ChangeEvent, UIEvent } from 'react';
+
+import { Box, Dialog, Flex, HStack, Icon, Input, NativeSelect, Stack, Text, VisuallyHidden } from '@chakra-ui/react';
+import { useCapabilities } from '@features/identity';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { Button } from '@platform/ui/Button';
+import { PanelHeader } from '@platform/ui/PanelHeader';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
import {
- shallowEqual,
+ useActiveProjectId,
useHasWorkbenchProvider,
- useOptionalWorkbenchCommands,
- useOptionalWorkbenchPersistenceService,
- useOptionalWorkbenchSelector,
+ useWorkbenchQueries,
+ useWorkbenchSubscription,
} from '@workbench/WorkbenchContext';
-import {
- CheckIcon,
- Code2Icon,
- DatabaseIcon,
- FolderIcon,
- InfoIcon,
- KeyboardIcon,
- ListOrderedIcon,
- MapIcon,
- PaletteIcon,
- RotateCcwIcon,
- SettingsIcon,
- SlidersHorizontalIcon,
- Trash2Icon,
- WorkflowIcon,
- type LucideIcon,
-} from 'lucide-react';
-import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from 'react';
+import { SearchIcon, XIcon } from 'lucide-react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { AboutSettings } from './AboutSettings';
-import { clearWorkspaceData, rememberWorkspaceClearFailure } from './clearWorkspaceData';
-import { GenerationDevicesSettings } from './GenerationDevicesSettings';
-import { HotkeysSettingsSection } from './HotkeysSettingsSection';
-import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';
-import { setWorkbenchSettingsSection, settingsDialogStore } from './settingsDialogStore';
-import {
- clearWorkbenchSettings,
- DEVELOPER_LOG_LEVELS,
- DEVELOPER_LOG_NAMESPACES,
- patchWorkbenchPreferences,
- useWorkbenchPreferences,
- useWorkbenchSettings,
-} from './store';
-
-interface SettingsTabDefinition {
- value: SettingsSectionId;
- label: string;
- icon: LucideIcon;
- condition?: boolean;
- children: ReactNode;
-}
+import type { SettingsSection } from './catalog';
-const updatePreferences = (patch: Partial<WorkbenchPreferences>): void => {
- void patchWorkbenchPreferences(patch);
+import { searchSettings, settingsCatalog } from './catalog';
+import {
+ closeWorkbenchSettings,
+ getSettingsSectionScroll,
+ rememberSettingsSectionScroll,
+ setSettingsQuery,
+ setWorkbenchSettingsSection,
+ settingsDialogStore,
+} from './settingsDialogStore';
+import { SettingsEntryView } from './SettingsEntryView';
+import { SettingsScopeLabel } from './SettingsScopeLabel';
+import { patchWorkbenchPreferences, useWorkbenchSettingsSelector } from './store';
+
+/** Warm code, never mounted editors or data queries, before exposing section navigation. */
+export const prepareSettingsDialog = async (): Promise<void> => {
+ const resources = new Set(settingsCatalog.flatMap((section) => section.entries.map((entry) => entry.resource)));
+ await Promise.allSettled([
+ ...[...resources].map((resource) => resource.load()),
+ import('./ApplicationSettingField').then((module) => module.prepareApplicationSettings()),
+ ]);
};
-const SETTINGS_TAB_LIST_WIDTH = { base: '40', md: '52' };
-const SETTINGS_CONTENT_PADDING = { base: '4', md: '5' };
-const THEME_GRID_COLUMNS = { base: 2, md: 3 };
-const DEVELOPER_GRID_COLUMNS = { base: 1, md: 2 };
-const DANGER_BUTTON_HOVER_STYLES = { bg: 'fg.error', color: 'bg.subtle' };
-const SWITCH_CHECKED_STYLES = { bg: 'accent.solid' };
-const FIELD_ALIGN_ITEMS = { base: 'stretch', md: 'center' };
-const FIELD_FLEX_DIRECTION = { base: 'column', md: 'row' };
-const SELECT_MAX_WIDTH = { base: 'full', md: '56' };
-
-export const SettingsDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {
- useEffect(() => {
- if (!isOpen) {
- return;
- }
-
- return registerHotkeyModalLayer('settings');
- }, [isOpen]);
+const GROUPS = ['application', 'project', 'widgets', 'system'] as const;
+const DIRECTION = { base: 'column', sm: 'row' } as const;
+const SIDEBAR_WIDTH = { base: 'full', sm: '44', md: '56' };
+const SIDEBAR_RIGHT_BORDER = { base: '0', sm: '1px' };
+const SIDEBAR_BOTTOM_BORDER = { base: '1px', sm: '0' };
+const SEARCH_PADDING = { base: '12', sm: '3' };
+const MOBILE_DISPLAY = { base: 'block', sm: 'none' };
+const DESKTOP_DISPLAY = { base: 'none', sm: 'block' };
+const CONTENT_PADDING = { base: '4', md: '6' };
+const clearSearch = () => setSettingsQuery('');
+const rememberScroll = (event: UIEvent<HTMLDivElement>) => {
+ const current = settingsDialogStore.getSnapshot();
+ if (!current.query.trim()) {
+ rememberSettingsSectionScroll(current.sectionId, event.currentTarget.scrollTop);
+ }
+};
+const retrySave = () => {
+ void patchWorkbenchPreferences({});
+};
- const handleOpenChange = useCallback(
- (event: { open: boolean }) => {
- if (!event.open) {
- onClose();
+const ProjectLifetime = () => {
+ const projectId = useActiveProjectId();
+ const queries = useWorkbenchQueries();
+ const subscribe = useWorkbenchSubscription();
+ useMountEffect(() =>
+ subscribe(() => {
+ if (!queries.isActiveProject(projectId)) {
+ closeWorkbenchSettings();
}
- },
- [onClose]
- );
-
- return (
- <Dialog.Root
- closeOnInteractOutside={false}
- lazyMount
- open={isOpen}
- scrollBehavior="inside"
- size="xl"
- unmountOnExit
- onOpenChange={handleOpenChange}
- >
- <SettingsDialogContent onClose={onClose} />
- </Dialog.Root>
+ })
);
+ return null;
};
-const SettingsDialogContent = ({ onClose }: { onClose: () => void }) => {
+const SettingsDialog = () => {
const { t } = useTranslation();
- const { error, scope, status } = useWorkbenchSettings();
- const handlePositionerClick = useCallback(
- (event: { target: EventTarget; currentTarget: EventTarget }) => {
- if (event.target === event.currentTarget) {
- onClose();
+ const hasWorkbench = useHasWorkbenchProvider();
+ const { canManageAppConfig } = useCapabilities();
+ const state = settingsDialogStore.useSelector((snapshot) => snapshot);
+ const error = useWorkbenchSettingsSelector((snapshot) => snapshot.error);
+ const sections = settingsCatalog.filter((section) => section.id !== 'server' || canManageAppConfig);
+ const active = sections.find((section) => section.id === state.sectionId) ?? sections[0];
+ const searching = state.query.trim().length > 0;
+ const matches = searchSettings(sections, state.query, t);
+ const displayed = searching
+ ? matches.filter((section) => !state.searchSection || section.id === state.searchSection)
+ : [active];
+ const count = matches.reduce((total, section) => total + section.entries.length, 0);
+ const selectSection = useCallback(
+ (sectionId: string) => {
+ if (searching) {
+ settingsDialogStore.patchSnapshot({ searchSection: sectionId || null });
+ } else {
+ setWorkbenchSettingsSection(sectionId);
}
},
- [onClose]
- );
-
- return (
- <Portal>
- <Dialog.Backdrop pointerEvents="auto" />
- <Dialog.Positioner pointerEvents="auto" onClick={handlePositionerClick}>
- <Dialog.Content h="min(46rem, calc(100dvh - 4rem))" maxW="4xl">
- <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">
- <Flex alignItems="start" gap="2">
- <Icon as={SettingsIcon} boxSize="5" />
- <Stack gap="1">
- <Dialog.Title lineHeight={1} mt="0.5">
- {t('settings.title')}
- </Dialog.Title>
- <Text color="fg.subtle" fontSize="xs">
- {scope === 'user' ? t('settings.descriptionUser') : t('settings.descriptionGlobal')}
- </Text>
- {status === 'error' && error ? (
- <Text color="fg.error" fontSize="2xs">
- {error}
- </Text>
- ) : null}
- </Stack>
- </Flex>
- </Dialog.Header>
- <Dialog.Body minH="0" p="0">
- <SettingsTabs />
- </Dialog.Body>
- <Dialog.CloseTrigger asChild>
- <CloseButton />
- </Dialog.CloseTrigger>
- </Dialog.Content>
- </Dialog.Positioner>
- </Portal>
+ [searching]
);
-};
-
-const SettingsTabs = () => {
- const { t } = useTranslation();
- const hasWorkbench = useHasWorkbenchProvider();
- const settingsTabs: SettingsTabDefinition[] = useMemo(
- () => [
- {
- children: <AppearanceSection />,
- icon: PaletteIcon,
- label: t('settings.tabs.appearance'),
- value: 'appearance',
- },
- {
- children: <BehaviorSection />,
- icon: SlidersHorizontalIcon,
- label: t('settings.tabs.behavior'),
- value: 'behavior',
- },
- {
- children: <HotkeysSettingsSection />,
- icon: KeyboardIcon,
- label: t('settings.tabs.hotkeys'),
- value: 'hotkeys',
- },
- {
- children: <ProjectSection />,
- condition: hasWorkbench,
- icon: FolderIcon,
- label: t('settings.tabs.project'),
- value: 'project',
- },
- {
- children: <QueueSection />,
- icon: ListOrderedIcon,
- label: t('settings.tabs.queue'),
- value: 'queue',
- },
- {
- children: <WorkflowSection />,
- icon: WorkflowIcon,
- label: t('settings.tabs.workflow'),
- value: 'workflow',
- },
- {
- children: <ImageMapSection />,
- icon: MapIcon,
- label: t('settings.tabs.imageMap'),
- value: 'imageMap',
- },
- {
- children: <DeveloperSection />,
- icon: Code2Icon,
- label: t('settings.tabs.developer'),
- value: 'developer',
- },
- {
- children: <WorkspaceSection />,
- icon: DatabaseIcon,
- label: t('settings.tabs.workspace'),
- value: 'workspace',
- },
- {
- children: <AboutSection />,
- icon: InfoIcon,
- label: t('settings.tabs.about'),
- value: 'about',
- },
- ],
- [hasWorkbench, t]
+ const selectAllResults = useCallback(() => selectSection(''), [selectSection]);
+ const changeSection = useCallback(
+ (event: ChangeEvent<HTMLSelectElement>) => selectSection(event.target.value),
+ [selectSection]
);
- const tabs = settingsTabs.filter((tab) => tab.condition !== false);
- const sectionId = settingsDialogStore.useSelector((snapshot) => snapshot.sectionId);
- const activeSectionId = tabs.some((tab) => tab.value === sectionId) ? sectionId : 'appearance';
- const handleValueChange = useCallback((event: { value: string }) => {
- setWorkbenchSettingsSection(event.value as SettingsSectionId);
+ const changeQuery = useCallback((event: ChangeEvent<HTMLInputElement>) => setSettingsQuery(event.target.value), []);
+ const attachBody = useCallback((element: HTMLDivElement | null) => {
+ const current = settingsDialogStore.getSnapshot();
+ if (element && !current.query.trim() && !current.entryId) {
+ element.scrollTop = getSettingsSectionScroll(current.sectionId);
+ }
}, []);
-
return (
- <Tabs.Root
- display="flex"
- h="full"
- minH="0"
- orientation="vertical"
- value={activeSectionId}
- variant="subtle"
- onValueChange={handleValueChange}
- >
- <Tabs.List
- alignItems="stretch"
+ <Flex h="full" minH="0" direction={DIRECTION}>
+ {hasWorkbench ? <ProjectLifetime /> : null}
+ <Flex
+ as="aside"
+ w={SIDEBAR_WIDTH}
+ flexShrink={0}
+ direction="column"
bg="bg"
+ borderRightWidth={SIDEBAR_RIGHT_BORDER}
+ borderBottomWidth={SIDEBAR_BOTTOM_BORDER}
borderColor="border.subtle"
- borderRightWidth="1px"
- flexShrink={0}
- p="1"
- gap="0.5"
- w={SETTINGS_TAB_LIST_WIDTH}
- >
- {tabs.map((tab) => (
- <SettingsTabTrigger key={tab.value} icon={tab.icon} label={tab.label} value={tab.value} />
- ))}
- </Tabs.List>
- <Box flex="1" minW="0" overflowY="auto" p={SETTINGS_CONTENT_PADDING}>
- {tabs.map((tab) => (
- <Tabs.Content key={tab.value} m="0" p="0" value={tab.value}>
- {tab.children}
- </Tabs.Content>
- ))}
- </Box>
- </Tabs.Root>
- );
-};
-
-const SettingsTabTrigger = ({ icon, label, value }: { icon: LucideIcon; label: string; value: string }) => (
- <Tabs.Trigger justifyContent="flex-start" textAlign="start" value={value} w="full">
- <Icon as={icon} boxSize="3.5" flexShrink={0} />
- <Text truncate>{label}</Text>
- </Tabs.Trigger>
-);
-
-const SettingsSection = ({
- children,
- description,
- title,
-}: {
- children: ReactNode;
- description: string;
- title: string;
-}) => (
- <Stack gap="3">
- <Stack gap="0.5">
- <Text color="fg" fontSize="sm" fontWeight="600">
- {title}
- </Text>
- <Text color="fg.subtle" fontSize="xs">
- {description}
- </Text>
- </Stack>
- {children}
- </Stack>
-);
-
-const AppearanceSection = () => {
- const { t } = useTranslation();
- const { language, reduceMotion, showFocusRegionHighlight, themeId } = useWorkbenchPreferences();
-
- const selectTheme = useCallback((nextThemeId: WorkbenchThemeId) => {
- updatePreferences({ themeId: nextThemeId });
- }, []);
- const updateLanguage = useCallback((value: string) => {
- updatePreferences({ language: value as WorkbenchLanguage });
- }, []);
- const updateReduceMotion = useCallback((checked: boolean) => {
- updatePreferences({ reduceMotion: checked });
- }, []);
- const updateShowFocusRegionHighlight = useCallback((checked: boolean) => {
- updatePreferences({ showFocusRegionHighlight: checked });
- }, []);
-
- return (
- <SettingsSection description="Choose a theme, language, and motion behavior." title="Appearance">
- <SimpleGrid columns={THEME_GRID_COLUMNS} gap="3">
- {THEMES.map((theme) => (
- <ThemeCard key={theme.id} selected={theme.id === themeId} theme={theme} onSelect={selectTheme} />
- ))}
- </SimpleGrid>
- <SettingSelect
- description={t('settings.languageDescription')}
- label={t('settings.language')}
- options={WORKBENCH_LANGUAGE_OPTIONS}
- value={language}
- onChange={updateLanguage}
- />
- <SettingToggle
- checked={reduceMotion}
- description="Disable transitions and animations across the workbench."
- label="Reduce motion"
- onChange={updateReduceMotion}
- />
- <SettingToggle
- checked={showFocusRegionHighlight}
- label={t('settings.enableHighlightFocusedRegions')}
- onChange={updateShowFocusRegionHighlight}
- />
- </SettingsSection>
- );
-};
-
-const ThemeCard = ({
- onSelect,
- selected,
- theme,
-}: {
- onSelect: (themeId: WorkbenchThemeId) => void;
- selected: boolean;
- theme: ThemeDefinition;
-}) => {
- const recipe = useSlotRecipe({ recipe: themeCardRecipe });
- const styles = recipe({ selected });
- const [surface, control, brandColor, accentColor] = previewSwatches(theme);
- const handleSelect = useCallback(() => onSelect(theme.id), [onSelect, theme.id]);
-
- return (
- <chakra.button type="button" aria-pressed={selected} css={styles.root} onClick={handleSelect}>
- <Flex css={styles.preview}>
- <Box css={styles.swatch} bg={surface} />
- <Box css={styles.swatch} bg={control} />
- <Box css={styles.swatch} bg={brandColor} />
- <Box css={styles.swatch} bg={accentColor} />
- </Flex>
- <Box css={styles.body}>
- <HStack justify="space-between" w="full">
- <Text css={styles.name}>{theme.label}</Text>
- <Box css={styles.indicator}>
- <Icon as={CheckIcon} boxSize="3" />
- </Box>
- </HStack>
- <Text css={styles.description}>{theme.description}</Text>
- </Box>
- </chakra.button>
- );
-};
-
-const BehaviorSection = () => {
- const {
- autoSwitchInvocationRoute,
- confirmImageDeletion,
- enableInformationalPopovers,
- enableModelDescriptions,
- notifyOnEnqueue,
- preferNumericAttentionStyle,
- showPromptSyntaxHighlighting,
- } = useWorkbenchPreferences();
- const updateAutoSwitchInvocationRoute = useCallback((checked: boolean) => {
- updatePreferences({ autoSwitchInvocationRoute: checked });
- }, []);
- const updateConfirmImageDeletion = useCallback((checked: boolean) => {
- updatePreferences({ confirmImageDeletion: checked });
- }, []);
- const updateEnableInformationalPopovers = useCallback((checked: boolean) => {
- updatePreferences({ enableInformationalPopovers: checked });
- }, []);
- const updateEnableModelDescriptions = useCallback((checked: boolean) => {
- updatePreferences({ enableModelDescriptions: checked });
- }, []);
- const updateNotifyOnEnqueue = useCallback((checked: boolean) => {
- updatePreferences({ notifyOnEnqueue: checked });
- }, []);
- const updatePreferNumericAttentionStyle = useCallback((checked: boolean) => {
- updatePreferences({ preferNumericAttentionStyle: checked });
- }, []);
- const updateShowPromptSyntaxHighlighting = useCallback((checked: boolean) => {
- updatePreferences({ showPromptSyntaxHighlighting: checked });
- }, []);
-
- return (
- <SettingsSection description="Safety checks, prompt editing, and user-assistance behavior." title="Behavior">
- <SettingToggle
- checked={autoSwitchInvocationRoute}
- description="Switch the Invoke source and destination to match the surface you are editing or bring to the front. Locked sources and destinations are never changed."
- label="Auto-switch Invoke route"
- onChange={updateAutoSwitchInvocationRoute}
- />
- <SettingToggle
- checked={confirmImageDeletion}
- description="Ask for confirmation before permanently deleting images."
- label="Confirm image deletion"
- onChange={updateConfirmImageDeletion}
- />
- <SettingToggle
- checked={enableInformationalPopovers}
- description="Show educational popovers on controls that have extra guidance."
- label="Enable informational popovers"
- onChange={updateEnableInformationalPopovers}
- />
- <SettingToggle
- checked={enableModelDescriptions}
- description="Include model descriptions in model dropdowns where available."
- label="Enable model descriptions in dropdowns"
- onChange={updateEnableModelDescriptions}
- />
- <SettingToggle
- checked={notifyOnEnqueue}
- description="Show a toast for every successful enqueue. Off, enqueues are still recorded in the notification center."
- label="Notify when queued"
- onChange={updateNotifyOnEnqueue}
- />
- <SettingToggle
- checked={preferNumericAttentionStyle}
- description="Prefer numeric prompt attention syntax when controls insert attention weights."
- label="Prefer numeric attention style"
- onChange={updatePreferNumericAttentionStyle}
- />
- <SettingToggle
- checked={showPromptSyntaxHighlighting}
- description="Color prompt syntax in prompt fields without changing the prompt text or validation behavior."
- label="Highlight prompt syntax"
- onChange={updateShowPromptSyntaxHighlighting}
- />
- </SettingsSection>
- );
-};
-
-const ProjectSection = () => {
- const activeProject = useOptionalWorkbenchSelector<Pick<Project, 'name' | 'settings'> | null>(
- (snapshot) => ({ name: snapshot.activeProject.name, settings: snapshot.activeProject.settings }),
- null,
- shallowEqual
- );
- const commands = useOptionalWorkbenchCommands();
- const updateProjectSettings = useCallback(
- (patch: Partial<ProjectSettings>) => {
- commands?.account.updateProjectPreferences(patch);
- },
- [commands]
- );
- const updateUseCpuNoise = useCallback(
- (checked: boolean) => {
- updateProjectSettings({ useCpuNoise: checked });
- },
- [updateProjectSettings]
- );
- const updateAntialiasProgressImages = useCallback(
- (checked: boolean) => {
- updateProjectSettings({ antialiasProgressImages: checked });
- },
- [updateProjectSettings]
- );
-
- if (!activeProject || !commands) {
- return null;
- }
-
- const settings = activeProject.settings;
-
- return (
- <SettingsSection
- description={`Settings saved with ${activeProject.name}. Future project-only settings can live here without becoming user preferences.`}
- title="Project"
- >
- <SettingToggle
- checked={settings.useCpuNoise}
- description="Use CPU noise generation for deterministic legacy-compatible outputs."
- label="Use CPU noise"
- onChange={updateUseCpuNoise}
- />
- <SettingToggle
- checked={settings.antialiasProgressImages}
- description="Smooth progress previews instead of rendering them pixelated."
- label="Antialias progress images"
- onChange={updateAntialiasProgressImages}
- />
- </SettingsSection>
- );
-};
-
-const WorkflowSection = () => {
- const { workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =
- useWorkbenchPreferences();
- const updateWorkflowEdgeStyle = useCallback((value: string) => {
- updatePreferences({ workflowEdgeStyle: value === 'square' ? 'square' : 'curved' });
- }, []);
- const updateWorkflowSnapToGrid = useCallback((checked: boolean) => {
- updatePreferences({ workflowSnapToGrid: checked });
- }, []);
- const updateWorkflowShowMinimap = useCallback((checked: boolean) => {
- updatePreferences({ workflowShowMinimap: checked });
- }, []);
- const updateWorkflowValidateConnections = useCallback((checked: boolean) => {
- updatePreferences({ workflowValidateConnections: checked });
- }, []);
-
- return (
- <SettingsSection description="Editing behavior for the project graph workflow editor." title="Workflow">
- <SettingSelect
- description="How connections between nodes are drawn in the editor."
- label="Connection style"
- options={WORKFLOW_EDGE_STYLE_OPTIONS}
- value={workflowEdgeStyle}
- onChange={updateWorkflowEdgeStyle}
- />
- <SettingToggle
- checked={workflowSnapToGrid}
- description="Snap nodes to the grid while dragging. When off, hold Ctrl to snap temporarily."
- label="Always snap to grid"
- onChange={updateWorkflowSnapToGrid}
- />
- <SettingToggle
- checked={workflowShowMinimap}
- description="Show the minimap overview in the corner of the workflow editor."
- label="Show minimap"
- onChange={updateWorkflowShowMinimap}
- />
- <SettingToggle
- checked={workflowValidateConnections}
- description="Reject connections between incompatible field types while wiring nodes. Turn off to wire anything (runs may fail)."
- label="Validate connections"
- onChange={updateWorkflowValidateConnections}
- />
- </SettingsSection>
- );
-};
-
-const QueueSection = () => {
- const { queueJobsScope } = useWorkbenchPreferences();
- const updateQueueJobsScope = useCallback((value: string) => {
- updatePreferences({ queueJobsScope: value === 'active-project' ? 'active-project' : 'all' });
- }, []);
-
- return (
- <Stack gap="6">
- <SettingsSection description="Choose which jobs the Queue widget includes in its counts and lists." title="Queue">
- <SettingSelect
- description="Show jobs from only the active project, or all queue jobs visible to you."
- label="Show jobs from"
- options={QUEUE_JOBS_SCOPE_OPTIONS}
- value={queueJobsScope}
- onChange={updateQueueJobsScope}
- />
- </SettingsSection>
- <SettingsSection
- description="Accelerators used for generation. With more than one selected, InvokeAI runs a session on each at the same time. This is a server-wide setting."
- title="Generation Devices"
- >
- <GenerationDevicesSettings />
- </SettingsSection>
- </Stack>
- );
-};
-
-const AboutSection = () => {
- const { t } = useTranslation();
-
- return (
- <Stack gap="6">
- <SettingsSection description={t('settings.about.description')} title={t('settings.about.title')}>
- <AboutSettings />
- </SettingsSection>
- </Stack>
- );
-};
-
-const ImageMapSection = () => {
- const { t } = useTranslation();
-
- return (
- <Stack gap="6">
- <SettingsSection
- description={t('settings.imageMapVocabulary.description')}
- title={t('settings.imageMapVocabulary.title')}
+ minH="0"
>
- <ImageMapVocabularySettings />
- </SettingsSection>
- </Stack>
- );
-};
-
-const DeveloperSection = () => {
- const { developerLogEnabled, developerLogLevel, developerLogNamespaces, developerPerformanceTimingsEnabled } =
- useWorkbenchPreferences();
- const enabledNamespaces = useMemo(() => new Set(developerLogNamespaces), [developerLogNamespaces]);
-
- const toggleNamespace = useCallback(
- (namespace: DeveloperLogNamespace, checked: boolean) => {
- const next = checked
- ? [...developerLogNamespaces, namespace]
- : developerLogNamespaces.filter((candidate) => candidate !== namespace);
-
- updatePreferences({
- developerLogNamespaces: DEVELOPER_LOG_NAMESPACES.filter((candidate) => next.includes(candidate)),
- });
- },
- [developerLogNamespaces]
- );
- const updateDeveloperLogEnabled = useCallback((checked: boolean) => {
- updatePreferences({ developerLogEnabled: checked });
- }, []);
- const updateDeveloperLogLevel = useCallback((value: string) => {
- updatePreferences({ developerLogLevel: value as DeveloperLogLevel });
- }, []);
- const updateDeveloperPerformanceTimingsEnabled = useCallback((checked: boolean) => {
- updatePreferences({ developerPerformanceTimingsEnabled: checked });
- }, []);
-
- return (
- <SettingsSection
- description="Current-user diagnostics settings. Entries are still grouped by project and kept in memory only."
- title="Developer"
- >
- <SettingToggle
- checked={developerLogEnabled}
- description="Record selected diagnostic log events in the Diagnostics widget."
- label="Record diagnostic logs"
- onChange={updateDeveloperLogEnabled}
- />
- <SettingSelect
- description="Minimum log level recorded in the Diagnostics widget."
- label="Log level"
- options={DEVELOPER_LOG_LEVEL_OPTIONS}
- value={developerLogLevel}
- onChange={updateDeveloperLogLevel}
- />
- <SettingToggle
- checked={developerPerformanceTimingsEnabled}
- description="Record performance measurements such as workflow editor timing and project serialization costs."
- label="Collect performance timings"
- onChange={updateDeveloperPerformanceTimingsEnabled}
- />
- <Stack gap="2">
- <Text color="fg" fontSize="sm" fontWeight="500">
- Log namespaces
- </Text>
- <SimpleGrid columns={DEVELOPER_GRID_COLUMNS} gap="2">
- {DEVELOPER_LOG_NAMESPACES.map((namespace) => (
- <DeveloperNamespaceCheckbox
- key={namespace}
- checked={enabledNamespaces.has(namespace)}
- namespace={namespace}
- toggleNamespace={toggleNamespace}
+ <Box p="3" pe={SEARCH_PADDING}>
+ <HStack position="relative">
+ <Icon as={SearchIcon} position="absolute" left="2.5" boxSize="3.5" color="fg.muted" pointerEvents="none" />
+ <Input
+ aria-label={t('settingsDialog.search')}
+ placeholder={t('settingsDialog.search')}
+ value={state.query}
+ ps="8"
+ pe="8"
+ size="sm"
+ onChange={changeQuery}
/>
- ))}
- </SimpleGrid>
- </Stack>
- </SettingsSection>
- );
-};
-
-const DeveloperNamespaceCheckbox = ({
- checked,
- namespace,
- toggleNamespace,
-}: {
- checked: boolean;
- namespace: DeveloperLogNamespace;
- toggleNamespace: (namespace: DeveloperLogNamespace, checked: boolean) => void;
-}) => {
- const handleCheckedChange = useCallback(
- (event: { checked: boolean | 'indeterminate' }) => toggleNamespace(namespace, event.checked === true),
- [namespace, toggleNamespace]
- );
-
- return (
- <Checkbox.Root checked={checked} size="sm" onCheckedChange={handleCheckedChange}>
- <Checkbox.HiddenInput />
- <Checkbox.Control />
- <Checkbox.Label color="fg.muted" fontSize="xs">
- {formatSettingLabel(namespace)}
- </Checkbox.Label>
- </Checkbox.Root>
- );
-};
-
-const WorkspaceSection = () => {
- const commands = useOptionalWorkbenchCommands();
- const mountedPersistence = useOptionalWorkbenchPersistenceService();
- const { scope } = useWorkbenchSettings();
- const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);
-
- const clearSavedData = useCallback(async () => {
- const failures = await clearWorkspaceData(
- () => (mountedPersistence ? mountedPersistence.clearWorkbench() : clearAllWorkbenchData()),
- clearWorkbenchSettings
- );
- if (failures.length === 0) {
- window.location.reload();
- return;
- }
- const message = failures.includes('projects')
- ? 'Saved project data could not be fully cleared. Reloading to restore a consistent workspace.'
- : 'Projects were cleared, but some local settings could not be. Reloading the workspace.';
- rememberWorkspaceClearFailure(message, window.sessionStorage);
- commands?.notifications.reportError({ area: 'workspace-clear', message, namespace: 'system' });
- window.location.reload();
- }, [commands, mountedPersistence]);
- const resetLayout = useCallback(() => commands?.layout.reset(), [commands]);
- const openClearConfirm = useCallback(() => setIsClearConfirmOpen(true), []);
- const closeClearConfirm = useCallback(() => setIsClearConfirmOpen(false), []);
-
- return (
- <SettingsSection
- description="Reset the layout, or permanently delete saved projects and settings."
- title="Workspace"
- >
- <HStack gap="2" wrap="wrap">
- {commands ? (
- <Button size="sm" variant="outline" onClick={resetLayout}>
- <RotateCcwIcon />
- Reset layout
- </Button>
+ {state.query ? (
+ <Button
+ aria-label={t('settingsDialog.clearSearch')}
+ position="absolute"
+ right="0"
+ size="2xs"
+ variant="ghost"
+ onClick={clearSearch}
+ >
+ <XIcon />
+ </Button>
+ ) : null}
+ </HStack>
+ </Box>
+ <Box display={MOBILE_DISPLAY} px="3" pb="3">
+ <NativeSelect.Root size="sm">
+ <NativeSelect.Field
+ aria-label={t('settingsDialog.section')}
+ value={searching ? (state.searchSection ?? '') : active.id}
+ onChange={changeSection}
+ >
+ {searching ? <option value="">{t('settingsDialog.allResults')}</option> : null}
+ {(searching ? matches : sections).map((section) => (
+ <option key={section.id} value={section.id}>
+ {resolveSettingsText(section.label, t)}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Box>
+ <Box
+ as="nav"
+ aria-label={t('settings.title')}
+ display={DESKTOP_DISPLAY}
+ overflowY="auto"
+ flex="1"
+ minH="0"
+ px="2"
+ pb="3"
+ >
+ {searching ? (
+ <Button
+ w="full"
+ justifyContent="space-between"
+ size="sm"
+ variant={!state.searchSection ? 'subtle' : 'ghost'}
+ onClick={selectAllResults}
+ >
+ {t('settingsDialog.allResults')}
+ <Text fontSize="xs">{count}</Text>
+ </Button>
+ ) : null}
+ {GROUPS.map((group) => {
+ const groupSections = (searching ? matches : sections).filter((section) => section.group === group);
+ if (!groupSections.length) {
+ return null;
+ }
+ return (
+ <Stack key={group} gap="0.5" mt="4">
+ <Text px="2" pb="1" fontSize="2xs" fontWeight="600" color="fg.muted" textTransform="uppercase">
+ {t(`settingsDialog.groups.${group}`)}
+ </Text>
+ {groupSections.map((section) => (
+ <SettingsNavigationItem
+ key={section.id}
+ section={section}
+ selected={(searching ? state.searchSection : active.id) === section.id}
+ searching={searching}
+ onSelect={selectSection}
+ />
+ ))}
+ </Stack>
+ );
+ })}
+ </Box>
+ </Flex>
+ <Flex direction="column" flex="1" minW="0" minH="0">
+ <Dialog.Header asChild>
+ <PanelHeader px="4" pe="12" py="0">
+ <HStack gap="2">
+ <Icon as={searching ? SearchIcon : active.icon} boxSize="4" />
+ <Dialog.Title fontSize="xs" fontWeight="700">
+ <VisuallyHidden>{t('settings.title')}: </VisuallyHidden>
+ {searching ? t('settingsDialog.results') : resolveSettingsText(active.label, t)}
+ </Dialog.Title>
+ </HStack>
+ </PanelHeader>
+ </Dialog.Header>
+ {error ? (
+ <HStack role="alert" px="4" py="2" bg="bg.error">
+ <Text fontSize="xs" color="fg.error" flex="1">
+ {error}
+ </Text>
+ <Button size="xs" onClick={retrySave}>
+ {t('common.retry')}
+ </Button>
+ </HStack>
) : null}
- <Button
- borderColor="border.emphasized"
- color="fg.error"
- size="sm"
- variant="outline"
- _hover={DANGER_BUTTON_HOVER_STYLES}
- onClick={openClearConfirm}
+ <VisuallyHidden role="status">{searching ? t('settingsDialog.resultCount', { count }) : ''}</VisuallyHidden>
+ <Box
+ key={searching ? `search:${state.searchSection ?? ''}` : active.id}
+ ref={attachBody}
+ onScroll={rememberScroll}
+ overflowY="auto"
+ flex="1"
+ minH="0"
+ px={CONTENT_PADDING}
+ pb="4"
>
- <Trash2Icon />
- Clear saved data…
- </Button>
- </HStack>
- <ConfirmDialog
- body={
- scope === 'user'
- ? 'This permanently deletes all projects and settings for your account on this server. It cannot be undone.'
- : 'This permanently deletes all projects and settings for this install. It cannot be undone.'
- }
- confirmLabel="Delete everything"
- isOpen={isClearConfirmOpen}
- title="Clear saved data?"
- onClose={closeClearConfirm}
- onConfirm={clearSavedData}
- />
- </SettingsSection>
+ {displayed.map((section) => (
+ <SettingsSectionContent
+ key={section.id}
+ section={section}
+ search={searching}
+ onReveal={setWorkbenchSettingsSection}
+ />
+ ))}
+ {searching && !displayed.length ? (
+ <Stack align="center" py="12" gap="3">
+ <Text color="fg.muted">{t('settingsDialog.noResults')}</Text>
+ <Button size="sm" variant="outline" onClick={clearSearch}>
+ {t('settingsDialog.clearSearch')}
+ </Button>
+ </Stack>
+ ) : null}
+ </Box>
+ </Flex>
+ </Flex>
);
};
-const SettingToggle = ({
- checked,
- description,
- label,
- onChange,
+const SettingsNavigationItem = ({
+ section,
+ selected,
+ searching,
+ onSelect,
}: {
- checked: boolean;
- description?: string;
- label: string;
- onChange: (checked: boolean) => void;
+ section: SettingsSection;
+ selected: boolean;
+ searching: boolean;
+ onSelect: (sectionId: string) => void;
}) => {
- const descriptionId = useId();
- const handleCheckedChange = useCallback(
- (event: { checked: boolean | 'indeterminate' }) => onChange(event.checked === true),
- [onChange]
- );
-
+ const { t } = useTranslation();
+ const select = useCallback(() => onSelect(section.id), [onSelect, section.id]);
return (
- <Switch.Root
- alignItems="center"
- checked={checked}
- display="flex"
- gap="4"
- justifyContent="space-between"
+ <Button
w="full"
- onCheckedChange={handleCheckedChange}
+ justifyContent="start"
+ size="sm"
+ variant={selected ? 'subtle' : 'ghost'}
+ aria-current={selected ? 'page' : undefined}
+ onClick={select}
>
- <Stack gap="0.5">
- <Switch.Label color="fg" fontSize="sm" fontWeight="500" m="0">
- {label}
- </Switch.Label>
- {description && (
- <Text color="fg.subtle" fontSize="xs" id={descriptionId}>
- {description}
- </Text>
- )}
- </Stack>
- <Switch.HiddenInput aria-describedby={descriptionId} />
- <Switch.Control flexShrink={0} _checked={SWITCH_CHECKED_STYLES}>
- <Switch.Thumb />
- </Switch.Control>
- </Switch.Root>
+ <Icon as={section.icon} boxSize="3.5" flexShrink={0} />
+ <Text flex="1" textAlign="start" whiteSpace="normal">
+ {resolveSettingsText(section.label, t)}
+ </Text>
+ {searching ? <Text fontSize="2xs">{section.entries.length}</Text> : null}
+ </Button>
);
};
-const SettingSelect = ({
- description,
- label,
- onChange,
- options,
- value,
+const SettingsSectionContent = ({
+ section,
+ search,
+ onReveal,
}: {
- description?: string;
- label: string;
- onChange: (value: string) => void;
- options: readonly { label: string; value: string }[];
- value: string;
+ section: SettingsSection;
+ search: boolean;
+ onReveal: (sectionId: string, entryId?: string) => void;
}) => {
- const collection = useMemo(() => createListCollection({ items: options }), [options]);
- const selectedValue = useMemo(() => [value], [value]);
- const handleValueChange = useCallback(
- ({ value: next }: { value: string[] }) => {
- const nextValue = next[0];
-
- if (nextValue !== undefined) {
- onChange(nextValue);
- }
- },
- [onChange]
+ const { t } = useTranslation();
+ const target = settingsDialogStore.useSelector((snapshot) =>
+ snapshot.sectionId === section.id ? snapshot.target : undefined
);
-
return (
- <Field.Root
- alignItems={FIELD_ALIGN_ITEMS}
- display="flex"
- flexDirection={FIELD_FLEX_DIRECTION}
- gap="3"
- justifyContent="space-between"
- >
- <Stack gap="0.5">
- <Field.Label color="fg" fontSize="sm" fontWeight="500" m="0">
- {label}
- </Field.Label>
- {description && (
- <Field.HelperText color="fg.subtle" fontSize="xs" m="0">
- {description}
- </Field.HelperText>
- )}
- </Stack>
- <Select
- collection={collection}
- flexShrink={0}
- maxW={SELECT_MAX_WIDTH}
- size="sm"
- value={selectedValue}
- w="full"
- onValueChange={handleValueChange}
- />
- </Field.Root>
+ <Box>
+ {!search && section.entries[0] ? (
+ <Box pt="3">
+ <SettingsScopeLabel scope={section.entries[0].field.scope} />
+ </Box>
+ ) : null}
+ {search ? (
+ <Stack gap="0.5" pt="5">
+ <Text as="h3" fontWeight="600" fontSize="sm">
+ {resolveSettingsText(section.label, t)}
+ </Text>
+ {section.entries[0] ? <SettingsScopeLabel scope={section.entries[0].field.scope} /> : null}
+ </Stack>
+ ) : null}
+ {section.entries.map((entry, index) => (
+ <SettingsEntryView
+ key={entry.field.id}
+ entry={entry}
+ section={section}
+ target={target}
+ search={search}
+ onReveal={onReveal}
+ showGroup={Boolean(
+ entry.field.group &&
+ resolveSettingsText(entry.field.group, t) !==
+ (section.entries[index - 1]?.field.group
+ ? resolveSettingsText(section.entries[index - 1].field.group!, t)
+ : '')
+ )}
+ />
+ ))}
+ </Box>
);
};
-
-const formatSettingLabel = (value: string): string =>
- value
- .split('-')
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
- .join(' ');
-
-const WORKFLOW_EDGE_STYLE_OPTIONS = [
- { label: 'Curved', value: 'curved' },
- { label: 'Square', value: 'square' },
-];
-
-const QUEUE_JOBS_SCOPE_OPTIONS = [
- { label: 'Active project', value: 'active-project' },
- { label: 'All', value: 'all' },
-];
-
-const DEVELOPER_LOG_LEVEL_OPTIONS = DEVELOPER_LOG_LEVELS.map((value) => ({
- label: formatSettingLabel(value),
- value,
-}));
-
-/** Default export so the top bar can host this body behind `React.lazy`. */
export default SettingsDialog;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.browser.test.tsx
new file mode 100644
index 0000000000..f515d2ecac
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.browser.test.tsx
@@ -0,0 +1,119 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider, Dialog } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { SettingsDialogHost } from './SettingsDialogHost';
+import { openWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';
+
+const initialLoad = vi.hoisted(() => {
+ let reject!: (error: Error) => void;
+ const promise = new Promise<never>((_resolve, rejectPromise) => {
+ reject = rejectPromise;
+ });
+ let resolveRetry!: () => void;
+ const retryPromise = new Promise<void>((resolve) => {
+ resolveRetry = resolve;
+ });
+ return { promise, reject, retryPromise, resolveRetry };
+});
+
+vi.mock('./dialogResource', async () => {
+ const { createDeferredResource } = await import('@workbench/deferredResource');
+ let failedOnce = false;
+ return {
+ settingsDialogResource: createDeferredResource(() => {
+ if (!failedOnce) {
+ failedOnce = true;
+ return initialLoad.promise;
+ }
+ return initialLoad.retryPromise.then(() => ({
+ default: () => (
+ <Dialog.Body>
+ <Dialog.Title>Settings: Behavior</Dialog.Title>
+ <input aria-label="Search settings" />
+ </Dialog.Body>
+ ),
+ }));
+ }),
+ };
+});
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+ interpolation: { escapeValue: false },
+});
+
+let host: HTMLDivElement | undefined;
+let root: Root | undefined;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ settingsDialogStore.patchSnapshot({ isOpen: false, returnFocus: null });
+});
+
+it('keeps a named modal through loading, failure, retry, and closing before restoring focus', async () => {
+ await page.viewport(1280, 900);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host, {
+ onCaughtError: (error) => {
+ if (!(error instanceof Error) || error.message !== 'Settings chunk unavailable') {
+ throw error;
+ }
+ },
+ });
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <button type="button" onClick={() => openWorkbenchSettings('behavior')}>
+ Open settings
+ </button>
+ <SettingsDialogHost />
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ const trigger = page.getByRole('button', { name: 'Open settings', exact: true });
+ await act(() => trigger.click());
+ await expect.element(page.getByRole('dialog', { name: 'Settings', exact: true })).toBeVisible();
+ await expect.element(page.getByRole('status')).toHaveTextContent(i18n.t('common.loading'));
+ expect(isHotkeyModalLayerActive()).toBe(true);
+
+ await act(() => initialLoad.reject(new Error('Settings chunk unavailable')));
+ await expect.element(page.getByRole('alert')).toHaveTextContent(i18n.t('settingsDialog.loadFailed'));
+ await expect.element(page.getByRole('dialog', { name: 'Settings', exact: true })).toBeVisible();
+ const retry = page.getByRole('button', { name: i18n.t('common.retry'), exact: true });
+ await expect.element(retry).toBeEnabled();
+ expect(isHotkeyModalLayerActive()).toBe(true);
+ await act(() => retry.click());
+ await expect.element(page.getByRole('alert')).toHaveAttribute('aria-busy', 'true');
+ expect(isHotkeyModalLayerActive()).toBe(true);
+ await act(() => initialLoad.resolveRetry());
+
+ await expect.element(page.getByRole('dialog', { name: 'Settings: Behavior', exact: true })).toBeVisible();
+ await expect.element(page.getByRole('alert')).not.toBeInTheDocument();
+ expect(isHotkeyModalLayerActive()).toBe(true);
+ await page.getByRole('textbox', { name: 'Search settings', exact: true }).click();
+ await expect.element(page.getByRole('textbox', { name: 'Search settings', exact: true })).toHaveFocus();
+ await act(() =>
+ document.querySelector<HTMLButtonElement>('[data-scope="dialog"][data-part="close-trigger"]')!.click()
+ );
+ expect(document.querySelector('[data-scope="dialog"][data-part="content"][data-state="closed"]')).not.toBeNull();
+ expect(isHotkeyModalLayerActive()).toBe(true);
+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
+ await expect.element(trigger).toHaveFocus();
+ expect(isHotkeyModalLayerActive()).toBe(false);
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx
index b139d2339a..8f2e4048d4 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogHost.tsx
@@ -1,26 +1,86 @@
-import { lazy, Suspense } from 'react';
+import { Dialog, Portal, Text } from '@chakra-ui/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { CloseButton } from '@platform/ui';
+import { RetryBoundary } from '@platform/ui/RetryBoundary';
+import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
+import { Suspense, use, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { settingsDialogResource as dialogResource } from './dialogResource';
import { closeWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';
+const LoadedDialog = () => {
+ const { default: SettingsDialog } = use(dialogResource.load());
+ return <SettingsDialog />;
+};
+
+const SettingsModalLayer = () => {
+ useMountEffect(() => registerHotkeyModalLayer('settings'));
+ return null;
+};
-/**
- * Mounts the settings dialog wherever it is placed, driven entirely by the
- * store. Every surface that can open settings — the app menu, a widget header
- * gear, a command — writes to the same store, so the dialog body must not be
- * owned by any one trigger.
- *
- * The body reaches into workbench commands, the persistence service, and every
- * settings section, so importing it eagerly made the Launchpad pay for the whole
- * editor composition — aggregate project state included — before the user had
- * opened a project. It arrives on first open.
- */
-const LazySettingsDialog = lazy(() => import('./SettingsDialog'));
+const getReturnFocus = () => {
+ const element = settingsDialogStore.getSnapshot().returnFocus;
+ return element?.isConnected ? element : null;
+};
+const handleOpenChange = ({ open }: { open: boolean }) => {
+ if (!open) {
+ closeWorkbenchSettings();
+ }
+};
+/** The presence owner remains mounted; only the editor body is deferred. */
export const SettingsDialogHost = () => {
+ const { t } = useTranslation();
+ const loading = useMemo(
+ () => (
+ <Dialog.Body p="5">
+ <Dialog.Title>{t('settings.title')}</Dialog.Title>
+ <Text role="status">{t('common.loading')}</Text>
+ </Dialog.Body>
+ ),
+ [t]
+ );
const isOpen = settingsDialogStore.useSelector((snapshot) => snapshot.isOpen);
-
- return isOpen ? (
- <Suspense fallback={null}>
- <LazySettingsDialog isOpen onClose={closeWorkbenchSettings} />
- </Suspense>
- ) : null;
+ const generation = settingsDialogStore.useSelector((snapshot) => snapshot.generation);
+ return (
+ <Dialog.Root
+ key={generation}
+ open={isOpen}
+ lazyMount
+ unmountOnExit
+ scrollBehavior="inside"
+ placement="center"
+ size="xl"
+ finalFocusEl={getReturnFocus}
+ onOpenChange={handleOpenChange}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content
+ aria-label={t('settings.title')}
+ h="min(48rem, calc(100dvh - 2rem))"
+ maxW="64rem"
+ w="calc(100dvw - 2rem)"
+ overflow="hidden"
+ p="0"
+ >
+ <SettingsModalLayer />
+ <RetryBoundary
+ retry={dialogResource.retry}
+ message={t('settingsDialog.loadFailed')}
+ retryLabel={t('common.retry')}
+ >
+ <Suspense fallback={loading}>
+ <LoadedDialog />
+ </Suspense>
+ </RetryBoundary>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton aria-label={t('common.close')} />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ );
};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx
new file mode 100644
index 0000000000..da0000bb4b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx
@@ -0,0 +1,133 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { Project } from '@workbench/projectContracts';
+import type * as projectsApi from '@workbench/projects/api';
+import type { WidgetRuntimeApi, WidgetViewProps } from '@workbench/widgetContracts';
+import type * as workbenchContext from '@workbench/WorkbenchContext';
+import type { WorkbenchInternalStore, WorkbenchSnapshot } from '@workbench/workbenchStore';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+import { system } from '@theme/system';
+import { canvasWidgetManifest } from '@workbench/widgets/canvas/manifest';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { settingsDialogResource } from './dialogResource';
+import { SettingsDialogHost } from './SettingsDialogHost';
+import { closeWorkbenchSettings, settingsDialogStore } from './settingsDialogStore';
+import { DEFAULT_PREFERENCES, patchWorkbenchPreferences } from './store';
+import { WidgetSettingsButton } from './WidgetSettingsButton';
+
+const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
+ useActiveProjectId: () => {
+ const store = storeRef.current!;
+ return useExternalStoreSelector(store.subscribe, store.getSnapshot, (snapshot) => snapshot.activeProject.id);
+ },
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => {
+ const store = storeRef.current!;
+ return useExternalStoreSelector(store.subscribe, store.getSnapshot, (snapshot) => selector(snapshot.activeProject));
+ },
+ useOptionalWorkbenchSelector: (selector: (snapshot: WorkbenchSnapshot) => unknown) => {
+ const store = storeRef.current!;
+ return useExternalStoreSelector(store.subscribe, store.getSnapshot, selector);
+ },
+ useWorkbenchCommands: () => storeRef.current!.commands,
+ useWorkbenchQueries: () => storeRef.current!.queries,
+ useWorkbenchSubscription: () => storeRef.current!.subscribe,
+ useHasWorkbenchProvider: () => true,
+}));
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof projectsApi>()),
+ setClientStateValue: async () => {},
+}));
+
+const translations = await fetch('/locales/en.json').then((response) => response.json());
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translation: translations } } });
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let root: Root;
+let host: HTMLDivElement;
+let widgetProps: WidgetViewProps;
+
+beforeEach(async () => {
+ accountLifecycle.activate('settings-target-test');
+ await patchWorkbenchPreferences(DEFAULT_PREFERENCES);
+ await Promise.all([settingsDialogResource.load(), import('./WidgetQuickSettings')]);
+ const state = createInitialWorkbenchState();
+ const project = state.projects[0]!;
+ const canvas = project.widgetInstances.canvas!;
+ project.widgetInstances['canvas-copy'] = {
+ ...canvas,
+ id: 'canvas-copy',
+ state: { ...canvas.state, values: { ...canvas.state.values, showGrid: true } },
+ };
+ storeRef.current = createWorkbenchStore(state);
+ widgetProps = {
+ instance: { ...project.widgetInstances['canvas-copy']!, title: 'Other Canvas' },
+ manifest: canvasWidgetManifest,
+ region: 'center',
+ runtime: {} as WidgetRuntimeApi,
+ };
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ closeWorkbenchSettings();
+ accountLifecycle.invalidate();
+});
+
+it('edits another widget through global search while retaining the originating Canvas instance', async () => {
+ const store = storeRef.current!;
+ const before = store.getSnapshot().activeProject;
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <WidgetSettingsButton {...widgetProps} />
+ <SettingsDialogHost />
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+ await act(() => page.getByRole('button', { name: 'Canvas settings', exact: true }).click());
+ await act(() =>
+ page
+ .getByRole('button', { name: i18n.t('settingsDialog.allWidgetSettings', { widget: 'Canvas' }), exact: true })
+ .click()
+ );
+ const search = page.getByRole('textbox', { name: i18n.t('settingsDialog.search'), exact: true });
+ await expect.element(search).toBeVisible();
+ await act(() => search.fill('filmstrip'));
+ const filmstrip = page.getByRole('checkbox', { name: i18n.t('widgets.preview.showFilmstrip'), exact: true });
+ await expect.element(filmstrip).toBeEnabled();
+ await act(() => page.getByText(i18n.t('widgets.preview.showFilmstrip'), { exact: true }).click());
+ await expect
+ .poll(() => store.getSnapshot().activeProject.widgetInstances.preview!.state.values.filmstripVisible)
+ .toBe(false);
+ const afterPreview = store.getSnapshot().activeProject;
+ expect(afterPreview.widgetInstances.canvas).toBe(before.widgetInstances.canvas);
+ expect(afterPreview.widgetInstances['canvas-copy']).toBe(before.widgetInstances['canvas-copy']);
+ expect(Object.keys(afterPreview.widgetInstances)).toEqual(Object.keys(before.widgetInstances));
+
+ await act(() => search.fill('show grid'));
+ const grid = page.getByRole('checkbox', { name: i18n.t('widgets.canvas.settings.grid'), exact: true });
+ await expect.element(grid).toBeChecked();
+ await act(() => page.getByText(i18n.t('widgets.canvas.settings.grid'), { exact: true }).click());
+ await expect
+ .poll(() => store.getSnapshot().activeProject.widgetInstances['canvas-copy']!.state.values.showGrid)
+ .toBe(false);
+ expect(store.getSnapshot().activeProject.widgetInstances.canvas).toBe(before.widgetInstances.canvas);
+ expect(settingsDialogStore.getSnapshot().target).toEqual({ projectId: before.id, instanceId: 'canvas-copy' });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx
new file mode 100644
index 0000000000..4913d62111
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsEntryView.tsx
@@ -0,0 +1,156 @@
+import type { SettingsTarget } from '@platform/ui/settings/contracts';
+
+import { Box, Stack, Text } from '@chakra-ui/react';
+import { Button } from '@platform/ui/Button';
+import { RetryBoundary } from '@platform/ui/RetryBoundary';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { getProjectWidgetInstance } from '@workbench/widgetState';
+import { useOptionalWorkbenchSelector } from '@workbench/WorkbenchContext';
+import { Suspense, use, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { SettingsEntry, SettingsSection } from './catalog';
+
+import { settingsDialogStore } from './settingsDialogStore';
+import { SettingsScopeLabel } from './SettingsScopeLabel';
+
+const LoadedSetting = ({
+ entry,
+ target,
+ surface,
+}: {
+ entry: SettingsEntry;
+ target?: SettingsTarget;
+ surface: 'quick' | 'dialog';
+}) => {
+ const { Field } = use(entry.resource.load());
+ const attach = useCallback(
+ (element: HTMLDivElement | null) => {
+ if (!element || surface !== 'dialog' || settingsDialogStore.getSnapshot().entryId !== entry.field.id) {
+ return;
+ }
+ const control = element.querySelector<HTMLElement>('input,button,[tabindex="0"]');
+ element.scrollIntoView({ block: 'nearest' });
+ control?.focus({ preventScroll: true });
+ settingsDialogStore.patchSnapshot({ entryId: undefined });
+ },
+ [entry.field.id, surface]
+ );
+ return (
+ <Box ref={attach}>
+ <Field field={entry.field} surface={surface} target={target} />
+ </Box>
+ );
+};
+
+export const SettingsEntryView = ({
+ entry,
+ section,
+ target: requestedTarget,
+ surface = 'dialog',
+ search = false,
+ onReveal,
+ showGroup = false,
+}: {
+ entry: SettingsEntry;
+ section: SettingsSection;
+ target?: SettingsTarget;
+ surface?: 'quick' | 'dialog';
+ search?: boolean;
+ onReveal?: (sectionId: string, entryId: string) => void;
+ showGroup?: boolean;
+}) => {
+ const { t } = useTranslation();
+ const target = useOptionalWorkbenchSelector((snapshot) => {
+ const project = snapshot.activeProject;
+ if (requestedTarget && requestedTarget.projectId !== project.id) {
+ return null;
+ }
+ const instance = requestedTarget?.instanceId
+ ? project.widgetInstances[requestedTarget.instanceId]
+ : section.widgetId
+ ? getProjectWidgetInstance(project, section.widgetId)
+ : undefined;
+ if (entry.field.scope === 'instance' && (!instance || instance.typeId !== section.widgetId)) {
+ return null;
+ }
+ return { projectId: project.id, instanceId: instance?.id };
+ }, null);
+ const reveal = useCallback(() => onReveal?.(section.id, entry.field.id), [onReveal, section.id, entry.field.id]);
+ const loading = useMemo(
+ () => (
+ <Text role="status" fontSize="xs" color="fg.muted">
+ {t('common.loading')}
+ </Text>
+ ),
+ [t]
+ );
+ const unavailable = (entry.field.scope === 'instance' || entry.field.scope === 'project') && !target;
+ const scope = entry.field.scope;
+ const isDestination = search && entry.field.kind === 'custom';
+ return (
+ <>
+ {showGroup && entry.field.group ? (
+ <Text
+ as="h3"
+ pt={surface === 'quick' ? '2' : '5'}
+ pb="1"
+ fontWeight="600"
+ fontSize={surface === 'quick' ? '2xs' : 'xs'}
+ color="fg.muted"
+ >
+ {resolveSettingsText(entry.field.group, t)}
+ </Text>
+ ) : null}
+ <Box
+ data-setting-id={entry.field.id}
+ py={surface === 'quick' ? '1.5' : '4'}
+ borderBottomWidth="1px"
+ borderColor="border.subtle"
+ >
+ {unavailable || isDestination ? (
+ <Stack gap="2">
+ <Text fontSize="sm" fontWeight="500">
+ {resolveSettingsText(entry.field.label, t)}
+ </Text>
+ {entry.field.description ? (
+ <Text fontSize="xs" color="fg.muted">
+ {resolveSettingsText(entry.field.description, t)}
+ </Text>
+ ) : null}
+ {unavailable ? (
+ <Text fontSize="xs" color="fg.muted">
+ {t(scope === 'instance' ? 'settingsDialog.instanceUnavailable' : 'settingsDialog.projectUnavailable')}
+ </Text>
+ ) : (
+ <Button size="xs" variant="outline" alignSelf="start" onClick={reveal}>
+ {t('settingsDialog.openEditor')}
+ </Button>
+ )}
+ </Stack>
+ ) : (
+ <RetryBoundary
+ key={`${entry.field.id}:${target?.projectId ?? ''}:${target?.instanceId ?? ''}`}
+ retry={entry.resource.retry}
+ message={t('settingsDialog.loadFailed')}
+ retryLabel={t('common.retry')}
+ >
+ <Suspense fallback={loading}>
+ <LoadedSetting entry={entry} target={target ?? undefined} surface={surface} />
+ </Suspense>
+ </RetryBoundary>
+ )}
+ {surface === 'dialog' && scope !== section.entries[0]?.field.scope ? (
+ <Box mt="2">
+ <SettingsScopeLabel scope={scope} />
+ </Box>
+ ) : null}
+ {search && !isDestination ? (
+ <Button size="2xs" variant="ghost" mt="1" onClick={reveal}>
+ {t('settingsDialog.showInSection')}
+ </Button>
+ ) : null}
+ </Box>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsScopeLabel.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsScopeLabel.tsx
new file mode 100644
index 0000000000..e3a8c59a65
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsScopeLabel.tsx
@@ -0,0 +1,20 @@
+import type { SettingDefinition } from '@platform/ui/settings/contracts';
+
+import { Text } from '@chakra-ui/react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkbenchSettingsSelector } from './store';
+
+export const SettingsScopeLabel = ({ scope }: { scope: SettingDefinition['scope'] }) => {
+ const { t } = useTranslation();
+ const preferenceScope = useWorkbenchSettingsSelector((snapshot) => snapshot.scope);
+ if (scope === 'none') {
+ return null;
+ }
+ const label = scope === 'preference' && preferenceScope === 'global' ? 'install' : scope;
+ return (
+ <Text fontSize="2xs" color="fg.muted">
+ {t(`settingsDialog.scope.${label}`)}
+ </Text>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/WidgetQuickSettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/WidgetQuickSettings.tsx
new file mode 100644
index 0000000000..251dea35b5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/WidgetQuickSettings.tsx
@@ -0,0 +1,44 @@
+import type { WidgetViewProps } from '@workbench/widgetContracts';
+
+import { Box } from '@chakra-ui/react';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { useActiveProjectId } from '@workbench/WorkbenchContext';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { settingsCatalog } from './catalog';
+import { SettingsEntryView } from './SettingsEntryView';
+
+const QUICK_GROUP_STYLES = { '& > h3:first-of-type': { paddingTop: '0' } };
+
+const WidgetQuickSettings = ({ manifest, instance }: WidgetViewProps) => {
+ const { t } = useTranslation();
+ const projectId = useActiveProjectId();
+ const target = useMemo(() => ({ projectId, instanceId: instance.id }), [projectId, instance.id]);
+ const section = settingsCatalog.find((candidate) => candidate.id === manifest.settings?.id);
+ if (!section) {
+ return null;
+ }
+ const entries =
+ manifest.settings?.quick?.flatMap((id) => section.entries.filter((entry) => entry.field.id === id)) ?? [];
+ return (
+ <Box css={QUICK_GROUP_STYLES}>
+ {entries.map((entry, index) => {
+ const group = entry.field.group ? resolveSettingsText(entry.field.group, t) : '';
+ const previousGroup = entries[index - 1]?.field.group;
+ const showGroup = Boolean(group && group !== (previousGroup ? resolveSettingsText(previousGroup, t) : ''));
+ return (
+ <SettingsEntryView
+ key={entry.field.id}
+ entry={entry}
+ section={section}
+ target={target}
+ surface="quick"
+ showGroup={showGroup}
+ />
+ );
+ })}
+ </Box>
+ );
+};
+export default WidgetQuickSettings;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/WidgetSettingsButton.tsx b/invokeai/frontend/webv2/src/workbench/settings/WidgetSettingsButton.tsx
new file mode 100644
index 0000000000..370aae4a50
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/WidgetSettingsButton.tsx
@@ -0,0 +1,156 @@
+import type { WidgetHeaderActions, WidgetViewProps } from '@workbench/widgetContracts';
+
+import { Box, Icon, Popover, Portal, Text } from '@chakra-ui/react';
+import { Button, IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { RetryBoundary } from '@platform/ui/RetryBoundary';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { createDeferredResource } from '@workbench/deferredResource';
+import { useActiveProjectId, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { SettingsIcon } from 'lucide-react';
+import { Suspense, use, useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { openWorkbenchSettings } from './settingsDialogStore';
+
+const quickResource = createDeferredResource(() => import('./WidgetQuickSettings'));
+const QuickSettings = (props: WidgetViewProps) => {
+ const { default: Content } = use(quickResource.load());
+ return <Content {...props} />;
+};
+
+const QUICK_POSITIONING = { placement: 'bottom-end' } as const;
+type WidgetSettingsButtonProps = WidgetViewProps & { SettingsActions?: WidgetHeaderActions };
+
+/** Changing the project or instance disposes any open popover and its deferred content. */
+export const WidgetSettingsButton = (props: WidgetSettingsButtonProps) => {
+ const projectId = useActiveProjectId();
+ return <TargetedWidgetSettingsButton key={`${projectId}:${props.instance.id}`} projectId={projectId} {...props} />;
+};
+
+/** All widget placements share one gear and one popover-to-dialog handoff. */
+const TargetedWidgetSettingsButton = ({
+ SettingsActions,
+ projectId,
+ ...props
+}: WidgetSettingsButtonProps & { projectId: string }) => {
+ const { t } = useTranslation();
+ const [presentation, setPresentation] = useState<'closed' | 'quick' | 'dialog'>('closed');
+ const trigger = useRef<HTMLButtonElement>(null);
+ const queries = useWorkbenchQueries();
+ const contribution = props.manifest.settings;
+ const sectionId = contribution?.id;
+ const instanceId = props.instance.id;
+ const typeId = props.manifest.id;
+ const isTargetCurrent = useCallback(
+ () =>
+ queries.isActiveProject(projectId) &&
+ queries.getProject(projectId)?.widgetInstances[instanceId]?.typeId === typeId,
+ [queries, projectId, instanceId, typeId]
+ );
+ const openDialog = useCallback(() => {
+ if (!sectionId || !isTargetCurrent()) {
+ return;
+ }
+ // A controlled close may also emit onOpenChange(false); it must retain this handoff state.
+ setPresentation('dialog');
+ openWorkbenchSettings({ sectionId, target: { projectId, instanceId } }, trigger.current ?? undefined);
+ }, [sectionId, isTargetCurrent, projectId, instanceId]);
+ const handleOpenChange = useCallback(
+ ({ open }: { open: boolean }) => {
+ if (open) {
+ if (isTargetCurrent()) {
+ setPresentation('quick');
+ }
+ } else {
+ setPresentation((current) => (current === 'dialog' ? current : 'closed'));
+ }
+ },
+ [isTargetCurrent]
+ );
+ const getReturnFocus = useCallback(() => trigger.current, []);
+ const loading = useMemo(
+ () => (
+ <Text role="status" fontSize="xs" color="fg.muted">
+ {t('common.loading')}
+ </Text>
+ ),
+ [t]
+ );
+
+ if (!contribution) {
+ return null;
+ }
+ const label = resolveSettingsText(contribution.label, t);
+ if (!contribution.quick?.length) {
+ return (
+ <Tooltip content={t('widgets.settingsLabel', { label })}>
+ <IconButton
+ ref={trigger}
+ aria-label={t('widgets.settingsLabel', { label })}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={openDialog}
+ >
+ <Icon as={SettingsIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ );
+ }
+ return (
+ <Popover.Root
+ open={presentation === 'quick'}
+ lazyMount
+ unmountOnExit
+ positioning={QUICK_POSITIONING}
+ onOpenChange={handleOpenChange}
+ restoreFocus={presentation !== 'dialog'}
+ finalFocusEl={getReturnFocus}
+ >
+ <Popover.Trigger asChild>
+ <IconButton
+ ref={trigger}
+ aria-label={t('widgets.settingsLabel', { label })}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ >
+ <Icon as={SettingsIcon} boxSize="3.5" />
+ </IconButton>
+ </Popover.Trigger>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent w="18rem">
+ <Scrollable maxH="min(38rem, calc(100dvh - 4rem))">
+ <Popover.Body p="2.5">
+ <Popover.Title fontSize="xs" fontWeight="600" mb="1">
+ {t('widgets.settingsLabel', { label })}
+ </Popover.Title>
+ <RetryBoundary
+ retry={quickResource.retry}
+ message={t('settingsDialog.loadFailed')}
+ retryLabel={t('common.retry')}
+ >
+ <Suspense fallback={loading}>
+ <QuickSettings {...props} />
+ </Suspense>
+ </RetryBoundary>
+ {SettingsActions ? (
+ <Box pt="2">
+ <SettingsActions {...props} />
+ </Box>
+ ) : null}
+ <Button size="xs" variant="ghost" w="full" mt="2" onClick={openDialog}>
+ {t('settingsDialog.allWidgetSettings', { widget: label })}
+ </Button>
+ </Popover.Body>
+ </Scrollable>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
new file mode 100644
index 0000000000..009b495739
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts
@@ -0,0 +1,141 @@
+import type { SettingDefinition, SettingsContribution, SettingsText } from '@platform/ui/settings/contracts';
+
+import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
+
+const text =
+ (key: string, fallback?: string): SettingsText =>
+ (t) =>
+ t(`settings.catalog.${key}`, { defaultValue: fallback });
+const preference = (id: string, label: string, keywords?: string): SettingDefinition => ({
+ id,
+ label: text(`${id}.label`, label),
+ description: text(`${id}.description`),
+ keywords,
+ kind: 'boolean',
+ scope: 'preference',
+});
+const custom = (id: string, label: string, scope: SettingDefinition['scope'] = 'preference'): SettingDefinition => ({
+ id,
+ label: text(`${id}.label`, label),
+ description: text(`${id}.description`),
+ kind: 'custom',
+ scope,
+});
+const section = (id: string, label: string, fields: readonly SettingDefinition[]): SettingsContribution => ({
+ id,
+ label: text(`sections.${id}`, label),
+ fields,
+ load: () => import('./ApplicationSettingField').then((module) => ({ Field: module.ApplicationSettingField })),
+});
+
+export const appearanceSettings = section('appearance', 'Appearance', [
+ custom('themeId', 'Theme'),
+ {
+ id: 'language',
+ label: text('language.label', 'Language'),
+ kind: 'select',
+ scope: 'preference',
+ options: WORKBENCH_LANGUAGE_OPTIONS,
+ },
+ preference('reduceMotion', 'Reduce motion', 'animation'),
+ preference('showFocusRegionHighlight', 'Highlight focused regions', 'panel outline'),
+]);
+export const behaviorSettings = section('behavior', 'Behavior', [
+ preference('autoSwitchInvocationRoute', 'Auto-switch Invoke route'),
+ preference('enableInformationalPopovers', 'Enable informational popovers', 'help tooltips'),
+ preference('enableModelDescriptions', 'Show model descriptions', 'models'),
+ preference('notifyOnEnqueue', 'Notify when queued', 'notifications queue'),
+ preference('preferNumericAttentionStyle', 'Prefer numeric attention style', 'generate prompt editor'),
+ preference('showPromptSyntaxHighlighting', 'Highlight prompt syntax', 'generate prompt editor'),
+]);
+export const hotkeysSettings = section('hotkeys', 'Keyboard shortcuts', [custom('hotkeys', 'Keyboard shortcuts')]);
+export const projectSettings = section('project', 'Project', [
+ {
+ ...preference('useCpuNoise', 'Use CPU noise'),
+ scope: 'project',
+ },
+]);
+export const galleryPreferenceSettings = section('gallery', 'Gallery', [
+ preference('confirmImageDeletion', 'Confirm image deletion', 'delete safety'),
+]);
+export const previewProjectSettings = section('preview', 'Preview', [
+ {
+ ...preference('antialiasProgressImages', 'Antialias progress images'),
+ scope: 'project',
+ },
+]);
+export const workflowSettings = section('workflow', 'Workflow', [
+ {
+ id: 'workflowEdgeStyle',
+ label: text('workflowEdgeStyle.label', 'Connection style'),
+ description: text('workflowEdgeStyle.description'),
+ kind: 'select',
+ scope: 'preference',
+ options: [
+ { value: 'curved', label: text('options.curved', 'Curved') },
+ { value: 'square', label: text('options.square', 'Square') },
+ ],
+ },
+ preference('workflowSnapToGrid', 'Always snap to grid', 'workflow nodes'),
+ preference('workflowShowMinimap', 'Show minimap'),
+ preference('workflowValidateConnections', 'Validate connections', 'workflow edges'),
+]);
+export const queueSettings = section('queue', 'Queue', [
+ {
+ id: 'queueJobsScope',
+ label: text('queueJobsScope.label', 'Show jobs from'),
+ description: text('queueJobsScope.description'),
+ kind: 'select',
+ scope: 'preference',
+ options: [
+ { value: 'active-project', label: text('options.activeProject', 'Active project') },
+ { value: 'all', label: text('options.all', 'All projects') },
+ ],
+ },
+]);
+export const imageMapVocabularySettings = section('imageMap', 'Image Map', [
+ custom('imageMapVocabulary', 'Vocabulary', 'server'),
+]);
+export const developerSettings = section('developer', 'Developer', [
+ preference('developerLogEnabled', 'Record diagnostic logs', 'debug console'),
+ {
+ id: 'developerLogLevel',
+ label: text('developerLogLevel.label', 'Log level'),
+ kind: 'select',
+ scope: 'preference',
+ options: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'].map((value) => ({
+ value,
+ label: text(`options.${value}`, value.charAt(0).toUpperCase() + value.slice(1)),
+ })),
+ },
+ preference('developerPerformanceTimingsEnabled', 'Collect performance timings', 'diagnostics'),
+ custom('developerLogNamespaces', 'Log namespaces'),
+]);
+export const serverSettings = section('server', 'Server', [
+ custom('generationDevices', 'Generation devices', 'server'),
+]);
+export const workspaceSettings = section('workspace', 'Data & workspace', [
+ custom('workspaceActions', 'Data & workspace', 'none'),
+]);
+export const aboutSettings = section('about', 'About', [custom('about', 'About InvokeAI', 'none')]);
+
+export const applicationSettingsContributions = [
+ appearanceSettings,
+ behaviorSettings,
+ hotkeysSettings,
+ projectSettings,
+ galleryPreferenceSettings,
+ previewProjectSettings,
+ imageMapVocabularySettings,
+ developerSettings,
+ serverSettings,
+ workspaceSettings,
+ aboutSettings,
+];
+/** These are the same descriptors rendered in settings and used by palette preference actions. */
+export const preferenceSettingsFields = [...applicationSettingsContributions, workflowSettings, queueSettings].flatMap(
+ (contribution) =>
+ contribution.fields
+ .filter((field) => field.scope === 'preference' && field.kind !== 'custom')
+ .map((field) => ({ field, sectionId: contribution.id }))
+);
diff --git a/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts
new file mode 100644
index 0000000000..2be96da880
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/catalog.test.ts
@@ -0,0 +1,145 @@
+import type { SettingDefinition, SettingsContribution } from '@platform/ui/settings/contracts';
+import type { WidgetManifest } from '@workbench/widgetContracts';
+
+import { createInstance } from 'i18next';
+import { EyeIcon } from 'lucide-react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildSettingsCatalog, searchSettings } from './catalog';
+
+const field = (id: string, overrides: Partial<SettingDefinition> = {}): SettingDefinition =>
+ ({ id, kind: 'boolean', label: id, scope: 'preference', ...overrides }) as SettingDefinition;
+const contribution = (id: string, fields: readonly SettingDefinition[]): SettingsContribution => ({
+ fields,
+ id,
+ label: id,
+ load: vi.fn(() => Promise.resolve({ Field: () => null })),
+});
+const widget = (settings: SettingsContribution): WidgetManifest => ({
+ allowMultiple: false,
+ allowedRegions: ['right'],
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ icon: EyeIcon,
+ id: 'preview',
+ label: 'Preview widget',
+ load: vi.fn(() => Promise.resolve({ view: () => null })),
+ settings,
+ version: 1,
+});
+
+const i18n = createInstance();
+await i18n.init({
+ lng: 'fr',
+ resources: {
+ fr: {
+ translation: {
+ section: 'Aperçu',
+ label: 'Arrière-plan',
+ description: 'Afficher les zones transparentes',
+ group: 'Visibilité',
+ option: 'Damier',
+ },
+ },
+ },
+});
+
+describe('settings catalog composition', () => {
+ it('builds and searches metadata without loading editors or widget implementations', () => {
+ const application = contribution('appearance', [field('motion')]);
+ const previewSettings = contribution('preview', [field('filmstrip')]);
+ const preview = widget(previewSettings);
+ const sections = buildSettingsCatalog([application], [preview]);
+
+ expect(searchSettings(sections, 'filmstrip', i18n.t).map((section) => section.id)).toEqual(['preview']);
+ expect(application.load).not.toHaveBeenCalled();
+ expect(previewSettings.load).not.toHaveBeenCalled();
+ expect(preview.load).not.toHaveBeenCalled();
+ });
+
+ it('merges application fields with their widget section while retaining field bindings and widget identity', async () => {
+ const previewSettings = contribution('preview', [field('filmstrip', { scope: 'instance' })]);
+ previewSettings.label = 'Preview preferences';
+ const projectSettings = contribution('preview', [field('antialias', { scope: 'project' })]);
+ const preview = widget(previewSettings);
+ const sections = buildSettingsCatalog([projectSettings], [preview]);
+
+ expect(sections).toHaveLength(1);
+ const section = sections[0]!;
+ expect(section).toMatchObject({
+ group: 'widgets',
+ icon: EyeIcon,
+ id: 'preview',
+ label: 'Preview preferences',
+ widgetId: 'preview',
+ });
+ expect(section.entries.map((entry) => entry.field)).toEqual([previewSettings.fields[0], projectSettings.fields[0]]);
+ const [instanceEntry, projectEntry] = section.entries;
+ await instanceEntry!.resource.load();
+ expect(previewSettings.load).toHaveBeenCalledOnce();
+ expect(projectSettings.load).not.toHaveBeenCalled();
+ await projectEntry!.resource.load();
+ expect(projectSettings.load).toHaveBeenCalledOnce();
+ });
+
+ it('rejects duplicate entry IDs inside a contribution and across a merged section', () => {
+ expect(() => buildSettingsCatalog([contribution('appearance', [field('motion'), field('motion')])], [])).toThrow(
+ 'Duplicate or empty setting appearance.motion'
+ );
+ expect(() =>
+ buildSettingsCatalog(
+ [contribution('preview', [field('filmstrip')])],
+ [widget(contribution('preview', [field('filmstrip')]))]
+ )
+ ).toThrow('Duplicate or empty setting preview.filmstrip');
+ });
+
+ it('rejects empty entry IDs and quick placements that do not belong to the contribution', () => {
+ expect(() => buildSettingsCatalog([contribution('appearance', [field('')])], [])).toThrow(
+ 'Duplicate or empty setting appearance.'
+ );
+ const previewSettings = contribution('preview', [field('filmstrip')]);
+ previewSettings.quick = ['antialias'];
+ expect(() =>
+ buildSettingsCatalog([contribution('preview', [field('antialias')])], [widget(previewSettings)])
+ ).toThrow('Unknown quick setting preview.antialias');
+ });
+});
+
+describe('settings search', () => {
+ const display = field('display', {
+ description: (t) => t('description'),
+ group: (t) => t('group'),
+ keywords: 'checkerboard alpha',
+ kind: 'select',
+ label: (t) => t('label'),
+ options: [{ label: (t) => t('option'), value: 'checker' }],
+ });
+ const previewSettings = contribution('preview', [
+ display,
+ field('vocabulary', { kind: 'custom', label: 'Vocabulary editor', keywords: 'semantic categories' }),
+ ]);
+ previewSettings.label = (t) => t('section');
+ const sections = buildSettingsCatalog([], [widget(previewSettings)]);
+ const resultIds = (query: string) =>
+ searchSettings(sections, query, i18n.t).flatMap((section) => section.entries.map((entry) => entry.field.id));
+
+ it.each(['ARRIERE', 'transparentes', 'visibilite', 'damier', 'checkerboard', 'alpha'])(
+ 'finds localized metadata and explicit aliases: %s',
+ (query) => {
+ expect(resultIds(query)).toEqual(['display']);
+ }
+ );
+
+ it('requires every word across section, label, description, group, options, and aliases', () => {
+ expect(resultIds(' APERCU arriere transparentes VISIBILITE damier ALPHA ')).toEqual(['display']);
+ expect(resultIds('arriere missing')).toEqual([]);
+ });
+
+ it('keeps custom editors searchable destinations and preserves catalog order', () => {
+ expect(resultIds('semantic editor')).toEqual(['vocabulary']);
+ expect(resultIds('apercu')).toEqual(['display', 'vocabulary']);
+ expect(resultIds(' ')).toEqual(['display', 'vocabulary']);
+ expect(searchSettings(sections, 'categories', i18n.t)[0]!.entries[0]!.field.kind).toBe('custom');
+ expect(previewSettings.load).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/catalog.ts b/invokeai/frontend/webv2/src/workbench/settings/catalog.ts
new file mode 100644
index 0000000000..62a53ebf13
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/catalog.ts
@@ -0,0 +1,123 @@
+import type { SettingDefinition, SettingsContribution, SettingsText } from '@platform/ui/settings/contracts';
+import type { DeferredResource } from '@workbench/deferredResource';
+import type { WidgetIconComponent, WidgetManifest } from '@workbench/widgetContracts';
+import type { TFunction } from 'i18next';
+
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { createDeferredResource } from '@workbench/deferredResource';
+import { firstPartyWidgetManifests } from '@workbench/widgets/manifests';
+import {
+ Code2Icon,
+ DatabaseIcon,
+ FolderIcon,
+ InfoIcon,
+ KeyboardIcon,
+ PaletteIcon,
+ ServerIcon,
+ SlidersHorizontalIcon,
+} from 'lucide-react';
+
+import { applicationSettingsContributions } from './applicationContributions';
+
+export interface SettingsEntry {
+ field: SettingDefinition;
+ resource: DeferredResource<Awaited<ReturnType<SettingsContribution['load']>>>;
+}
+export interface SettingsSection {
+ id: string;
+ label: SettingsText;
+ group: 'application' | 'project' | 'widgets' | 'system';
+ icon: WidgetIconComponent;
+ widgetId?: string;
+ entries: readonly SettingsEntry[];
+}
+
+const sectionPresentation = {
+ appearance: { group: 'application', icon: PaletteIcon },
+ behavior: { group: 'application', icon: SlidersHorizontalIcon },
+ hotkeys: { group: 'application', icon: KeyboardIcon },
+ project: { group: 'project', icon: FolderIcon },
+ developer: { group: 'system', icon: Code2Icon },
+ server: { group: 'system', icon: ServerIcon },
+ workspace: { group: 'system', icon: DatabaseIcon },
+ about: { group: 'system', icon: InfoIcon },
+} as const;
+const groupOrder = ['application', 'project', 'widgets', 'system'];
+
+/** Pure composition and validation; constructing a catalog never invokes a loader. */
+export const buildSettingsCatalog = (
+ applications: readonly SettingsContribution[],
+ widgets: readonly WidgetManifest[]
+): SettingsSection[] => {
+ const sections = new Map<string, SettingsSection>();
+ const add = (contribution: SettingsContribution, widget?: WidgetManifest) => {
+ const existing = sections.get(contribution.id);
+ const ids = new Set(existing?.entries.map((entry) => entry.field.id));
+ const localIds = new Set(contribution.fields.map((field) => field.id));
+ for (const id of contribution.quick ?? []) {
+ if (!localIds.has(id)) {
+ throw new Error(`Unknown quick setting ${contribution.id}.${id}`);
+ }
+ }
+ const resource = createDeferredResource(contribution.load);
+ const entries = contribution.fields.map((field) => {
+ if (!field.id || ids.has(field.id)) {
+ throw new Error(`Duplicate or empty setting ${contribution.id}.${field.id}`);
+ }
+ ids.add(field.id);
+ return { field, resource };
+ });
+ const presentation = sectionPresentation[contribution.id as keyof typeof sectionPresentation];
+ sections.set(contribution.id, {
+ id: contribution.id,
+ label: widget?.settings?.label ?? existing?.label ?? contribution.label,
+ group: widget ? 'widgets' : (existing?.group ?? presentation?.group ?? 'widgets'),
+ icon: widget?.icon ?? existing?.icon ?? presentation?.icon ?? SlidersHorizontalIcon,
+ widgetId: widget?.id ?? existing?.widgetId,
+ entries: [...(existing?.entries ?? []), ...entries],
+ });
+ };
+ for (const widget of widgets) {
+ if (widget.settings) {
+ add(widget.settings, widget);
+ }
+ }
+ for (const contribution of applications) {
+ add(contribution);
+ }
+ return [...sections.values()].sort(
+ (a, b) =>
+ groupOrder.indexOf(a.group) - groupOrder.indexOf(b.group) ||
+ (a.group === 'widgets' ? a.id.localeCompare(b.id) : 0)
+ );
+};
+
+export const settingsCatalog = buildSettingsCatalog(applicationSettingsContributions, firstPartyWidgetManifests);
+
+const normalize = (value: string): string => value.normalize('NFD').replace(/\p{M}/gu, '').toLocaleLowerCase();
+export const searchSettings = (
+ sections: readonly SettingsSection[],
+ query: string,
+ t: TFunction
+): SettingsSection[] => {
+ const words = normalize(query).trim().split(/\s+/).filter(Boolean);
+ if (!words.length) {
+ return [...sections];
+ }
+ return sections.flatMap((section) => {
+ const entries = section.entries.filter(({ field }) => {
+ const text = normalize(
+ [
+ resolveSettingsText(section.label, t),
+ resolveSettingsText(field.label, t),
+ field.description ? resolveSettingsText(field.description, t) : '',
+ field.group ? resolveSettingsText(field.group, t) : '',
+ field.keywords ?? '',
+ field.kind === 'select' ? field.options.map((option) => resolveSettingsText(option.label, t)).join(' ') : '',
+ ].join(' ')
+ );
+ return words.every((word) => text.includes(word));
+ });
+ return entries.length ? [{ ...section, entries }] : [];
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
index 2d9ff79841..fe15207d63 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts
@@ -1,4 +1,5 @@
import type { WorkbenchLanguage } from '@platform/i18n/languages';
+import type { SettingsTarget } from '@platform/ui/settings/contracts';
import type { WorkbenchThemeId } from '@theme/themes';
import type { DeveloperLogLevel, DeveloperLogNamespace } from '@workbench/diagnostics/contracts';
import type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';
@@ -96,3 +97,10 @@ export interface WorkbenchPreferences {
/** User-saved Generate settings snapshots ("recipes"), in the order they were saved. */
generatePresets: StoredGeneratePreset[];
}
+
+export type SettingsSectionId = string;
+export interface SettingsDestination {
+ sectionId: SettingsSectionId;
+ entryId?: string;
+ target?: SettingsTarget;
+}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/dialogResource.ts b/invokeai/frontend/webv2/src/workbench/settings/dialogResource.ts
new file mode 100644
index 0000000000..6a2c1c83f1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/dialogResource.ts
@@ -0,0 +1,7 @@
+import { createDeferredResource } from '@workbench/deferredResource';
+
+export const settingsDialogResource = createDeferredResource(async () => {
+ const module = await import('./SettingsDialog');
+ await module.prepareSettingsDialog();
+ return module;
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.test.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.test.ts
new file mode 100644
index 0000000000..94be851459
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.test.ts
@@ -0,0 +1,96 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ closeWorkbenchSettings,
+ getSettingsSectionScroll,
+ openWorkbenchSettings,
+ rememberSettingsSectionScroll,
+ setSettingsQuery,
+ setWorkbenchSettingsSection,
+ settingsDialogStore,
+} from './settingsDialogStore';
+
+beforeEach(() => accountLifecycle.activate('settings-navigation-test'));
+
+describe('settings navigation', () => {
+ it('opens a specific widget instance and field, clearing stale search state', () => {
+ openWorkbenchSettings('appearance');
+ setSettingsQuery('motion');
+ settingsDialogStore.patchSnapshot({ searchSection: 'appearance' });
+ const target = { instanceId: 'canvas-instance', projectId: 'project-a' };
+
+ openWorkbenchSettings({ entryId: 'showGrid', sectionId: 'canvas', target });
+
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({
+ entryId: 'showGrid',
+ isOpen: true,
+ query: '',
+ searchSection: null,
+ sectionId: 'canvas',
+ target,
+ });
+ });
+
+ it('remembers the browsed section after closing but releases an explicit target when reopened generically', () => {
+ openWorkbenchSettings({
+ entryId: 'showGrid',
+ sectionId: 'canvas',
+ target: { projectId: 'project-a', instanceId: 'canvas-instance' },
+ });
+ closeWorkbenchSettings();
+ expect(settingsDialogStore.getSnapshot().isOpen).toBe(false);
+ openWorkbenchSettings();
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({
+ entryId: undefined,
+ isOpen: true,
+ sectionId: 'canvas',
+ target: undefined,
+ });
+ });
+
+ it('clears section filtering while editing the query without changing the browsing destination', () => {
+ openWorkbenchSettings('canvas');
+ setSettingsQuery('grid');
+ rememberSettingsSectionScroll('canvas', 320);
+ settingsDialogStore.patchSnapshot({ searchSection: 'canvas' });
+ setSettingsQuery('');
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({ query: '', searchSection: null, sectionId: 'canvas' });
+ });
+
+ it('reveals an entry in its section and removes the prior widget target and search', () => {
+ openWorkbenchSettings({ sectionId: 'canvas', target: { projectId: 'project-a', instanceId: 'canvas-instance' } });
+ setSettingsQuery('filmstrip');
+ setWorkbenchSettingsSection('preview', 'filmstripVisible');
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({
+ entryId: 'filmstripVisible',
+ query: '',
+ searchSection: null,
+ sectionId: 'preview',
+ target: undefined,
+ });
+ });
+
+ it('clears destinations and search synchronously on account changes, invalidating the prior dialog generation', () => {
+ openWorkbenchSettings({
+ sectionId: 'canvas',
+ entryId: 'showGrid',
+ target: { projectId: 'project-a', instanceId: 'canvas-instance' },
+ });
+ setSettingsQuery('grid');
+ const generation = settingsDialogStore.getSnapshot().generation;
+ accountLifecycle.activate('other-user');
+
+ expect(getSettingsSectionScroll('canvas')).toBe(0);
+ expect(settingsDialogStore.getSnapshot()).toEqual({
+ generation: generation + 1,
+ isOpen: false,
+ query: '',
+ returnFocus: null,
+ searchSection: null,
+ sectionId: 'appearance',
+ });
+ openWorkbenchSettings();
+ expect(settingsDialogStore.getSnapshot().sectionId).toBe('appearance');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
index 851849f7b2..c39173a345 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/settingsDialogStore.ts
@@ -1,43 +1,78 @@
-import type { SettingsSectionId } from '@workbench/widgetContracts';
-
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
-/**
- * Open/close state for the workbench settings dialog, addressable from
- * anywhere: widget frames, menus, and commands call `openWorkbenchSettings`
- * with the section they want. The dialog itself is hosted by the top bar's
- * `SettingsButton`, which subscribes to this store.
- */
+import type { SettingsDestination, SettingsSectionId } from './contracts';
+
+import { settingsDialogResource } from './dialogResource';
-interface SettingsDialogSnapshot {
+interface SettingsDialogSnapshot extends SettingsDestination {
isOpen: boolean;
- sectionId: SettingsSectionId;
+ query: string;
+ searchSection: string | null;
+ returnFocus: HTMLElement | null;
+ generation: number;
}
-
-const INITIAL_SETTINGS_DIALOG_SNAPSHOT: SettingsDialogSnapshot = {
+const initialSnapshot = (): SettingsDialogSnapshot => ({
isOpen: false,
sectionId: 'appearance',
+ query: '',
+ searchSection: null,
+ returnFocus: null,
+ generation: 0,
+});
+export const settingsDialogStore = createExternalStore<SettingsDialogSnapshot>(initialSnapshot());
+const sectionScrollPositions = new Map<SettingsSectionId, number>();
+export const getSettingsSectionScroll = (sectionId: SettingsSectionId): number =>
+ sectionScrollPositions.get(sectionId) ?? 0;
+export const rememberSettingsSectionScroll = (sectionId: SettingsSectionId, offset: number): void => {
+ sectionScrollPositions.set(sectionId, offset);
};
-
-export const settingsDialogStore = createExternalStore<SettingsDialogSnapshot>(INITIAL_SETTINGS_DIALOG_SNAPSHOT);
-
registerAccountOwnedResource({
+ name: 'settings-dialog',
clear: () => {
- settingsDialogStore.setSnapshot(INITIAL_SETTINGS_DIALOG_SNAPSHOT);
+ sectionScrollPositions.clear();
+ settingsDialogStore.setSnapshot({
+ ...initialSnapshot(),
+ generation: settingsDialogStore.getSnapshot().generation + 1,
+ });
},
- name: 'settings-dialog',
});
-/** Open the workbench settings dialog, optionally at a specific section. */
-export const openWorkbenchSettings = (sectionId: SettingsSectionId = 'appearance'): void => {
- settingsDialogStore.setSnapshot({ isOpen: true, sectionId });
+export const openWorkbenchSettings = (
+ destination?: SettingsSectionId | SettingsDestination,
+ returnFocus?: HTMLElement
+): void => {
+ settingsDialogResource.preload();
+ const current = settingsDialogStore.getSnapshot();
+ const next = typeof destination === 'string' ? { sectionId: destination } : destination;
+ settingsDialogStore.setSnapshot({
+ ...current,
+ isOpen: true,
+ query: '',
+ searchSection: null,
+ entryId: undefined,
+ target: undefined,
+ ...next,
+ returnFocus:
+ returnFocus ??
+ (typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null),
+ });
};
-
export const closeWorkbenchSettings = (): void => {
settingsDialogStore.patchSnapshot({ isOpen: false });
};
-
-export const setWorkbenchSettingsSection = (sectionId: SettingsSectionId): void => {
- settingsDialogStore.patchSnapshot({ sectionId });
+export const setWorkbenchSettingsSection = (sectionId: SettingsSectionId, entryId?: string): void => {
+ settingsDialogStore.patchSnapshot({
+ sectionId,
+ entryId,
+ query: '',
+ searchSection: null,
+ target:
+ settingsDialogStore.getSnapshot().sectionId === sectionId ? settingsDialogStore.getSnapshot().target : undefined,
+ });
+};
+export const setSettingsQuery = (query: string): void => {
+ settingsDialogStore.patchSnapshot({ query, searchSection: null, entryId: undefined });
};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.browser.test.tsx
new file mode 100644
index 0000000000..6710528d7c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.browser.test.tsx
@@ -0,0 +1,124 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { SettingsTarget } from '@platform/ui/settings/contracts';
+import type { Project } from '@workbench/projectContracts';
+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { useExternalStoreSelector } from '@platform/state/selectors';
+import { system } from '@theme/system';
+import { Field as CanvasField } from '@workbench/widgets/canvas/settingsBindings';
+import { canvasSettingsContribution } from '@workbench/widgets/canvas/settingsContribution';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act, createRef, useImperativeHandle } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useWidgetSettingsTarget } from './useWidgetSettingsTarget';
+
+const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => {
+ const store = storeRef.current!;
+ return useExternalStoreSelector(store.subscribe, store.getSnapshot, (snapshot) => selector(snapshot.activeProject));
+ },
+ useWorkbenchCommands: () => storeRef.current!.commands,
+ useWorkbenchQueries: () => storeRef.current!.queries,
+}));
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({ lng: 'en', resources: {} });
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement;
+let root: Root;
+const bindingRef = createRef<{ patch(values: Record<string, unknown>): void }>();
+const Probe = ({ target }: { target?: SettingsTarget }) => {
+ const binding = useWidgetSettingsTarget('canvas', target, (values) => values.showGrid === true);
+ useImperativeHandle(bindingRef, () => binding, [binding]);
+ return <output data-disabled={binding.disabled}>{String(binding.value)}</output>;
+};
+
+const interact = (run: () => void) =>
+ act(async () => {
+ run();
+ await Promise.resolve();
+ });
+
+beforeEach(() => {
+ accountLifecycle.activate('settings-test');
+ storeRef.current = createWorkbenchStore();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(async () => {
+ await interact(() => root.unmount());
+ host.remove();
+});
+
+describe('widget settings target', () => {
+ it('shares Canvas preferences between quick and dialog controls through the real aggregate', async () => {
+ const field = canvasSettingsContribution.fields.find((candidate) => candidate.id === 'showGrid')!;
+ await interact(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <CanvasField field={field} surface="quick" />
+ <CanvasField field={field} surface="dialog" />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ const controls = Array.from(host.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'));
+ expect(controls).toHaveLength(2);
+ expect(controls.every((control) => !control.checked)).toBe(true);
+ await interact(() => controls[0]!.click());
+ expect(controls.every((control) => control.checked)).toBe(true);
+ expect(storeRef.current!.getSnapshot().activeProject.widgetInstances.canvas!.state.values.showGrid).toBe(true);
+ await interact(() => controls[1]!.click());
+ expect(controls.every((control) => !control.checked)).toBe(true);
+ });
+
+ it('edits an explicit instance without retargeting the default instance', async () => {
+ const state = createInitialWorkbenchState();
+ const project = state.projects[0]!;
+ project.widgetInstances['canvas-copy'] = { ...project.widgetInstances.canvas!, id: 'canvas-copy' };
+ storeRef.current = createWorkbenchStore(state);
+ await interact(() => root.render(<Probe target={{ instanceId: 'canvas-copy', projectId: project.id }} />));
+ await interact(() => bindingRef.current!.patch({ showGrid: true }));
+ const instances = storeRef.current.getSnapshot().activeProject.widgetInstances;
+ expect(instances['canvas-copy']!.state.values.showGrid).toBe(true);
+ expect(instances.canvas!.state.values.showGrid).toBeUndefined();
+ });
+
+ it('disables a removed or wrong-type target without creating an instance', async () => {
+ const store = storeRef.current!;
+ const projectId = store.getSnapshot().activeProject.id;
+ for (const instanceId of ['missing', 'preview']) {
+ await interact(() => root.render(<Probe target={{ instanceId, projectId }} />));
+ expect(host.querySelector('output')?.dataset.disabled).toBe('true');
+ const before = store.getSnapshot();
+ await interact(() => bindingRef.current!.patch({ showGrid: true }));
+ expect(store.getSnapshot()).toBe(before);
+ }
+ });
+
+ it('rejects stale writes after a project switch and account rotation', async () => {
+ const store = storeRef.current!;
+ await interact(() => root.render(<Probe />));
+ const previousPatch = bindingRef.current!.patch;
+ const firstProjectId = store.getSnapshot().activeProject.id;
+ await interact(() => {
+ store.commands.projects.create();
+ });
+ await interact(() => previousPatch({ showGrid: true }));
+ expect(store.queries.getProject(firstProjectId)!.widgetInstances.canvas!.state.values.showGrid).toBeUndefined();
+ accountLifecycle.activate('next-account');
+ const before = store.getSnapshot();
+ await interact(() => bindingRef.current!.patch({ showGrid: true }));
+ expect(store.getSnapshot()).toBe(before);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts
new file mode 100644
index 0000000000..e4de01a75d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts
@@ -0,0 +1,44 @@
+import type { SettingsTarget } from '@platform/ui/settings/contracts';
+import type { WidgetTypeId } from '@workbench/widgetContracts';
+
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { getProjectWidgetInstance } from '@workbench/widgetState';
+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useCallback, useState } from 'react';
+
+/** Selects only one field and fences writes against removed instances and project/account changes. */
+export const useWidgetSettingsTarget = <Value extends boolean | string | number>(
+ widgetId: WidgetTypeId,
+ target: SettingsTarget | undefined,
+ read: (values: Record<string, unknown>) => Value
+) => {
+ const [accountScope] = useState(captureAccountScope);
+ const queries = useWorkbenchQueries();
+ const { widgets } = useWorkbenchCommands();
+ const instanceId = useActiveProjectSelector((project) => {
+ if (target && target.projectId !== project.id) {
+ return undefined;
+ }
+ const instance = target?.instanceId
+ ? project.widgetInstances[target.instanceId]
+ : getProjectWidgetInstance(project, widgetId);
+ return instance?.typeId === widgetId ? instance.id : undefined;
+ });
+ const projectId = useActiveProjectSelector((project) => project.id);
+ const value = useActiveProjectSelector((project) =>
+ read(project.widgetInstances[instanceId ?? '']?.state.values ?? {})
+ );
+ const patch = useCallback(
+ (values: Record<string, unknown>) => {
+ if (!instanceId || !isAccountScopeCurrent(accountScope) || !queries.isActiveProject(projectId)) {
+ return;
+ }
+ const project = queries.getProject(projectId);
+ if (project?.widgetInstances[instanceId]?.typeId === widgetId) {
+ widgets.patchInstanceValues(instanceId, values, projectId);
+ }
+ },
+ [accountScope, instanceId, projectId, queries, widgetId, widgets]
+ );
+ return { disabled: !instanceId, patch, value };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
index 47644ecf7d..84dbcc93bf 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
@@ -9,6 +9,7 @@ import type {
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
+import { closeWorkbenchSettings, settingsDialogStore } from '@workbench/settings/settingsDialogStore';
import i18next from 'i18next';
import { MapIcon, TagsIcon } from 'lucide-react';
import { act } from 'react';
@@ -19,9 +20,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* A floated widget renders bare inside this window, so its header controls
* only exist here — the map's label and selection toggles used to disappear on
- * float. The window mounts the widget's own actions and nothing else: the
- * frame-level chrome (settings, the overflow menu, the float control) is
- * replaced by this bar's shade/maximize/dock buttons.
+ * float. The window mounts widget actions and the shared settings gear, with
+ * its own shade/maximize/dock controls replacing the frame's layout controls.
*/
const windowMocks = vi.hoisted(() => ({
@@ -33,20 +33,26 @@ const windowMocks = vi.hoisted(() => ({
setFloatingMode: vi.fn(),
}));
+const project = {
+ id: 'project-1',
+ widgetInstances: {
+ 'image-map-instance': {
+ createdAt: 0,
+ id: 'image-map-instance',
+ state: { values: {} },
+ typeId: 'image-map',
+ },
+ },
+ widgetRegions: { center: { activeInstanceId: null, instanceIds: [] } },
+};
+
vi.mock('@workbench/WorkbenchContext', () => ({
- useActiveProjectSelector: (selector: (project: unknown) => unknown) =>
- selector({
- id: 'project-1',
- widgetInstances: {
- 'image-map-instance': {
- createdAt: 0,
- id: 'image-map-instance',
- state: { values: {} },
- typeId: 'image-map',
- },
- },
- widgetRegions: { center: { activeInstanceId: null, instanceIds: [] } },
- }),
+ useActiveProjectSelector: (selector: (project: unknown) => unknown) => selector(project),
+ useActiveProjectId: () => project.id,
+ useWorkbenchQueries: () => ({
+ getProject: (projectId: string) => (projectId === project.id ? project : null),
+ isActiveProject: (projectId: string) => projectId === project.id,
+ }),
useWorkbenchCommands: () => ({ widgets: windowMocks }),
}));
@@ -63,9 +69,8 @@ vi.mock('./createWidgetRuntime', () => ({ useWidgetRuntime: () => ({}) }));
import { FloatingWidgetWindow } from './FloatingWidgetWindow';
-// `settingsSection` and `headerMenu` are what separate the widget's own
-// actions from the full header cluster: were the window to mount the `actions`
-// slot instead, the settings gear and the overflow trigger would appear here.
+// The floating slot includes settings, while the overflow menu belongs to the
+// full docked header cluster.
const manifest = {
allowFloating: true,
allowedRegions: ['center', 'left', 'right'],
@@ -73,7 +78,7 @@ const manifest = {
icon: MapIcon,
id: 'image-map',
label: () => 'Image Map',
- settingsSection: 'image-map',
+ settings: { id: 'imageMap', label: 'Image Map', fields: [], load: () => Promise.resolve({ Field: () => null }) },
version: 1,
} as unknown as WidgetManifest;
@@ -130,6 +135,7 @@ await i18n.use(initReactI18next).init({
widgets: {
floating: { dock: 'Dock to panel', maximize: 'Maximize', move: 'Move {{label}} window', shade: 'Shade' },
labels: { imageMap: 'Image Map' },
+ settingsLabel: '{{label}} settings',
},
},
},
@@ -159,6 +165,7 @@ const renderWindow = async (floatingState: FloatingWidgetState = state) => {
};
beforeEach(() => {
+ closeWorkbenchSettings();
windowMocks.actionsRegion = null;
windowMocks.useFailingWidget = false;
windowMocks.dockFloating.mockClear();
@@ -184,17 +191,30 @@ describe('FloatingWidgetWindow chrome', () => {
expect(windowMocks.actionsRegion).toBe('floating');
});
- it('leaves the frame-level chrome to the window, which carries its own', async () => {
+ it('keeps one shared settings gear without duplicating the window layout controls', async () => {
await renderWindow();
- // The manifest has a settings section and the implementation a header
- // menu, so the full actions cluster would put both in this bar.
- expect(host?.querySelector('button[aria-label*="settings"]')).toBeNull();
+ expect(host?.querySelectorAll('button[aria-label="Image Map settings"]')).toHaveLength(1);
expect(host?.querySelector('button[aria-label*="actions"]')).toBeNull();
expect(host?.querySelector('button[aria-label="Float Window"]')).toBeNull();
expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();
});
+ it('opens settings for the floating widget instance and remembers its gear for focus restoration', async () => {
+ await renderWindow();
+ const gear = host!.querySelector<HTMLButtonElement>('button[aria-label="Image Map settings"]')!;
+ await act(async () => {
+ gear.click();
+ await Promise.resolve();
+ });
+ expect(settingsDialogStore.getSnapshot()).toMatchObject({
+ isOpen: true,
+ sectionId: 'imageMap',
+ target: { instanceId: 'image-map-instance', projectId: 'project-1' },
+ });
+ expect(settingsDialogStore.getSnapshot().returnFocus).toBe(gear);
+ });
+
it('keeps the window usable when the widget implementation fails to load', async () => {
windowMocks.useFailingWidget = true;
@@ -238,6 +258,7 @@ describe('FloatingWidgetWindow chrome', () => {
await renderWindow({ ...state, mode: 'shaded' });
expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).not.toBeNull();
+ expect(host?.querySelector('button[aria-label="Image Map settings"]')).not.toBeNull();
expect(host?.querySelector('[data-testid="map-body"]')).toBeNull();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx
index 0ccb790a8d..f502b99a08 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx
@@ -1,4 +1,5 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type * as workbenchContext from '@workbench/WorkbenchContext';
import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
import { ChakraProvider } from '@chakra-ui/react';
@@ -19,7 +20,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const storeRef = vi.hoisted(() => ({ current: null as WorkbenchInternalStore | null }));
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
shallowEqual: Object.is,
useActiveProjectSelector: (selector: (project: never) => unknown) => {
const store = storeRef.current!;
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
index 5cae5619f2..fe83796931 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
@@ -1,5 +1,6 @@
-/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
import type { RegisteredWidget, WidgetManifest, WidgetTypeId, WorkbenchRegion } from '@workbench/widgetContracts';
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type * as workbenchContext from '@workbench/WorkbenchContext';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
@@ -27,7 +28,8 @@ vi.mock('@platform/react/draftRegistry', () => ({
flushWorkbenchDrafts: floatMocks.flushWorkbenchDrafts,
}));
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
useActiveProjectSelector: (selector: (project: unknown) => unknown) =>
selector({
id: 'project-1',
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
index 292e9b4c99..ca553dcf3f 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
@@ -2,6 +2,7 @@ import type { WidgetRegion } from '@workbench/layoutContracts';
import type {
WidgetInstanceId,
WidgetInstanceRuntimeMeta,
+ WidgetHeaderActions,
WidgetHeaderLabel,
WidgetHeaderMenu,
WidgetManifest,
@@ -14,9 +15,10 @@ import { Box, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';
import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { useMountEffect } from '@platform/react/useMountEffect';
import { IconButton } from '@platform/ui/Button';
+import { PanelHeader } from '@platform/ui/PanelHeader';
import { Tooltip } from '@platform/ui/Tooltip';
import { useFocusRegionProps } from '@workbench/focusRegions';
-import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
+import { WidgetSettingsButton } from '@workbench/settings/WidgetSettingsButton';
import { resolveWidgetInstanceLabel } from '@workbench/widgetLabels';
import { getEnabledCenterViewCount } from '@workbench/widgetPlacementCommands';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
@@ -28,7 +30,7 @@ import {
shouldSnapPanelShutAt,
} from '@workbench/workbenchState';
import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';
-import { PictureInPicture2Icon, SettingsIcon } from 'lucide-react';
+import { PictureInPicture2Icon } from 'lucide-react';
import {
useCallback,
useEffect,
@@ -357,6 +359,7 @@ export const WidgetFloatButton = ({
export const WidgetHeaderActionsGroup = ({
actions,
HeaderMenu,
+ SettingsActions,
instance,
manifest,
region,
@@ -364,33 +367,23 @@ export const WidgetHeaderActionsGroup = ({
}: {
actions?: ReactNode;
HeaderMenu?: WidgetHeaderMenu;
+ SettingsActions?: WidgetHeaderActions;
instance: WidgetInstanceRuntimeMeta;
manifest: WidgetManifest;
region: WorkbenchRegion;
runtime: WidgetRuntimeApi;
}) => {
- const { t } = useTranslation();
- const label = resolveWidgetInstanceLabel(instance, manifest, t);
- const handleSettingsClick = useCallback(
- () => openWorkbenchSettings(manifest.settingsSection),
- [manifest.settingsSection]
- );
-
return (
<HStack flexShrink={0} gap="0.5">
{actions}
- {manifest.settingsSection ? (
- <Tooltip content={t('widgets.settingsLabel', { label })}>
- <IconButton
- aria-label={t('widgets.settingsLabel', { label })}
- color="fg.muted"
- size="2xs"
- variant="ghost"
- onClick={handleSettingsClick}
- >
- <Icon as={SettingsIcon} boxSize="3.5" />
- </IconButton>
- </Tooltip>
+ {manifest.settings ? (
+ <WidgetSettingsButton
+ SettingsActions={SettingsActions}
+ instance={instance}
+ manifest={manifest}
+ region={region}
+ runtime={runtime}
+ />
) : null}
<WidgetFloatButton instanceId={instance.id} manifest={manifest} region={region} />
<WidgetActionsMenu
@@ -408,6 +401,7 @@ export const WidgetHeader = ({
actions,
HeaderLabel,
HeaderMenu,
+ SettingsActions,
instance,
manifest,
region,
@@ -416,6 +410,7 @@ export const WidgetHeader = ({
actions?: ReactNode;
HeaderLabel?: WidgetHeaderLabel;
HeaderMenu?: WidgetHeaderMenu;
+ SettingsActions?: WidgetHeaderActions;
instance: WidgetInstanceRuntimeMeta;
manifest: WidgetManifest;
region: WorkbenchRegion;
@@ -427,7 +422,7 @@ export const WidgetHeader = ({
const label = resolveWidgetInstanceLabel(instance, manifest, t);
return (
- <HStack justify="space-between" borderBottomWidth={1} h={10} ps="3" pe="2">
+ <PanelHeader>
<HStack flex="1" gap="1.5" minW="0">
<WidgetIdentityIcon icon={manifest.icon} />
{HeaderLabel && !instance.title ? (
@@ -441,13 +436,14 @@ export const WidgetHeader = ({
</HStack>
<WidgetHeaderActionsGroup
HeaderMenu={HeaderMenu}
+ SettingsActions={SettingsActions}
actions={actions}
instance={instance}
manifest={manifest}
region={region}
runtime={runtime}
/>
- </HStack>
+ </PanelHeader>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx
index 2b100fbf0a..2bf729c1ce 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx
@@ -1,5 +1,6 @@
-/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */
import type { NormalizedWidgetManifest, RegisteredWidget, WidgetInstanceContract } from '@workbench/widgetContracts';
+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */
+import type * as workbenchContext from '@workbench/WorkbenchContext';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
@@ -13,7 +14,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
// Panel frames read the region's persisted size; the fallback under test only
// needs a stable one, so the store is stubbed rather than booted.
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
shallowEqual: Object.is,
useActiveProjectSelector: (
selector: (project: {
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx
index 4c38015f60..b76f9ca422 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx
@@ -1,4 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type * as workbenchContext from '@workbench/WorkbenchContext';
+
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
import { FocusRegionProvider } from '@workbench/focusRegions';
@@ -17,7 +19,8 @@ const frameMocks = vi.hoisted(() => ({
// The frame reads the region's persisted size and writes back through the
// layout commands; both are stubbed so the drag arithmetic is what is under
// test, not the reducer.
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
shallowEqual: Object.is,
useActiveProjectSelector: (
selector: (project: {
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx
index 57365ab579..27c0cc8779 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx
@@ -1,10 +1,11 @@
-/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
import type {
NormalizedWidgetManifest,
RegisteredWidget,
WidgetImplementation,
WidgetInstanceContract,
} from '@workbench/widgetContracts';
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type * as workbenchContext from '@workbench/WorkbenchContext';
import { ChakraProvider, Stack, Text } from '@chakra-ui/react';
import { StatusWidgetChip } from '@platform/ui';
@@ -35,8 +36,14 @@ const workbenchMocks = vi.hoisted(() => ({
runtime: {},
}));
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof workbenchContext>()),
shallowEqual: Object.is,
+ useActiveProjectId: () => workbenchMocks.project.id,
+ useWorkbenchQueries: () => ({
+ getProject: (projectId: string) => (projectId === workbenchMocks.project.id ? workbenchMocks.project : null),
+ isActiveProject: (projectId: string) => projectId === workbenchMocks.project.id,
+ }),
useActiveProjectSelector: (selector: (project: typeof workbenchMocks.project) => unknown) =>
selector(workbenchMocks.project),
useWorkbenchCommands: () => ({ layout: { setRegionCollapsed: () => {}, setRegionSize: () => {} } }),
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
index e6653974b4..c7bc80d45f 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx
@@ -13,6 +13,7 @@ import { Box, Flex, Text } from '@chakra-ui/react';
import { getWidgetReadyMark, markSemanticReady } from '@platform/performance/semanticReady';
import { useMountEffect } from '@platform/react/useMountEffect';
import { Scrollable } from '@platform/ui/Scrollable';
+import { WidgetSettingsButton } from '@workbench/settings/WidgetSettingsButton';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';
@@ -37,8 +38,8 @@ interface WidgetRendererByIdProps extends Omit<WidgetViewProps, 'instance' | 'ma
/**
* The chrome slots a region can hoist out of the widget frame. `actions` is the
* full trailing cluster (widget actions, settings, float, overflow menu);
- * `viewActions` is the widget's own `headerActions` alone, for chrome that
- * already carries its own frame controls.
+ * `viewActions` contains widget actions and settings, for chrome that already
+ * carries its own layout controls.
*/
type WidgetChromeSlotName = 'actions' | 'label' | 'viewActions';
@@ -137,15 +138,27 @@ const WidgetChromeSlot = ({
}
// The window chrome around a floating widget already carries the frame's own
- // controls (shade, maximize, dock), so it takes the widget's actions alone —
- // a floated widget keeps the toggles its docked header shows.
+ // controls (shade, maximize, dock). Preferences remain available beside the
+ // widget's own actions without duplicating those layout controls.
if (slot === 'viewActions') {
- return actions;
+ return (
+ <>
+ {actions}
+ <WidgetSettingsButton
+ SettingsActions={implementation.settingsActions}
+ instance={instanceMeta}
+ manifest={widget.manifest}
+ region={region}
+ runtime={runtime}
+ />
+ </>
+ );
}
return (
<WidgetHeaderActionsGroup
HeaderMenu={implementation.headerMenu}
+ SettingsActions={implementation.settingsActions}
actions={actions}
instance={instanceMeta}
manifest={widget.manifest}
@@ -381,6 +394,7 @@ const HeaderSlot = memo(function HeaderSlot({
<WidgetHeader
HeaderLabel={implementation.headerLabel}
HeaderMenu={implementation.headerMenu}
+ SettingsActions={implementation.settingsActions}
actions={actions}
instance={instance}
manifest={widget.manifest}
diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
index eafd8b7960..4478aba409 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
@@ -1,3 +1,4 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
import type { TFunction } from 'i18next';
import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps } from 'react';
@@ -94,6 +95,7 @@ export type WidgetHost = ComponentType;
export interface WidgetImplementation {
view: WidgetView;
headerActions?: WidgetHeaderActions;
+ settingsActions?: WidgetHeaderActions;
headerLabel?: WidgetHeaderLabel;
headerMenu?: WidgetHeaderMenu;
footer?: WidgetFooter;
@@ -273,19 +275,6 @@ export interface WidgetWorkbenchApi {
closeWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;
}
-/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */
-export type SettingsSectionId =
- | 'appearance'
- | 'behavior'
- | 'hotkeys'
- | 'project'
- | 'queue'
- | 'workflow'
- | 'imageMap'
- | 'developer'
- | 'workspace'
- | 'about';
-
export interface WidgetManifest {
/** Widget runtime API contract version. Defaults to 1 during registry normalization. */
apiVersion?: 1;
@@ -321,8 +310,8 @@ export interface WidgetManifest {
* its own chunk.
*/
loadHost?: () => Promise<WidgetHost>;
- /** When set, the frame header shows a gear that opens this settings dialog section. */
- settingsSection?: SettingsSectionId;
+ /** Shared definitions for the shell's quick controls and full settings dialog. */
+ settings?: SettingsContribution;
state?: WidgetStateRegistration;
graphBearing?: {
sourceId: InvocationSourceId;
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
index bfbb3834a0..1e7a67e7b9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
@@ -11,41 +11,9 @@ import { getAuthSession } from '@features/identity';
import { createDeferredResource } from './deferredResource';
import { createWidgetImplementationResource } from './widgetImplementationResource';
-import { autosaveStatusWidgetManifest } from './widgets/autosave-status/manifest';
-import { canvasWidgetManifest } from './widgets/canvas/manifest';
-import { diagnosticsWidgetManifest } from './widgets/diagnostics/manifest';
-import { galleryWidgetManifest } from './widgets/gallery/manifest';
-import { generateWidgetManifest } from './widgets/generate/manifest';
-import { imageMapWidgetManifest } from './widgets/image-map/manifest';
-import { layersWidgetManifest } from './widgets/layers/manifest';
-import { notificationsWidgetManifest } from './widgets/notifications/manifest';
-import { previewWidgetManifest } from './widgets/preview/manifest';
-import { projectWidgetManifest } from './widgets/project/manifest';
-import { queueStatusWidgetManifest } from './widgets/queue-status/manifest';
-import { queueWidgetManifest } from './widgets/queue/manifest';
-import { serverStatusWidgetManifest } from './widgets/server-status/manifest';
-import { upscaleWidgetManifest } from './widgets/upscale/manifest';
-import { videoWidgetManifest } from './widgets/video/manifest';
-import { workflowWidgetManifest } from './widgets/workflow/manifest';
-
-export const firstPartyWidgetManifests: WidgetManifest[] = [
- generateWidgetManifest,
- workflowWidgetManifest,
- upscaleWidgetManifest,
- videoWidgetManifest,
- canvasWidgetManifest,
- diagnosticsWidgetManifest,
- galleryWidgetManifest,
- imageMapWidgetManifest,
- previewWidgetManifest,
- projectWidgetManifest,
- layersWidgetManifest,
- queueWidgetManifest,
- notificationsWidgetManifest,
- serverStatusWidgetManifest,
- queueStatusWidgetManifest,
- autosaveStatusWidgetManifest,
-];
+import { firstPartyWidgetManifests } from './widgets/manifests';
+
+export { firstPartyWidgetManifests } from './widgets/manifests';
const createFailure = (widgetId: WidgetTypeId, error: unknown): WidgetFailure => ({
details: error instanceof Error ? (error.stack ?? error.message) : String(error),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index 2cd978f384..8c46b89b99 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -4,15 +4,16 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
-import { Box, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
import { useModifierHeld } from '@platform/react/useModifierHeld';
-import { IconButton } from '@platform/ui/Button';
+import { Button, IconButton } from '@platform/ui/Button';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
import { MenuContent } from '@platform/ui/Menu';
import { Tooltip } from '@platform/ui/Tooltip';
+import { getCanvasEngine } from '@workbench/canvas-operations/api';
import { useNotify } from '@workbench/useNotify';
import { getProjectWidgetValues } from '@workbench/widgetState';
-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
import {
BugIcon,
CheckIcon,
@@ -22,16 +23,15 @@ import {
FrameIcon,
MaximizeIcon,
Redo2Icon,
- SettingsIcon,
SquareDashedBottomIcon,
Trash2Icon,
Undo2Icon,
} from 'lucide-react';
-import { Fragment, useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
+import { useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { CanvasHeaderCommandContext } from './canvasHeaderCommands';
-import type { CanvasBooleanSetting, ResolvedCanvasSettings } from './canvasSettings';
+import type { ResolvedCanvasSettings } from './canvasSettings';
import { gridSizeForModelBase } from './bboxGrid';
import {
@@ -40,13 +40,7 @@ import {
executeCanvasHeaderCommand,
zoomAtViewportCentre,
} from './canvasHeaderCommands';
-import {
- CANVAS_SETTING_SECTIONS,
- CANVAS_SETTINGS,
- CANVAS_SNAP_TO_GRID_KEY,
- canvasSettingsEqual,
- resolveCanvasSettings,
-} from './canvasSettings';
+import { CANVAS_SNAP_TO_GRID_KEY, canvasSettingsEqual, resolveCanvasSettings } from './canvasSettings';
import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';
import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';
import { useCanvasEngine } from './useCanvasEngine';
@@ -74,7 +68,7 @@ const selectModelBase = (project: Project): string | null => {
/**
* Canvas widget header actions, in legacy toolbar order: the zoom-percent menu, a
* reset-view (fit content to view) button, fit-bbox-to-layers / fit-bbox-to-masks,
- * undo / redo, a new-session menu, and the sectioned settings popover. Rendered in
+ * undo / redo, and a new-session menu. Rendered in
* the widget frame's header slot; resolves the shared engine like the layers header
* does, and renders nothing until it is available.
*
@@ -281,8 +275,6 @@ const CanvasHeaderActionsInner = ({
</Portal>
</Menu.Root>
- <CanvasSettingsMenu editingLocked={editingLocked} engine={engine} />
-
<ConfirmDialog
body={t('widgets.canvas.controls.newCanvasConfirm')}
confirmLabel={t('widgets.canvas.controls.newCanvas')}
@@ -298,78 +290,43 @@ const CanvasHeaderActionsInner = ({
/** A thin vertical rule separating header-action groups (matching legacy's dividers). */
const HeaderDivider = () => <Box bg="border.subtle" flexShrink={0} h="4" mx="1" w="1px" />;
-/**
- * The gear-icon settings popover: the data-driven boolean preferences grouped into
- * Behavior / Display / Grid sections, plus a Shift-revealed Debug group of engine
- * actions (matching legacy `CanvasSettingsPopover`). `closeOnSelect={false}` keeps
- * it open while toggling. Settings persist per-project and never enter undo history.
- */
-const CanvasSettingsMenu = ({ editingLocked, engine }: { editingLocked: boolean; engine: CanvasHeaderEngine }) => {
+/** Diagnostics use an existing engine; opening settings must never acquire a canvas engine lease. */
+export const CanvasSettingsActions = (_props: WidgetViewProps) => {
+ const projectId = useActiveProjectId();
+ const engine = getCanvasEngine(projectId);
+ return engine ? <CanvasSettingsActionsInner engine={engine} /> : null;
+};
+
+const CanvasSettingsActionsInner = ({ engine }: { engine: CanvasHeaderEngine }) => {
const { t } = useTranslation();
- const { widgets } = useWorkbenchCommands();
- const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
- // Shift reveals the Debug section, matching legacy `useShiftModifier` (event-driven).
const shiftHeld = useModifierHeld('Shift');
-
- const toggle = (setting: CanvasBooleanSetting) => {
- widgets.patchValues('canvas', { [setting.key]: !settings[setting.key] });
- };
-
+ const editingLocked = useCanvasDocumentEditingLocked(engine);
+ if (!shiftHeld) {
+ return null;
+ }
return (
- <Menu.Root closeOnSelect={false} positioning={MENU_POSITIONING}>
- <Menu.Trigger asChild>
- <IconButton aria-label={t('widgets.canvas.settings.label')} color="fg.muted" size="2xs" variant="ghost">
- <SettingsIcon />
- </IconButton>
- </Menu.Trigger>
- <Portal>
- <Menu.Positioner>
- <MenuContent minW="15rem" py="1">
- {CANVAS_SETTING_SECTIONS.map((section, sectionIndex) => (
- <Fragment key={section}>
- {sectionIndex > 0 ? <Menu.Separator borderColor="border.subtle" /> : null}
- <Menu.ItemGroup>
- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
- {t(`widgets.canvas.settings.sections.${section}`)}
- </Menu.ItemGroupLabel>
- {CANVAS_SETTINGS.filter((setting) => setting.section === section).map((setting) => (
- <Menu.Item key={setting.key} value={setting.key} onClick={() => toggle(setting)}>
- <Icon as={CheckIcon} boxSize="3.5" opacity={settings[setting.key] ? 1 : 0} />
- <Menu.ItemText fontSize="xs">{t(setting.labelKey)}</Menu.ItemText>
- </Menu.Item>
- ))}
- </Menu.ItemGroup>
- </Fragment>
- ))}
- {shiftHeld ? (
- <>
- <Menu.Separator borderColor="border.subtle" />
- <Menu.ItemGroup>
- <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
- {t('widgets.canvas.settings.sections.debug')}
- </Menu.ItemGroupLabel>
- <Menu.Item value="debug-clear-caches" onClick={() => void engine.diagnostics.clearCaches()}>
- <Icon as={DatabaseIcon} boxSize="3.5" color="fg.subtle" />
- <Menu.ItemText fontSize="xs">{t('widgets.canvas.settings.clearCaches')}</Menu.ItemText>
- </Menu.Item>
- <Menu.Item value="debug-log-info" onClick={() => engine.diagnostics.logDebugInfo()}>
- <Icon as={BugIcon} boxSize="3.5" color="fg.subtle" />
- <Menu.ItemText fontSize="xs">{t('widgets.canvas.settings.logDebugInfo')}</Menu.ItemText>
- </Menu.Item>
- <Menu.Item
- disabled={editingLocked}
- value="debug-clear-history"
- onClick={() => engine.history.clearHistory()}
- >
- <Icon as={Trash2Icon} boxSize="3.5" color="fg.subtle" />
- <Menu.ItemText fontSize="xs">{t('widgets.canvas.settings.clearHistory')}</Menu.ItemText>
- </Menu.Item>
- </Menu.ItemGroup>
- </>
- ) : null}
- </MenuContent>
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
+ <Stack borderTopWidth="1px" borderColor="border.subtle" gap="1" pt="2">
+ <Text color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ {t('widgets.canvas.settings.sections.debug')}
+ </Text>
+ <Button size="xs" variant="ghost" justifyContent="start" onClick={() => void engine.diagnostics.clearCaches()}>
+ <DatabaseIcon />
+ {t('widgets.canvas.settings.clearCaches')}
+ </Button>
+ <Button size="xs" variant="ghost" justifyContent="start" onClick={() => engine.diagnostics.logDebugInfo()}>
+ <BugIcon />
+ {t('widgets.canvas.settings.logDebugInfo')}
+ </Button>
+ <Button
+ disabled={editingLocked}
+ size="xs"
+ variant="ghost"
+ justifyContent="start"
+ onClick={() => engine.history.clearHistory()}
+ >
+ <Trash2Icon />
+ {t('widgets.canvas.settings.clearHistory')}
+ </Button>
+ </Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts
index c7a6b01447..5b9235ed2c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts
@@ -7,7 +7,6 @@ import {
CANVAS_INVERT_BRUSH_SCROLL_KEY,
CANVAS_OUTPUT_ONLY_MASKED_REGIONS_KEY,
CANVAS_RULE_OF_THIRDS_KEY,
- CANVAS_SETTING_SECTIONS,
CANVAS_SETTINGS,
CANVAS_SHOW_BBOX_KEY,
CANVAS_SHOW_GRID_KEY,
@@ -81,12 +80,9 @@ describe('canvasSettings persistence mapping', () => {
expect(readCanvasBooleanSetting({ [CANVAS_SHOW_GRID_KEY]: 1 }, settingByKey(CANVAS_SHOW_GRID_KEY))).toBe(false);
});
- it('maps every setting to a unique key and a known section', () => {
+ it('maps every setting to a unique persisted key', () => {
const keys = CANVAS_SETTINGS.map((s) => s.key);
expect(new Set(keys).size).toBe(keys.length);
- for (const setting of CANVAS_SETTINGS) {
- expect(CANVAS_SETTING_SECTIONS).toContain(setting.section);
- }
});
it('gives every engine-backed store a distinct store id (other frontend-consumed settings have none)', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
index aaecc302e2..de364cd960 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
@@ -153,9 +153,6 @@ export const CANVAS_SETTINGS: readonly CanvasBooleanSetting[] = [
},
];
-/** The sections, in popover render order. */
-export const CANVAS_SETTING_SECTIONS: readonly CanvasSettingSection[] = ['behavior', 'display', 'grid'];
-
/** Resolved settings, keyed by persisted setting key (default-applied). */
export type ResolvedCanvasSettings = Record<string, boolean>;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts
index 8d90b4b3f2..bb4f36fe82 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/implementation.ts
@@ -1,9 +1,10 @@
import type { WidgetImplementation } from '@workbench/widgetContracts';
-import { CanvasHeaderActions } from './CanvasHeaderActions';
+import { CanvasHeaderActions, CanvasSettingsActions } from './CanvasHeaderActions';
import { CanvasWidgetView } from './CanvasWidgetView';
export const widgetImplementation = {
headerActions: CanvasHeaderActions,
+ settingsActions: CanvasSettingsActions,
view: CanvasWidgetView,
} satisfies WidgetImplementation;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/manifest.ts
index 4ccd487e44..97cb7d0f1a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/manifest.ts
@@ -2,6 +2,8 @@ import type { WidgetManifest } from '@workbench/widgetContracts';
import { WandSparklesIcon } from 'lucide-react';
+import { canvasSettingsContribution } from './settingsContribution';
+
export const canvasWidgetManifest: WidgetManifest = {
allowMultiple: false,
allowedRegions: ['center'],
@@ -11,5 +13,6 @@ export const canvasWidgetManifest: WidgetManifest = {
id: 'canvas',
label: (t) => t('widgets.labels.canvas'),
load: () => import('./implementation').then((module) => module.widgetImplementation),
+ settings: canvasSettingsContribution,
version: 1,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx
new file mode 100644
index 0000000000..9ed1054fb5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx
@@ -0,0 +1,32 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { SettingControl } from '@platform/ui/settings/SettingControl';
+import { useWidgetSettingsTarget } from '@workbench/settings/useWidgetSettingsTarget';
+import { useCallback } from 'react';
+
+import { CANVAS_SETTINGS, readCanvasBooleanSetting } from './canvasSettings';
+
+export const Field = ({ field, surface, target }: SettingFieldProps) => {
+ const definition = CANVAS_SETTINGS.find((setting) => setting.key === field.id);
+ const { disabled, patch, value } = useWidgetSettingsTarget('canvas', target, (values) =>
+ definition ? readCanvasBooleanSetting(values, definition) : false
+ );
+ const onChange = useCallback(
+ (next: boolean | string | number) => {
+ if (definition && typeof next === 'boolean') {
+ patch({ [definition.key]: next });
+ }
+ },
+ [definition, patch]
+ );
+ return (
+ <SettingControl
+ isModified={definition !== undefined && value !== definition.defaultValue}
+ disabled={disabled}
+ field={field}
+ surface={surface}
+ value={value}
+ onChange={onChange}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts
new file mode 100644
index 0000000000..bdc200fb72
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts
@@ -0,0 +1,18 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
+
+import { CANVAS_SETTINGS } from './canvasSettings';
+
+export const canvasSettingsContribution: SettingsContribution = {
+ id: 'canvas',
+ label: (t) => t('widgets.labels.canvas'),
+ fields: CANVAS_SETTINGS.map((setting) => ({
+ group: (t) => t(`widgets.canvas.settings.sections.${setting.section}`),
+ id: setting.key,
+ kind: 'boolean',
+ label: (t) => t(setting.labelKey),
+ scope: 'instance',
+ keywords: setting.key === 'showCheckerboard' ? 'transparency background' : undefined,
+ })),
+ quick: CANVAS_SETTINGS.map((setting) => setting.key),
+ load: () => import('./settingsBindings'),
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
index 3c6b49f0b7..45552209b6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts
@@ -1,5 +1,6 @@
import type { WidgetManifest } from '@workbench/widgetContracts';
+import { gallerySettingsContribution } from '@features/gallery/settingsContribution';
import { ImageIcon } from 'lucide-react';
export const galleryWidgetManifest: WidgetManifest = {
@@ -13,9 +14,9 @@ export const galleryWidgetManifest: WidgetManifest = {
load: () =>
import('@features/gallery/widget').then((module) => ({
footer: module.GalleryWidgetFooter,
- headerActions: module.GalleryWidgetHeaderActions,
headerLabel: module.GalleryWidgetLabel,
view: module.GalleryWidgetView,
})),
+ settings: gallerySettingsContribution,
version: 1,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
index 22648c4d12..8037a62645 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
@@ -2,6 +2,8 @@ import type { WidgetManifest } from '@workbench/widgetContracts';
import { MapIcon } from 'lucide-react';
+import { imageMapSettingsContribution } from './settingsContribution';
+
export const imageMapWidgetManifest: WidgetManifest = {
allowFloating: true,
allowMultiple: false,
@@ -12,6 +14,6 @@ export const imageMapWidgetManifest: WidgetManifest = {
label: (t) => t('widgets.labels.imageMap'),
load: () => import('./implementation').then((module) => module.widgetImplementation),
loadHost: () => import('./ImageMapDataRuntime').then((module) => module.ImageMapDataRuntime),
- settingsSection: 'imageMap',
+ settings: imageMapSettingsContribution,
version: 1,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx
new file mode 100644
index 0000000000..8b6b8db2e8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx
@@ -0,0 +1,34 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { SettingControl } from '@platform/ui/settings/SettingControl';
+import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';
+import { useWidgetSettingsTarget } from '@workbench/settings/useWidgetSettingsTarget';
+import { useCallback } from 'react';
+
+export const Field = ({ field, surface, target }: SettingFieldProps) => {
+ const { disabled, patch, value } = useWidgetSettingsTarget(
+ 'image-map',
+ target,
+ field.id === 'clickSelectsCluster' ? getImageMapClickSelectsCluster : getImageMapShowClusterLabels
+ );
+ const onChange = useCallback(
+ (next: boolean | string | number) => {
+ if (typeof next === 'boolean' && (field.id === 'clickSelectsCluster' || field.id === 'showClusterLabels')) {
+ patch({ [field.id]: next });
+ }
+ },
+ [field.id, patch]
+ );
+ const defaultValue =
+ field.id === 'clickSelectsCluster' ? getImageMapClickSelectsCluster({}) : getImageMapShowClusterLabels({});
+ return (
+ <SettingControl
+ isModified={value !== defaultValue}
+ disabled={disabled}
+ field={field}
+ surface={surface}
+ value={value}
+ onChange={onChange}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts
new file mode 100644
index 0000000000..bfa9b58966
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts
@@ -0,0 +1,23 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
+
+export const imageMapSettingsContribution: SettingsContribution = {
+ id: 'imageMap',
+ label: (t) => t('widgets.labels.imageMap'),
+ fields: [
+ {
+ id: 'showClusterLabels',
+ kind: 'boolean',
+ label: (t) => t('settingsDialog.fields.showClusterLabels'),
+ scope: 'instance',
+ keywords: 'tags text display',
+ },
+ {
+ id: 'clickSelectsCluster',
+ kind: 'boolean',
+ label: (t) => t('settingsDialog.fields.clickSelectsCluster'),
+ scope: 'instance',
+ keywords: 'click gallery selection',
+ },
+ ],
+ load: () => import('./settingsBindings'),
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/manifests.ts b/invokeai/frontend/webv2/src/workbench/widgets/manifests.ts
new file mode 100644
index 0000000000..ab7ceab323
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/manifests.ts
@@ -0,0 +1,37 @@
+import type { WidgetManifest } from '@workbench/widgetContracts';
+
+import { autosaveStatusWidgetManifest } from './autosave-status/manifest';
+import { canvasWidgetManifest } from './canvas/manifest';
+import { diagnosticsWidgetManifest } from './diagnostics/manifest';
+import { galleryWidgetManifest } from './gallery/manifest';
+import { generateWidgetManifest } from './generate/manifest';
+import { imageMapWidgetManifest } from './image-map/manifest';
+import { layersWidgetManifest } from './layers/manifest';
+import { notificationsWidgetManifest } from './notifications/manifest';
+import { previewWidgetManifest } from './preview/manifest';
+import { projectWidgetManifest } from './project/manifest';
+import { queueStatusWidgetManifest } from './queue-status/manifest';
+import { queueWidgetManifest } from './queue/manifest';
+import { serverStatusWidgetManifest } from './server-status/manifest';
+import { upscaleWidgetManifest } from './upscale/manifest';
+import { videoWidgetManifest } from './video/manifest';
+import { workflowWidgetManifest } from './workflow/manifest';
+
+export const firstPartyWidgetManifests: WidgetManifest[] = [
+ generateWidgetManifest,
+ workflowWidgetManifest,
+ upscaleWidgetManifest,
+ videoWidgetManifest,
+ canvasWidgetManifest,
+ diagnosticsWidgetManifest,
+ galleryWidgetManifest,
+ imageMapWidgetManifest,
+ previewWidgetManifest,
+ projectWidgetManifest,
+ layersWidgetManifest,
+ queueWidgetManifest,
+ notificationsWidgetManifest,
+ serverStatusWidgetManifest,
+ queueStatusWidgetManifest,
+ autosaveStatusWidgetManifest,
+];
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts
index f2fed99dd7..c754f63172 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts
@@ -2,6 +2,8 @@ import type { WidgetManifest } from '@workbench/widgetContracts';
import { EyeIcon } from 'lucide-react';
+import { previewSettingsContribution } from './settingsContribution';
+
export const previewWidgetManifest: WidgetManifest = {
allowFloating: true,
allowMultiple: false,
@@ -11,5 +13,6 @@ export const previewWidgetManifest: WidgetManifest = {
id: 'preview',
label: (t) => t('widgets.labels.preview'),
load: () => import('./implementation').then((module) => module.widgetImplementation),
+ settings: previewSettingsContribution,
version: 1,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx
new file mode 100644
index 0000000000..0ae68adf75
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx
@@ -0,0 +1,34 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { SettingControl } from '@platform/ui/settings/SettingControl';
+import { useWidgetSettingsTarget } from '@workbench/settings/useWidgetSettingsTarget';
+import { useCallback } from 'react';
+
+import { getPreviewComparisonMode, getPreviewFilmstripVisible } from './previewSettings';
+
+export const Field = ({ field, surface, target }: SettingFieldProps) => {
+ const { disabled, patch, value } = useWidgetSettingsTarget<boolean | string>('preview', target, (values) =>
+ field.id === 'comparisonMode' ? getPreviewComparisonMode(values) : getPreviewFilmstripVisible(values)
+ );
+ const onChange = useCallback(
+ (next: boolean | string | number) => {
+ if (field.id === 'comparisonMode' && (next === 'slider' || next === 'side-by-side' || next === 'hover')) {
+ patch({ comparisonMode: next });
+ } else if (field.id === 'filmstripVisible' && typeof next === 'boolean') {
+ patch({ filmstripVisible: next });
+ }
+ },
+ [field.id, patch]
+ );
+ const defaultValue = field.id === 'comparisonMode' ? getPreviewComparisonMode({}) : getPreviewFilmstripVisible({});
+ return (
+ <SettingControl
+ isModified={value !== defaultValue}
+ disabled={disabled}
+ field={field}
+ surface={surface}
+ value={value}
+ onChange={onChange}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts
new file mode 100644
index 0000000000..7bd96699e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts
@@ -0,0 +1,27 @@
+import type { SettingsContribution } from '@platform/ui/settings/contracts';
+
+export const previewSettingsContribution: SettingsContribution = {
+ id: 'preview',
+ label: (t) => t('widgets.labels.preview'),
+ fields: [
+ {
+ id: 'filmstripVisible',
+ kind: 'boolean',
+ label: (t) => t('widgets.preview.showFilmstrip'),
+ scope: 'instance',
+ keywords: 'thumbnails gallery',
+ },
+ {
+ id: 'comparisonMode',
+ kind: 'select',
+ label: (t) => t('settingsDialog.fields.comparisonMode'),
+ scope: 'instance',
+ options: [
+ { label: (t) => t('widgets.preview.slider'), value: 'slider' },
+ { label: (t) => t('widgets.preview.sideBySide'), value: 'side-by-side' },
+ { label: (t) => t('widgets.preview.hover'), value: 'hover' },
+ ],
+ },
+ ],
+ load: () => import('./settingsBindings'),
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts
index a16abaffe7..53388bf666 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts
@@ -1,6 +1,7 @@
import type { WidgetManifest } from '@workbench/widgetContracts';
import { loadQueueWidgetHost, loadQueueWidgetImplementation } from '@features/queue/widget';
+import { queueSettings } from '@workbench/settings/applicationContributions';
import { ListOrderedIcon } from 'lucide-react';
export const queueWidgetManifest: WidgetManifest = {
@@ -15,6 +16,6 @@ export const queueWidgetManifest: WidgetManifest = {
label: (t) => t('widgets.labels.queue'),
load: loadQueueWidgetImplementation,
loadHost: loadQueueWidgetHost,
- settingsSection: 'queue',
+ settings: queueSettings,
version: 1,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts
index 0576ac1039..dd05f4c70a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts
@@ -1,6 +1,7 @@
import type { WidgetManifest } from '@workbench/widgetContracts';
import { loadWorkflowWidgetHost, loadWorkflowWidgetImplementation } from '@features/workflow/widget';
+import { workflowSettings } from '@workbench/settings/applicationContributions';
import { WorkflowIcon } from 'lucide-react';
export const workflowWidgetManifest: WidgetManifest = {
@@ -18,6 +19,6 @@ export const workflowWidgetManifest: WidgetManifest = {
label: (t) => t('widgets.labels.workflow'),
load: loadWorkflowWidgetImplementation,
loadHost: loadWorkflowWidgetHost,
- settingsSection: 'workflow',
+ settings: workflowSettings,
version: 1,
};
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 73784aa495..9277e5fc5a 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -4,6 +4,7 @@ import { fileURLToPath, URL } from 'node:url';
import { defineConfig } from 'vite';
import { chunkSourceManifest } from './scripts/chunk-source-manifest.mjs';
+import { localeAssetsPlugin } from './scripts/locale-assets-plugin.mjs';
import { serviceWorkerPlugin } from './scripts/service-worker-plugin.mjs';
// Override with e.g. INVOKEAI_DEV_BACKEND=http://127.0.0.1:9091 when the
@@ -31,6 +32,13 @@ const ROUTE_SHARED_MODULES = [
// the whole Launchpad chunk in after it — the same regression the
// `launchpad/intents.ts` note below describes.
'/platform/ui/BrandIcon.tsx',
+ // Settings share these controls across both routes and deferred editors.
+ // Keep those extra consumers from splitting already-eager controls into requests of their own.
+ '/platform/ui/Button.tsx',
+ '/platform/ui/Tooltip.tsx',
+ '/platform/ui/RetryBoundary.tsx',
+ '/platform/ui/PanelHeader.tsx',
+ '/platform/ui/settings/contracts.ts',
'/platform/core/concurrency.ts',
'/platform/query/client.ts',
'/platform/time/serverTimestamp.ts',
@@ -49,6 +57,7 @@ const ROUTE_SHARED_MODULES = [
'/platform/ui/theme/applyTheme.ts',
'/workbench/components/WorkbenchSplashScreen.tsx',
'/workbench/hotkeys/catalog.ts',
+ '/workbench/hotkeys/modalLayer.ts',
'/workbench/launchpad/formatRelativeTime.ts',
// The Launchpad writes `?intent=` and the editor's session controller reads
// it. Without this the editor pulls the whole Launchpad chunk for a lookup
@@ -97,6 +106,8 @@ const ROUTE_SHARED_MODULES = [
// both routes above, scoped here to the editor alone because none of this
// is reachable from the Launchpad.
const EDITOR_BOOT_SHARED_MODULES = [
+ // This adapter owns editor-lifetime Gallery state; its image-action bridge stays deferred.
+ '/app/GalleryUiAdapter.tsx',
// The gallery picker's trigger shell (every boot widget with an image slot
// mounts one) plus the Gallery widget UI its lazy view shares; the widget
// boots every editor route, so this moves bytes rather than adding requests.
@@ -121,6 +132,42 @@ const EDITOR_BOOT_SHARED_MODULES = [
'/workbench/shell/topbar/ProjectSwitcher.tsx',
] as const;
+// The editor registry and deferred settings/palette share metadata, never widget views.
+// Keep it separate from editor boot UI so Launchpad settings cannot pull in the editor.
+const WIDGET_METADATA_MODULES = [
+ '/features/gallery/settingsContribution.ts',
+ '/features/queue/widget.ts',
+ '/features/workflow/widget.ts',
+ '/workbench/settings/applicationContributions.ts',
+ '/workbench/settings/catalog.ts',
+ '/workbench/widgets/canvas/canvasSettings.ts',
+ '/workbench/widgets/canvas/settingsContribution.ts',
+ '/workbench/widgets/image-map/settingsContribution.ts',
+ '/workbench/widgets/layers/panes/editorPaneLayout.ts',
+ '/workbench/widgets/manifests.ts',
+ '/workbench/widgets/preview/settingsContribution.ts',
+ '/workbench/widgets/preview/previewSettings.ts',
+] as const;
+
+// Gallery’s shared state projection and UI port travel together. Explicit sources
+// keep the UI port’s compiler runtime in the vendor chunk used by both routes.
+const GALLERY_STATE_MODULES = [
+ '/features/gallery/core/items.ts',
+ '/features/gallery/core/recentImages.ts',
+ '/features/gallery/core/selection.ts',
+ '/features/gallery/core/semanticImageQuery.ts',
+ '/features/gallery/core/settings.ts',
+ '/features/gallery/ui/GalleryUiContext.tsx',
+ '/features/gallery/ui/galleryStateView.ts',
+ '/features/queue/contracts.ts',
+ '/features/queue/core/generationMeta.ts',
+ '/features/queue/core/historySnapshot.ts',
+ '/features/queue/core/historySummary.ts',
+ '/features/queue/core/progressRail.ts',
+ '/features/queue/core/submissionRules.ts',
+ '/features/queue/data/events.ts',
+] as const;
+
// The singleton widget hosts the editor mounts once at boot: workflow's
// dialog shell, queue's data runtime, image-map's data runtime. Each is
// fetched together with the other two on every editor boot, all three are
@@ -162,10 +209,6 @@ const getLegacyChunkName = (id: string): string | null => {
return 'shell-shared';
}
- if (matchesAnySuffix(id, ['/features/gallery/core/items.ts', '/features/gallery/ui/galleryStateView.ts'])) {
- return 'gallery-state';
- }
-
if (!id.includes('/node_modules/')) {
return null;
}
@@ -214,6 +257,12 @@ export default defineConfig({
output: {
codeSplitting: {
groups: [
+ {
+ includeDependenciesRecursively: false,
+ name: 'gallery-state',
+ priority: 30,
+ test: (id) => matchesAnySuffix(id, GALLERY_STATE_MODULES),
+ },
{
includeDependenciesRecursively: false,
name: 'route-shared',
@@ -226,6 +275,13 @@ export default defineConfig({
priority: 30,
test: (id) => matchesAnySuffix(id, EDITOR_BOOT_SHARED_MODULES),
},
+ {
+ includeDependenciesRecursively: false,
+ name: 'widget-metadata',
+ priority: 30,
+ test: (id) =>
+ matchesAnySuffix(id, WIDGET_METADATA_MODULES) || /\/workbench\/widgets\/[^/]+\/manifest\.ts$/.test(id),
+ },
{
includeDependenciesRecursively: false,
name: 'widget-hosts',
@@ -254,6 +310,7 @@ export default defineConfig({
presets: [reactCompilerPreset()],
}),
chunkSourceManifest({ projectRoot: PROJECT_ROOT }),
+ localeAssetsPlugin({ projectRoot: PROJECT_ROOT }),
serviceWorkerPlugin({ projectRoot: PROJECT_ROOT }),
],
resolve: {