Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat: add shared workbench settings
joshistoast510b53908e14
diff --git a/invokeai/frontend/webv2/src/App.tsx b/invokeai/frontend/webv2/src/App.tsxindex 76e0190d2a..bc0fe6cdcd 100644--- a/invokeai/frontend/webv2/src/App.tsx+++ b/invokeai/frontend/webv2/src/App.tsx@@ -4,9 +4,11 @@ import { RouterProvider } from '@tanstack/react-router';import { router } from './router';import { system } from './theme/system';import { AppToaster } from './workbench/components/ui/toaster';+import { ThemeController } from './workbench/ThemeController';export const App = () => (<ChakraProvider value={system}>+ <ThemeController /><AppToaster /><RouterProvider router={router} /></ChakraProvider>diff --git a/invokeai/frontend/webv2/src/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/WorkbenchApp.tsxindex c7541774c0..5094f3ba2c 100644--- a/invokeai/frontend/webv2/src/WorkbenchApp.tsx+++ b/invokeai/frontend/webv2/src/WorkbenchApp.tsx@@ -1,7 +1,6 @@import { useSearch } from '@tanstack/react-router';import { SessionExpiryGuard } from './workbench/auth/components/SessionExpiryGuard';-import { ThemeController } from './workbench/ThemeController';import { ModelsRuntime } from './workbench/widgets/models/ModelsRuntime';import { WorkbenchProvider } from './workbench/WorkbenchContext';import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';@@ -24,7 +23,6 @@ export const WorkbenchApp = () => {return (<WorkbenchProvider loadOptions={{ createNew: search.new, openProjectId: search.project }}>- <ThemeController /><SessionExpiryGuard /><WorkbenchRuntime /><ModelsRuntime />diff --git a/invokeai/frontend/webv2/src/router.tsx b/invokeai/frontend/webv2/src/router.tsxindex aa28b80c48..2285bfb873 100644--- a/invokeai/frontend/webv2/src/router.tsx+++ b/invokeai/frontend/webv2/src/router.tsx@@ -15,6 +15,7 @@ import { LoginScreen } from './workbench/auth/components/LoginScreen';import { SetupScreen } from './workbench/auth/components/SetupScreen';import { HomeScreen } from './workbench/home/HomeScreen';import { peekOpenProjectIds, type WorkbenchSearch } from './workbench/projects/session';+import { loadWorkbenchSettings } from './workbench/settings/store';/*** Code-based route tree. The authenticated layout route owns the auth guard,@@ -39,17 +40,17 @@ const authenticatedRoute = createRoute({beforeLoad: async () => {const session = await ensureAuthSession();- if (!session.multiuserEnabled) {- return;- }+ if (session.multiuserEnabled) {+ if (session.setupRequired) {+ throw redirect({ to: '/setup' });+ }- if (session.setupRequired) {- throw redirect({ to: '/setup' });+ if (session.user === null) {+ throw redirect({ to: '/login' });+ }}- if (session.user === null) {- throw redirect({ to: '/login' });- }+ await loadWorkbenchSettings();},component: Outlet,getParentRoute: () => rootRoute,diff --git a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx b/invokeai/frontend/webv2/src/workbench/ThemeController.tsxindex ebd2eecd2a..a2c01f94e5 100644--- a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx+++ b/invokeai/frontend/webv2/src/workbench/ThemeController.tsx@@ -1,7 +1,7 @@import { useEffect } from 'react';import { THEMES_BY_ID } from '../theme/system';-import { useWorkbench } from './WorkbenchContext';+import { useWorkbenchSettings } from './settings/store';/*** Applies the persisted appearance preferences to the document root.@@ -20,10 +20,17 @@ import { useWorkbench } from './WorkbenchContext';const THEME_HINT_STORAGE_KEY = 'invokeai:v7:webv2:theme';export const ThemeController = () => {- const { state } = useWorkbench();- const { reduceMotion, themeId } = state.account.preferences;+ const { preferences, status } = useWorkbenchSettings();+ const { reduceMotion, themeId } = preferences;+ // Until the settings store has resolved, the pre-paint hint script owns the+ // theme; applying the store's defaults here would flash and clobber it.+ const hasResolved = status === 'ready' || status === 'error';useEffect(() => {+ if (!hasResolved) {+ return;+ }+const root = document.documentElement;const theme = THEMES_BY_ID[themeId] ?? THEMES_BY_ID.dark;@@ -39,9 +46,13 @@ export const ThemeController = () => {} catch {// Storage unavailable — the next load just paints the default theme.}- }, [themeId]);+ }, [hasResolved, themeId]);useEffect(() => {+ if (!hasResolved) {+ return;+ }+const root = document.documentElement;if (reduceMotion) {@@ -49,7 +60,7 @@ export const ThemeController = () => {} else {delete root.dataset.reduceMotion;}- }, [reduceMotion]);+ }, [hasResolved, reduceMotion]);return null;};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 1858f06208..28ee5eb490 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -212,3 +212,5 @@ export const useWorkbench = (): WorkbenchContextValue => {return context;};++export const useOptionalWorkbench = (): WorkbenchContextValue | null => use(WorkbenchContext);diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsxsimilarity index 80%rename from invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsxrename to invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsxindex 1d6b7d1e2f..79dfbac4af 100644--- a/invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/auth/components/AccountMenu.tsx@@ -3,37 +3,43 @@ import { useNavigate } from '@tanstack/react-router';import { useState } from 'react';import { ChevronDownIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';-import { ProfileDialog } from './ProfileDialog';import { MenuContent } from '../../components/ui/Menu';-import { useWorkbench } from '../../WorkbenchContext';+import { SettingsButton } from '../../settings/SettingsDialog';+import { useOptionalWorkbench } from '../../WorkbenchContext';import { logoutSession, useAuthSession } from '../session';+import { ProfileDialog } from './ProfileDialog';/**- * Signed-in account cluster for the top bar: avatar trigger, account dialog,- * the admin users view, and sign-out. Renders nothing in single-user mode, so- * the shell needs no awareness of whether multi-user is enabled.+ * Shared settings/account cluster used by both Home and the workbench shell:+ * the settings gear always renders; the avatar menu joins it when a+ * multi-user session is signed in.*/-export const UserMenu = () => {+export const AccountMenu = () => {const session = useAuthSession();- const { activeProject, dispatch } = useWorkbench();+ const workbench = useOptionalWorkbench();const navigate = useNavigate();const [isProfileOpen, setIsProfileOpen] = useState(false);if (!session.multiuserEnabled || session.user === null) {- return null;+ return <SettingsButton />;}const user = session.user;const label = user.display_name?.trim() || user.email;const openUserManagement = () => {+ const activeProject = workbench?.activeProject;++ if (!activeProject || !workbench) {+ return;+ }+const centerRegion = activeProject.widgetRegions.center;- // Enabling an absent center widget also makes it active.if (centerRegion.enabledWidgetIds.includes('users')) {- dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'users' });+ workbench.dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'users' });} else {- dispatch({ region: 'center', type: 'toggleRegionWidget', widgetId: 'users' });+ workbench.dispatch({ region: 'center', type: 'toggleRegionWidget', widgetId: 'users' });}};@@ -43,7 +49,8 @@ export const UserMenu = () => {};return (- <>+ <HStack gap="0.5">+ <SettingsButton /><Menu.Root positioning={{ placement: 'bottom-end' }}><Menu.Trigger asChild><chakra.button@@ -92,7 +99,7 @@ export const UserMenu = () => {<Icon as={UserRoundCogIcon} boxSize="3.5" />Account settings</Menu.Item>- {user.is_admin ? (+ {user.is_admin && workbench ? (<Menu.Item value="users" onClick={openUserManagement}><Icon as={UsersIcon} boxSize="3.5" />Manage users@@ -108,6 +115,6 @@ export const UserMenu = () => {</Portal></Menu.Root><ProfileDialog isOpen={isProfileOpen} user={user} onClose={() => setIsProfileOpen(false)} />- </>+ </HStack>);};diff --git a/invokeai/frontend/webv2/src/workbench/components/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/components/ImageContextMenu.tsxindex 2f772ae4aa..a9de22dfc5 100644--- a/invokeai/frontend/webv2/src/workbench/components/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/ImageContextMenu.tsx@@ -27,7 +27,7 @@ import type { GalleryBoard, GalleryImage } from '../gallery/api';import { Button } from './ui/Button';import { MenuContent } from './ui/Menu';import { Tooltip } from './ui/Tooltip';-import { useWorkbench } from '../WorkbenchContext';+import { useWorkbenchPreferences } from '../settings/store';import type { ImageActions } from './useImageActions';export interface ImageContextMenuTarget {@@ -60,8 +60,7 @@ export const ImageContextMenu = ({target: ImageContextMenuTarget | null;onClose: () => void;}) => {- const { state } = useWorkbench();- const confirmImageDeletion = state.account.preferences.confirmImageDeletion;+ const { confirmImageDeletion } = useWorkbenchPreferences();const [pendingDeletion, setPendingDeletion] = useState<string[] | null>(null);const targetRef = useRef(target);diff --git a/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsxindex c0589228f7..2dc2927df9 100644--- a/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx@@ -1,7 +1,8 @@-import { Badge, Combobox, createListCollection, HStack, Portal, Text } from '@chakra-ui/react';+import { Badge, Combobox, createListCollection, HStack, Portal, Stack, Text } from '@chakra-ui/react';import { useEffect, useMemo, useState } from 'react';import { ensureModelsLoaded, useModelsSnapshot } from '../models/modelsStore';+import { useWorkbenchPreferences } from '../settings/store';import {formatBytes,getModelBaseColorPalette,@@ -38,6 +39,7 @@ export const ModelSelect = ({/** Selected model key, or null. */value: string | null;}) => {+ const { enableModelDescriptions } = useWorkbenchPreferences();const { models } = useModelsSnapshot();const [searchTerm, setSearchTerm] = useState('');@@ -149,9 +151,16 @@ export const ModelSelect = ({{groupModels.map((model) => (<Combobox.Item key={model.key} item={model}><HStack flex="1" gap="2" minW="0">- <Text flex="1" fontSize="xs" minW="0" truncate>- {model.name}- </Text>+ <Stack flex="1" gap="0" minW="0">+ <Text fontSize="xs" minW="0" truncate>+ {model.name}+ </Text>+ {enableModelDescriptions && model.description ? (+ <Text color="fg.subtle" fontSize="2xs" truncate>+ {model.description}+ </Text>+ ) : null}+ </Stack><BadgecolorPalette={getModelBaseColorPalette(model.base)}flexShrink={0}diff --git a/invokeai/frontend/webv2/src/workbench/components/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/components/SettingsDialog.tsxdeleted file mode 100644index 4dcbefbfc0..0000000000--- a/invokeai/frontend/webv2/src/workbench/components/SettingsDialog.tsx+++ /dev/null@@ -1,237 +0,0 @@-import {- Box,- chakra,- Dialog,- Flex,- HStack,- Icon,- Portal,- SimpleGrid,- Stack,- Switch,- Text,- useSlotRecipe,-} from '@chakra-ui/react';-import type { ReactNode } from 'react';-import { CheckIcon, RotateCcwIcon, SettingsIcon, Trash2Icon } from 'lucide-react';--import { themeCardRecipe } from '../../theme/recipes';-import { THEMES, type ThemeDefinition } from '../../theme/system';-import { syncedWorkbenchPersistence } from '../projects/syncedPersistence';-import type { WorkbenchThemeId } from '../types';-import { useWorkbench } from '../WorkbenchContext';-import { Button, CloseButton, IconButton } from './ui/Button';--/**- * Settings entry point: a self-contained gear button that owns its own dialog- * open-state. Kept as one composable unit (rather than threading an `isOpen`- * boolean through the TopBar) so the rest of the shell stays unaware of it.- */-export const SettingsButton = () => (- <Dialog.Root placement="center" scrollBehavior="inside" size="lg">- <Dialog.Trigger asChild>- <IconButton aria-label="Settings" color="fg.muted" size="sm" variant="ghost" _hover={{ color: 'fg.default' }}>- <SettingsIcon />- </IconButton>- </Dialog.Trigger>- <SettingsDialogContent />- </Dialog.Root>-);--const SettingsDialogContent = () => (- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content bg="bg.surface" borderColor="border.subtle" borderWidth="1px" color="fg.default">- <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">- <Stack gap="0.5">- <Dialog.Title fontSize="md" fontWeight="700">- Settings- </Dialog.Title>- <Text color="fg.subtle" fontSize="xs">- Appearance and workspace preferences for this browser.- </Text>- </Stack>- </Dialog.Header>- <Dialog.Body>- <Stack gap="7" py="2">- <AppearanceSection />- <BehaviorSection />- <WorkspaceSection />- </Stack>- </Dialog.Body>- <Dialog.CloseTrigger asChild>- <CloseButton color="fg.muted" size="sm" />- </Dialog.CloseTrigger>- </Dialog.Content>- </Dialog.Positioner>- </Portal>-);--const SettingsSection = ({- children,- description,- title,-}: {- children: ReactNode;- description: string;- title: string;-}) => (- <Stack gap="3">- <Stack gap="0.5">- <Text color="fg.default" fontSize="sm" fontWeight="600">- {title}- </Text>- <Text color="fg.subtle" fontSize="xs">- {description}- </Text>- </Stack>- {children}- </Stack>-);--const AppearanceSection = () => {- const { dispatch, state } = useWorkbench();- const { reduceMotion, showFocusRegionHighlight, themeId } = state.account.preferences;-- const selectTheme = (nextThemeId: WorkbenchThemeId) => {- dispatch({ preferences: { themeId: nextThemeId }, type: 'setPreferences' });- };-- return (- <SettingsSection description="Choose a theme and tune motion." title="Appearance">- <SimpleGrid columns={{ base: 2, md: 3 }} gap="3">- {THEMES.map((theme) => (- <ThemeCard key={theme.id} selected={theme.id === themeId} theme={theme} onSelect={selectTheme} />- ))}- </SimpleGrid>- <SettingToggle- checked={reduceMotion}- description="Disable transitions and animations across the workbench."- label="Reduce motion"- onChange={(checked) => dispatch({ preferences: { reduceMotion: checked }, type: 'setPreferences' })}- />- <SettingToggle- checked={showFocusRegionHighlight}- description="Draw a subtle outline around the active workbench region."- label="Highlight focused region"- onChange={(checked) => dispatch({ preferences: { showFocusRegionHighlight: checked }, type: 'setPreferences' })}- />- </SettingsSection>- );-};--const ThemeCard = ({- onSelect,- selected,- theme,-}: {- onSelect: (themeId: WorkbenchThemeId) => void;- selected: boolean;- theme: ThemeDefinition;-}) => {- const recipe = useSlotRecipe({ recipe: themeCardRecipe });- const styles = recipe({ selected });-- return (- <chakra.button type="button" aria-pressed={selected} css={styles.root} onClick={() => onSelect(theme.id)}>- <Flex css={styles.preview}>- <Box css={styles.swatch} bg={theme.colors.surface} />- <Box css={styles.swatch} bg={theme.colors.panel} />- <Box css={styles.swatch} bg={theme.colors.accent} />- <Box css={styles.swatch} bg={theme.colors.active} />- </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 SettingToggle = ({- checked,- description,- label,- onChange,-}: {- checked: boolean;- description: string;- label: string;- onChange: (checked: boolean) => void;-}) => (- <Switch.Root- alignItems="center"- checked={checked}- display="flex"- justifyContent="space-between"- w="full"- onCheckedChange={(event) => onChange(event.checked)}- >- <Stack gap="0.5">- <Switch.Label color="fg.default" fontSize="sm" fontWeight="500" m="0">- {label}- </Switch.Label>- <Text color="fg.subtle" fontSize="xs">- {description}- </Text>- </Stack>- <Switch.HiddenInput />- <Switch.Control _checked={{ bg: 'accent.invoke' }}>- <Switch.Thumb />- </Switch.Control>- </Switch.Root>-);--const BehaviorSection = () => {- const { dispatch, state } = useWorkbench();- const { confirmImageDeletion } = state.account.preferences;-- return (- <SettingsSection description="Safety checks and interaction behavior." title="Behavior">- <SettingToggle- checked={confirmImageDeletion}- description="Ask for confirmation before permanently deleting images."- label="Confirm image deletion"- onChange={(checked) => dispatch({ preferences: { confirmImageDeletion: checked }, type: 'setPreferences' })}- />- </SettingsSection>- );-};--const WorkspaceSection = () => {- const { dispatch } = useWorkbench();-- const clearSavedData = () => {- void syncedWorkbenchPersistence.clearWorkbench().then(() => {- window.location.reload();- });- };-- return (- <SettingsSection description="Reset the layout or clear your saved projects and preferences." title="Workspace">- <HStack gap="2" wrap="wrap">- <Button size="sm" variant="outline" onClick={() => dispatch({ type: 'resetActiveLayout' })}>- <RotateCcwIcon />- Reset layout- </Button>- <Button- borderColor="border.emphasis"- color="fg.error"- size="sm"- variant="outline"- _hover={{ bg: 'fg.error', color: 'bg.surface' }}- onClick={clearSavedData}- >- <Trash2Icon />- Clear saved data- </Button>- </HStack>- </SettingsSection>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsxindex 08d9d4a14c..2a01d1f1a4 100644--- a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx@@ -4,9 +4,9 @@ import { ChevronDownIcon, ListOrderedIcon, PauseIcon, PlayIcon, XIcon } from 'luimport { InvokeControl } from './InvokeControl';import { LayoutPresetMenu } from './LayoutPresetMenu';import { ProjectTabs } from './ProjectTabs';-import { SettingsButton } from './SettingsDialog';import { IconButton } from './ui/Button';-import { UserMenu } from '../auth/components/UserMenu';+import { AccountMenu } from '../auth/components/AccountMenu';+import { useWorkbenchPreferences } from '../settings/store';import { useWorkbench } from '../WorkbenchContext';import { DEFAULT_THEME_ID, THEMES_BY_ID } from '../../theme/themes';import { Tooltip } from './ui/Tooltip';@@ -34,15 +34,14 @@ export const TopBar = () => (<Box w="1px" h="5" bg="border.subtle" mx="1" flexShrink={0} /><ProjectTabs /><LayoutPresetMenu />- <SettingsButton />- <UserMenu />+ <AccountMenu /></Flex>);/** Compact legacy Invoke logo used as the workbench app-menu affordance. */const BrandMark = () => {- const { state } = useWorkbench();- const theme = THEMES_BY_ID[state.account.preferences.themeId] ?? THEMES_BY_ID[DEFAULT_THEME_ID];+ const { themeId } = useWorkbenchPreferences();+ const theme = THEMES_BY_ID[themeId] ?? THEMES_BY_ID[DEFAULT_THEME_ID];return (<Linkdiff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 14b75b10d0..1e27e5fb0c 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -1,8 +1,8 @@import type { FocusEvent, PointerEvent, ReactNode } from 'react';import { createContext, use, useState } from 'react';+import { useWorkbenchPreferences } from './settings/store';import type { WidgetRegion } from './types';-import { useWorkbench } from './WorkbenchContext';interface FocusRegionContextValue {focusedRegion: WidgetRegion | null;@@ -48,8 +48,8 @@ const useFocusRegionContext = () => {export const useFocusRegionProps = (region: WidgetRegion) => {const { focusedRegion, setFocusedRegion } = useFocusRegionContext();- const { state } = useWorkbench();- const isHighlighted = state.account.preferences.showFocusRegionHighlight && focusedRegion === region;+ const { showFocusRegionHighlight } = useWorkbenchPreferences();+ const isHighlighted = showFocusRegionHighlight && focusedRegion === region;return {css: highlightStyles,diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.tsindex 4e6bada09f..6244b197ae 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts@@ -2,6 +2,7 @@ import type {BackendGraphContract,BackendGraphEdgeContract,BackendInvocationContract,+ ProjectSettings,ResultDestination,} from '../types';import type { CompiledGenerateGraph, GenerateSettings, MainModelConfig, SupportedGenerateBase } from './types';@@ -86,7 +87,8 @@ const addMetadata = (outputNode: BackendInvocationContract,settings: GenerateSettings,model: MainModelConfig,- generationMode: string+ generationMode: string,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>) => {const metadata = addNode(graph, {cfg_scale: settings.cfgScale,@@ -95,7 +97,7 @@ const addMetadata = (height: settings.height,id: createId('core_metadata'),model,- rand_device: 'cuda',+ rand_device: projectSettings.useCpuNoise ? 'cpu' : 'cuda',scheduler: settings.scheduler,steps: settings.steps,type: 'core_metadata',@@ -111,7 +113,8 @@ const addMetadata = (const buildSDGraph = (settings: GenerateSettings,model: MainModelConfig,- outputIsIntermediate: boolean+ outputIsIntermediate: boolean,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>): BackendGraphContract => {const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';@@ -129,7 +132,7 @@ const buildSDGraph = (height: settings.height,id: 'noise',type: 'noise',- use_cpu: false,+ use_cpu: projectSettings.useCpuNoise,width: settings.width,});const denoise = addNode(graph, {@@ -178,7 +181,7 @@ const buildSDGraph = (addEdge(graph, noise, 'noise', denoise, 'noise');addEdge(graph, denoise, 'latents', output, 'latents');addEdge(graph, modelLoader, 'vae', output, 'vae');- addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img');+ addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings);return graph;};@@ -202,13 +205,14 @@ const toGraphContract = (backendGraph: BackendGraphContract, label: string) => (export const compileGenerateGraph = (settings: GenerateSettings,model: MainModelConfig,- destination: ResultDestination+ destination: ResultDestination,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>): CompiledGenerateGraph => {if (!isSupportedGenerateModel(model)) {throw new Error(`${model.base} generation is not wired into the V7 Generate widget yet.`);}- const backendGraph = buildSDGraph(settings, model, destination === 'canvas');+ const backendGraph = buildSDGraph(settings, model, destination === 'canvas', projectSettings);return {backendGraph,diff --git a/invokeai/frontend/webv2/src/workbench/home/HomeTopBar.tsx b/invokeai/frontend/webv2/src/workbench/home/HomeTopBar.tsxindex 11ba3e363d..733799ed32 100644--- a/invokeai/frontend/webv2/src/workbench/home/HomeTopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/home/HomeTopBar.tsx@@ -1,16 +1,10 @@-import { Avatar, chakra, Flex, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { useNavigate } from '@tanstack/react-router';-import { ChevronDownIcon, LogOutIcon } from 'lucide-react';+import { Flex, HStack, Text } from '@chakra-ui/react';+import { AccountMenu } from '../auth/components/AccountMenu';import { InvokeMark } from '../auth/components/AuthScreen';-import { MenuContent } from '../components/ui/Menu';-import { logoutSession, useAuthSession } from '../auth/session';/**- * Home's slim header: brand on the left, the signed-in account on the right.- * Account settings and user management live in the editor shell; here the- * menu only carries identity and sign-out, and single-user mode shows no- * account cluster at all.+ * Home's slim header: brand on the left, shared account/settings controls on the right.*/export const HomeTopBar = () => (<Flex@@ -28,64 +22,6 @@ export const HomeTopBar = () => (Invoke</Text></HStack>- <HomeUserMenu />+ <AccountMenu /></Flex>);--const HomeUserMenu = () => {- const session = useAuthSession();- const navigate = useNavigate();-- if (!session.multiuserEnabled || session.user === null) {- return null;- }-- const user = session.user;- const label = user.display_name?.trim() || user.email;-- const signOut = async () => {- await logoutSession();- await navigate({ to: '/login' });- };-- return (- <Menu.Root positioning={{ placement: 'bottom-end' }}>- <Menu.Trigger asChild>- <chakra.button- alignItems="center"- color="fg.default"- display="flex"- flexShrink={0}- gap="1.5"- px="1.5"- py="1"- rounded="md"- type="button"- _hover={{ bg: 'bg.surface' }}- >- <Avatar.Root bg="accent.widget" color="fg.default" size="2xs">- <Avatar.Fallback fontSize="2xs" name={label} />- </Avatar.Root>- <Text fontSize="xs" fontWeight="600">- {label}- </Text>- <Icon as={ChevronDownIcon} boxSize="3" color="fg.muted" />- </chakra.button>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="48">- <Text color="fg.muted" fontSize="2xs" px="3" py="2">- {user.email}- </Text>- <Menu.Separator />- <Menu.Item value="sign-out" onClick={() => void signOut()}>- <Icon as={LogOutIcon} boxSize="3.5" />- Sign out- </Menu.Item>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.tsindex d442e25496..f9ee1d02fd 100644--- a/invokeai/frontend/webv2/src/workbench/persistence.ts+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts@@ -5,10 +5,9 @@ const BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';const WORKBENCH_SCHEMA_VERSION = 1;/**- * Projects, account preferences, and active layout are account-owned on- * multi-user backends (spec: State Ownership), so each signed-in user gets- * their own storage bucket on this browser. Single-user mode keeps the- * unscoped key, so existing data is untouched.+ * Projects and the editor session are account-owned on multi-user backends, so+ * each signed-in user gets their own storage bucket on this browser.+ * Single-user mode keeps the unscoped key, so existing data is untouched.*/const getStorageKey = (): string => `${BASE_STORAGE_KEY}${getUserStorageScope()}`;diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.tsindex ed43b0ade1..b46032b3d9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts@@ -1,9 +1,11 @@import { getClientStateValue } from './api';-import type { AccountState, WorkbenchState } from '../types';+import type { AccountState, WorkbenchPreferences, WorkbenchState } from '../types';/**- * The per-user session blob in the client-state KV: account preferences plus- * the editor session — which projects are open as tabs and which is active.+ * The per-user session blob in the client-state KV: the editor session — which+ * projects are open as tabs and which is active — plus a legacy account snapshot+ * for older installs. Current settings live in `settings.ts` so Home can load+ * them without mounting the workbench provider.** `openProjectIds` arrived with the library/session split. Blobs written* before it have no open set; `undefined` there means "unknown — open every@@ -23,7 +25,10 @@ export interface WorkbenchSearch {}export interface WorkbenchSessionBlob {- account: AccountState;+ account: AccountState & {+ /** Written by builds that kept preferences in the account; read once as a migration source. */+ preferences?: Partial<WorkbenchPreferences>;+ };activeProjectId: string;openProjectIds?: string[];}diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 9b816f13b4..4af418e1af 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -23,7 +23,7 @@ import {** The backend database is the source of truth: each project is one* revision-versioned document on the server, and the small session blob- * (preferences + open tabs + active project) lives in the per-user+ * (open tabs + active project, with legacy account data) lives in the per-user* client-state KV. The user-scoped localStorage snapshot is kept as a* write-through cache so the workbench still loads and autosaves while the* backend is unreachable; un-pushed changes are replayed on the next save ordiff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxnew file mode 100644index 0000000000..8abf804309--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -0,0 +1,613 @@+import {+ Box,+ chakra,+ Checkbox,+ Dialog,+ Field,+ Flex,+ HStack,+ Icon,+ NativeSelect,+ Portal,+ SimpleGrid,+ Stack,+ Switch,+ Tabs,+ Text,+ useSlotRecipe,+} from '@chakra-ui/react';+import { useId, useState, type ReactNode } from 'react';+import {+ CheckIcon,+ Code2Icon,+ DatabaseIcon,+ FolderIcon,+ PaletteIcon,+ RotateCcwIcon,+ SettingsIcon,+ SlidersHorizontalIcon,+ Trash2Icon,+ type LucideIcon,+} from 'lucide-react';++import { themeCardRecipe } from '../../theme/recipes';+import { THEMES, type ThemeDefinition } from '../../theme/system';+import { Button, CloseButton, IconButton } from '../components/ui/Button';+import { ConfirmDialog } from '../components/ui/ConfirmDialog';+import { syncedWorkbenchPersistence } from '../projects/syncedPersistence';+import type {+ DeveloperLogLevel,+ DeveloperLogNamespace,+ ProjectSettings,+ WorkbenchLanguage,+ WorkbenchPreferences,+ WorkbenchThemeId,+} from '../types';+import { useOptionalWorkbench } from '../WorkbenchContext';+import {+ clearWorkbenchSettings,+ DEVELOPER_LOG_LEVELS,+ DEVELOPER_LOG_NAMESPACES,+ patchWorkbenchPreferences,+ useWorkbenchPreferences,+ useWorkbenchSettings,+ WORKBENCH_LANGUAGES,+} from './store';++interface SettingsTabDefinition {+ value: string;+ label: string;+ icon: LucideIcon;+ condition?: boolean;+ children: ReactNode;+}++const updatePreferences = (patch: Partial<WorkbenchPreferences>): void => {+ void patchWorkbenchPreferences(patch);+};++export const SettingsButton = () => {+ const [isOpen, setIsOpen] = useState(false);++ return (+ <>+ <IconButton+ aria-label="Settings"+ color="fg.muted"+ size="sm"+ variant="ghost"+ _hover={{ color: 'fg.default' }}+ onClick={() => setIsOpen(true)}+ >+ <SettingsIcon />+ </IconButton>+ <SettingsDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />+ </>+ );+};++export const SettingsDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => (+ <Dialog.Root+ lazyMount+ open={isOpen}+ placement="center"+ scrollBehavior="inside"+ size="xl"+ unmountOnExit+ onOpenChange={(event) => {+ if (!event.open) {+ onClose();+ }+ }}+ >+ <SettingsDialogContent />+ </Dialog.Root>+);++const SettingsDialogContent = () => {+ const { error, scope, status } = useWorkbenchSettings();++ return (+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content+ bg="bg.surface"+ borderColor="border.subtle"+ borderWidth="1px"+ color="fg.default"+ h="min(46rem, calc(100dvh - 4rem))"+ maxW="4xl"+ >+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">+ <Stack gap="0.5">+ <Dialog.Title fontSize="md" fontWeight="700">+ Settings+ </Dialog.Title>+ <Text color="fg.subtle" fontSize="xs">+ {scope === 'user'+ ? 'Preferences for the signed-in user. Project settings apply only to the active project.'+ : 'Global preferences for this single-user install. Project settings apply only to the active project.'}+ </Text>+ {status === 'error' && error ? (+ <Text color="fg.error" fontSize="2xs">+ {error}+ </Text>+ ) : null}+ </Stack>+ </Dialog.Header>+ <Dialog.Body minH="0" p="0">+ <SettingsTabs />+ </Dialog.Body>+ <Dialog.CloseTrigger asChild>+ <CloseButton color="fg.muted" size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ );+};++const SettingsTabs = () => {+ const workbench = useOptionalWorkbench();+ const tabs: SettingsTabDefinition[] = [+ {+ children: <AppearanceSection />,+ icon: PaletteIcon,+ label: 'Appearance',+ value: 'appearance',+ },+ {+ children: <BehaviorSection />,+ icon: SlidersHorizontalIcon,+ label: 'Behavior',+ value: 'behavior',+ },+ {+ children: <ProjectSection />,+ condition: Boolean(workbench),+ icon: FolderIcon,+ label: 'Project',+ value: 'project',+ },+ {+ children: <DeveloperSection />,+ icon: Code2Icon,+ label: 'Developer',+ value: 'developer',+ },+ {+ children: <WorkspaceSection />,+ icon: DatabaseIcon,+ label: 'Workspace',+ value: 'workspace',+ },+ ].filter((tab) => tab.condition !== false);++ return (+ <Tabs.Root defaultValue="appearance" display="flex" h="full" minH="0" orientation="vertical" variant="subtle">+ <Tabs.List+ alignItems="stretch"+ bg="bg.shell"+ borderColor="border.subtle"+ borderRightWidth="1px"+ flexShrink={0}+ gap="1"+ p="2"+ w={{ base: '40', md: '52' }}+ >+ {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={{ base: '4', md: '5' }}>+ {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+ color="fg.muted"+ fontSize="xs"+ fontWeight="600"+ gap="2"+ justifyContent="flex-start"+ px="3"+ py="2"+ rounded="md"+ textAlign="start"+ value={value}+ w="full"+ _selected={{ bg: 'bg.surfaceRaised', color: 'fg.default' }}+ >+ <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.default" fontSize="sm" fontWeight="600">+ {title}+ </Text>+ <Text color="fg.subtle" fontSize="xs">+ {description}+ </Text>+ </Stack>+ {children}+ </Stack>+);++const AppearanceSection = () => {+ const { language, reduceMotion, showFocusRegionHighlight, themeId } = useWorkbenchPreferences();++ const selectTheme = (nextThemeId: WorkbenchThemeId) => {+ updatePreferences({ themeId: nextThemeId });+ };++ return (+ <SettingsSection description="Choose a theme, language, and motion behavior." title="Appearance">+ <SimpleGrid columns={{ base: 2, md: 3 }} gap="3">+ {THEMES.map((theme) => (+ <ThemeCard key={theme.id} selected={theme.id === themeId} theme={theme} onSelect={selectTheme} />+ ))}+ </SimpleGrid>+ <SettingSelect+ comingSoon+ description="Interface language. More i18n coverage will arrive soon."+ label="Language"+ value={language}+ onChange={(value) => updatePreferences({ language: value as WorkbenchLanguage })}+ >+ {WORKBENCH_LANGUAGES.map((value) => (+ <option key={value} value={value}>+ {value}+ </option>+ ))}+ </SettingSelect>+ <SettingToggle+ checked={reduceMotion}+ description="Disable transitions and animations across the workbench."+ label="Reduce motion"+ onChange={(checked) => updatePreferences({ reduceMotion: checked })}+ />+ <SettingToggle+ checked={showFocusRegionHighlight}+ description="Draw a subtle outline around the active workbench region."+ label="Highlight focused region"+ onChange={(checked) => updatePreferences({ showFocusRegionHighlight: checked })}+ />+ </SettingsSection>+ );+};++const ThemeCard = ({+ onSelect,+ selected,+ theme,+}: {+ onSelect: (themeId: WorkbenchThemeId) => void;+ selected: boolean;+ theme: ThemeDefinition;+}) => {+ const recipe = useSlotRecipe({ recipe: themeCardRecipe });+ const styles = recipe({ selected });++ return (+ <chakra.button type="button" aria-pressed={selected} css={styles.root} onClick={() => onSelect(theme.id)}>+ <Flex css={styles.preview}>+ <Box css={styles.swatch} bg={theme.colors.surface} />+ <Box css={styles.swatch} bg={theme.colors.panel} />+ <Box css={styles.swatch} bg={theme.colors.accent} />+ <Box css={styles.swatch} bg={theme.colors.active} />+ </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 { confirmImageDeletion, enableInformationalPopovers, enableModelDescriptions } = useWorkbenchPreferences();++ return (+ <SettingsSection description="Safety checks and user-assistance behavior." title="Behavior">+ <SettingToggle+ checked={confirmImageDeletion}+ description="Ask for confirmation before permanently deleting images."+ label="Confirm image deletion"+ onChange={(checked) => updatePreferences({ confirmImageDeletion: checked })}+ />+ <SettingToggle+ checked={enableInformationalPopovers}+ comingSoon+ description="Show educational popovers on controls that have extra guidance."+ label="Enable informational popovers"+ onChange={(checked) => updatePreferences({ enableInformationalPopovers: checked })}+ />+ <SettingToggle+ checked={enableModelDescriptions}+ description="Include model descriptions in model dropdowns where available."+ label="Enable model descriptions in dropdowns"+ onChange={(checked) => updatePreferences({ enableModelDescriptions: checked })}+ />+ </SettingsSection>+ );+};++const ProjectSection = () => {+ const workbench = useOptionalWorkbench();++ if (!workbench) {+ return null;+ }++ const settings = workbench.activeProject.settings;+ const updateProjectSettings = (patch: Partial<ProjectSettings>) => {+ workbench.dispatch({ settings: patch, type: 'setActiveProjectSettings' });+ };++ return (+ <SettingsSection+ description={`Settings saved with ${workbench.activeProject.name}. Future project-only settings can live here without becoming user preferences.`}+ title="Project"+ >+ <SettingToggle+ checked={settings.useCpuNoise}+ description="Use CPU noise generation for deterministic legacy-compatible outputs."+ label="Use CPU noise"+ onChange={(checked) => updateProjectSettings({ useCpuNoise: checked })}+ />+ <SettingToggle+ checked={settings.showProgressDetails}+ comingSoon+ description="Show detailed invocation progress when the backend reports it."+ label="Show progress details"+ onChange={(checked) => updateProjectSettings({ showProgressDetails: checked })}+ />+ <SettingToggle+ checked={settings.antialiasProgressImages}+ comingSoon+ description="Smooth progress previews instead of rendering them pixelated."+ label="Antialias progress images"+ onChange={(checked) => updateProjectSettings({ antialiasProgressImages: checked })}+ />+ <SettingToggle+ checked={settings.showProgressImagesInViewer}+ comingSoon+ description="Show progress images in the viewer when an image is still generating."+ label="Show progress images in viewer"+ onChange={(checked) => updateProjectSettings({ showProgressImagesInViewer: checked })}+ />+ <SettingToggle+ checked={settings.preferNumericAttentionStyle}+ comingSoon+ description="Prefer numeric prompt attention syntax when controls insert attention weights."+ label="Prefer numeric attention style"+ onChange={(checked) => updateProjectSettings({ preferNumericAttentionStyle: checked })}+ />+ </SettingsSection>+ );+};++const DeveloperSection = () => {+ const { developerLogEnabled, developerLogLevel, developerLogNamespaces } = useWorkbenchPreferences();+ const enabledNamespaces = new Set(developerLogNamespaces);++ const toggleNamespace = (namespace: DeveloperLogNamespace, checked: boolean) => {+ const next = checked+ ? [...developerLogNamespaces, namespace]+ : developerLogNamespaces.filter((candidate) => candidate !== namespace);++ updatePreferences({+ developerLogNamespaces: DEVELOPER_LOG_NAMESPACES.filter((candidate) => next.includes(candidate)),+ });+ };++ return (+ <SettingsSection description="Console logging controls for development builds." title="Developer">+ <SettingToggle+ checked={developerLogEnabled}+ comingSoon+ description="Enable console logging for selected namespaces."+ label="Enable developer logs"+ onChange={(checked) => updatePreferences({ developerLogEnabled: checked })}+ />+ <SettingSelect+ comingSoon+ description="Minimum log level written to the console."+ label="Log level"+ value={developerLogLevel}+ onChange={(value) => updatePreferences({ developerLogLevel: value as DeveloperLogLevel })}+ >+ {DEVELOPER_LOG_LEVELS.map((value) => (+ <option key={value} value={value}>+ {formatSettingLabel(value)}+ </option>+ ))}+ </SettingSelect>+ <Stack gap="2">+ <Text color="fg.default" fontSize="sm" fontWeight="500">+ Log namespaces+ </Text>+ <SimpleGrid columns={{ base: 1, md: 2 }} gap="2">+ {DEVELOPER_LOG_NAMESPACES.map((namespace) => (+ <Checkbox.Root+ key={namespace}+ checked={enabledNamespaces.has(namespace)}+ disabled+ size="sm"+ onCheckedChange={(event) => toggleNamespace(namespace, event.checked === true)}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label color="fg.muted" fontSize="xs">+ {formatSettingLabel(namespace)}+ </Checkbox.Label>+ </Checkbox.Root>+ ))}+ </SimpleGrid>+ </Stack>+ </SettingsSection>+ );+};++const WorkspaceSection = () => {+ const workbench = useOptionalWorkbench();+ const { scope } = useWorkbenchSettings();+ const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);++ const clearSavedData = async () => {+ await Promise.all([syncedWorkbenchPersistence.clearWorkbench(), clearWorkbenchSettings()]);+ window.location.reload();+ };++ return (+ <SettingsSection+ description="Reset the layout, or permanently delete saved projects and settings."+ title="Workspace"+ >+ <HStack gap="2" wrap="wrap">+ {workbench ? (+ <Button size="sm" variant="outline" onClick={() => workbench.dispatch({ type: 'resetActiveLayout' })}>+ <RotateCcwIcon />+ Reset layout+ </Button>+ ) : null}+ <Button+ borderColor="border.emphasis"+ color="fg.error"+ size="sm"+ variant="outline"+ _hover={{ bg: 'fg.error', color: 'bg.surface' }}+ onClick={() => setIsClearConfirmOpen(true)}+ >+ <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={() => setIsClearConfirmOpen(false)}+ onConfirm={clearSavedData}+ />+ </SettingsSection>+ );+};++const SettingToggle = ({+ checked,+ comingSoon,+ description,+ label,+ onChange,+}: {+ checked: boolean;+ comingSoon?: boolean;+ description: string;+ label: string;+ onChange: (checked: boolean) => void;+}) => {+ const descriptionId = useId();++ return (+ <Switch.Root+ alignItems="center"+ checked={checked}+ disabled={comingSoon}+ display="flex"+ gap="4"+ justifyContent="space-between"+ w="full"+ onCheckedChange={(event) => onChange(event.checked)}+ >+ <Stack gap="0.5">+ <Switch.Label color="fg.default" fontSize="sm" fontWeight="500" m="0">+ {label}+ </Switch.Label>+ <Text color="fg.subtle" fontSize="xs" id={descriptionId}>+ {description}+ </Text>+ </Stack>+ <Switch.HiddenInput aria-describedby={descriptionId} />+ <Switch.Control flexShrink={0} _checked={{ bg: 'accent.invoke' }}>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Root>+ );+};++const SettingSelect = ({+ children,+ comingSoon,+ description,+ label,+ onChange,+ value,+}: {+ children: ReactNode;+ comingSoon?: boolean;+ description: string;+ label: string;+ onChange: (value: string) => void;+ value: string;+}) => (+ <Field.Root+ alignItems={{ base: 'stretch', md: 'center' }}+ disabled={comingSoon}+ display="flex"+ flexDirection={{ base: 'column', md: 'row' }}+ gap="3"+ justifyContent="space-between"+ >+ <Stack gap="0.5">+ <Field.Label color="fg.default" fontSize="sm" fontWeight="500" m="0">+ {label}+ </Field.Label>+ <Field.HelperText color="fg.subtle" fontSize="xs" m="0">+ {description}+ </Field.HelperText>+ </Stack>+ <NativeSelect.Root flexShrink={0} maxW={{ base: 'full', md: '56' }} size="sm" w="full">+ <NativeSelect.Field value={value} onChange={(event) => onChange(event.currentTarget.value)}>+ {children}+ </NativeSelect.Field>+ <NativeSelect.Indicator />+ </NativeSelect.Root>+ </Field.Root>+);++const formatSettingLabel = (value: string): string =>+ value+ .split('-')+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ');diff --git a/invokeai/frontend/webv2/src/workbench/settings/index.ts b/invokeai/frontend/webv2/src/workbench/settings/index.tsnew file mode 100644index 0000000000..b0175d4b12--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/index.ts@@ -0,0 +1,2 @@+export * from './SettingsDialog';+export * from './store';diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsnew file mode 100644index 0000000000..dc39a32809--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -0,0 +1,193 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as storeModule from './store';++/**+ * The settings store's load/patch contract: backend-first with legacy+ * migration, resolved once per account scope, and offline edits replay+ * instead of being reverted by a stale server copy.+ */++const api = vi.hoisted(() => {+ const clientState = new Map<string, string>();++ return {+ __clientState: clientState,+ deleteClientStateValue: vi.fn((key: string) => {+ clientState.delete(key);++ return Promise.resolve();+ }),+ getClientStateValue: vi.fn((key: string) => Promise.resolve(clientState.get(key) ?? null)),+ setClientStateValue: vi.fn((key: string, value: string) => {+ clientState.set(key, value);++ return Promise.resolve();+ }),+ };+});++const auth = vi.hoisted(() => ({ scope: '' }));++vi.mock('../projects/api', () => api);+vi.mock('../auth/session', () => ({ getUserStorageScope: () => auth.scope }));++const storage = new Map<string, string>();++vi.stubGlobal('window', {+ localStorage: {+ getItem: (key: string): string | null => storage.get(key) ?? null,+ removeItem: (key: string): void => {+ storage.delete(key);+ },+ setItem: (key: string, value: string): void => {+ storage.set(key, value);+ },+ },+});++const SETTINGS_KEY = 'webv2:workbench-settings';+const SESSION_KEY = 'webv2:workbench-account';++let store: typeof storeModule;++const seedBackendPreferences = (preferences: Record<string, unknown>): void => {+ api.__clientState.set(SETTINGS_KEY, JSON.stringify(preferences));+};++const readBackendPreferences = (): Record<string, unknown> =>+ JSON.parse(api.__clientState.get(SETTINGS_KEY) ?? 'null') as Record<string, unknown>;++beforeEach(async () => {+ vi.resetModules();+ api.__clientState.clear();+ api.deleteClientStateValue.mockClear();+ api.getClientStateValue.mockClear();+ api.setClientStateValue.mockClear();+ auth.scope = '';+ storage.clear();++ store = await import('./store');+});++describe('loadWorkbenchSettings', () => {+ it('adopts backend preferences without writing them back', async () => {+ seedBackendPreferences({ themeId: 'forest' });++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('forest');+ expect(api.setClientStateValue).not.toHaveBeenCalled();+ expect(store.useWorkbenchSettings).toBeDefined();+ expect(store.getWorkbenchPreferences().themeId).toBe('forest');+ });++ it('migrates legacy session-blob preferences once when the settings key is missing', async () => {+ api.__clientState.set(+ SESSION_KEY,+ JSON.stringify({+ account: { activeLayoutPresetId: 'gallery', preferences: { themeId: 'mono' } },+ activeProjectId: 'p1',+ })+ );++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('mono');+ expect(readBackendPreferences().themeId).toBe('mono');+ expect(api.setClientStateValue).toHaveBeenCalledTimes(1);+ });++ it('resolves once per scope and reloads when the scope changes', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();+ await store.loadWorkbenchSettings();++ expect(api.getClientStateValue.mock.calls.filter(([key]) => key === SETTINGS_KEY)).toHaveLength(1);++ auth.scope = ':user:u2';+ seedBackendPreferences({ themeId: 'light' });++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('light');+ });++ it('heals invalid stored values to defaults', async () => {+ seedBackendPreferences({ developerLogLevel: 'shout', themeId: 'sunset' });++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('dark');+ expect(preferences.developerLogLevel).toBe('debug');+ });++ it('serves the local copy when the backend is unreachable and retries next time', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();++ vi.resetModules();+ store = await import('./store');+ api.getClientStateValue.mockRejectedValueOnce(new Error('offline'));++ const offline = await store.loadWorkbenchSettings();++ expect(offline.themeId).toBe('forest');+ expect(store.useWorkbenchSettings).toBeDefined();++ const recovered = await store.loadWorkbenchSettings();++ expect(recovered.themeId).toBe('forest');+ });++ it('reports an error with defaults when nothing is available anywhere', async () => {+ api.getClientStateValue.mockRejectedValueOnce(new Error('offline'));++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('dark');+ });+});++describe('patchWorkbenchPreferences', () => {+ it('persists to the backend and localStorage', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();++ await store.patchWorkbenchPreferences({ reduceMotion: true });++ expect(readBackendPreferences().reduceMotion).toBe(true);+ expect(readBackendPreferences().themeId).toBe('forest');+ expect(store.getWorkbenchPreferences().reduceMotion).toBe(true);+ });++ it('replays an offline edit on the next load instead of reverting to the server copy', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();++ api.setClientStateValue.mockRejectedValueOnce(new Error('offline'));+ await store.patchWorkbenchPreferences({ themeId: 'light' });++ expect(readBackendPreferences().themeId).toBe('forest');++ vi.resetModules();+ store = await import('./store');++ const preferences = await store.loadWorkbenchSettings();++ expect(preferences.themeId).toBe('light');+ expect(readBackendPreferences().themeId).toBe('light');+ });+});++describe('clearWorkbenchSettings', () => {+ it('resets to defaults locally and deletes the backend key', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();++ await store.clearWorkbenchSettings();++ expect(store.getWorkbenchPreferences().themeId).toBe('dark');+ expect(api.__clientState.has(SETTINGS_KEY)).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsnew file mode 100644index 0000000000..302a8cffbe--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -0,0 +1,387 @@+import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '../../theme/themes';+import { getUserStorageScope } from '../auth/session';+import { createExternalStore } from '../externalStore';+import { deleteClientStateValue, getClientStateValue, setClientStateValue } from '../projects/api';+import { fetchSessionBlob } from '../projects/session';+import type {+ DeveloperLogLevel,+ DeveloperLogNamespace,+ ProjectSettings,+ WorkbenchLanguage,+ WorkbenchPreferences,+} from '../types';++const SETTINGS_BASE_STORAGE_KEY = 'invokeai:v7:webv2:settings';+const LEGACY_WORKBENCH_BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';+const SETTINGS_CLIENT_STATE_KEY = 'webv2:workbench-settings';++export const WORKBENCH_LANGUAGES: WorkbenchLanguage[] = [+ 'ar',+ 'az',+ 'de',+ 'en',+ 'es',+ 'fi',+ 'fr',+ 'he',+ 'hu',+ 'it',+ 'ja',+ 'ko',+ 'nl',+ 'pl',+ 'pt',+ 'pt-BR',+ 'ru',+ 'sv',+ 'tr',+ 'ua',+ 'vi',+ 'zh-CN',+ 'zh-Hant',+];++export const DEVELOPER_LOG_LEVELS: DeveloperLogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];++export const DEVELOPER_LOG_NAMESPACES: DeveloperLogNamespace[] = [+ 'canvas',+ 'canvas-workflow-integration',+ 'config',+ 'dnd',+ 'events',+ 'gallery',+ 'generation',+ 'metadata',+ 'models',+ 'system',+ 'queue',+ 'workflows',+];++export const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {+ antialiasProgressImages: false,+ preferNumericAttentionStyle: false,+ showProgressDetails: false,+ showProgressImagesInViewer: true,+ useCpuNoise: true,+};++export const DEFAULT_PREFERENCES: WorkbenchPreferences = {+ confirmImageDeletion: true,+ developerLogEnabled: true,+ developerLogLevel: 'debug',+ developerLogNamespaces: [...DEVELOPER_LOG_NAMESPACES],+ enableInformationalPopovers: true,+ enableModelDescriptions: true,+ language: 'en',+ reduceMotion: false,+ showFocusRegionHighlight: true,+ themeId: DEFAULT_THEME_ID,+};++interface WorkbenchSettingsSnapshot {+ preferences: WorkbenchPreferences;+ scope: 'global' | 'user';+ status: 'idle' | 'loading' | 'ready' | 'error';+ error?: string;+}++const store = createExternalStore<WorkbenchSettingsSnapshot>({+ preferences: { ...DEFAULT_PREFERENCES, developerLogNamespaces: [...DEFAULT_PREFERENCES.developerLogNamespaces] },+ scope: 'global',+ status: 'idle',+});++const isBrowser = (): boolean => typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';++const getSettingsStorageKey = (): string => `${SETTINGS_BASE_STORAGE_KEY}${getUserStorageScope()}`;++const getLegacyWorkbenchStorageKey = (): string => `${LEGACY_WORKBENCH_BASE_STORAGE_KEY}${getUserStorageScope()}`;++const getSettingsScope = (): WorkbenchSettingsSnapshot['scope'] => (getUserStorageScope() ? 'user' : 'global');++const isWorkbenchLanguage = (value: unknown): value is WorkbenchLanguage =>+ typeof value === 'string' && WORKBENCH_LANGUAGES.includes(value as WorkbenchLanguage);++const isDeveloperLogLevel = (value: unknown): value is DeveloperLogLevel =>+ typeof value === 'string' && DEVELOPER_LOG_LEVELS.includes(value as DeveloperLogLevel);++const normalizeDeveloperLogNamespaces = (values: unknown): DeveloperLogNamespace[] => {+ if (!Array.isArray(values)) {+ return [...DEFAULT_PREFERENCES.developerLogNamespaces];+ }++ const enabled = new Set(+ values.filter(+ (value): value is DeveloperLogNamespace =>+ typeof value === 'string' && DEVELOPER_LOG_NAMESPACES.includes(value as DeveloperLogNamespace)+ )+ );++ return DEVELOPER_LOG_NAMESPACES.filter((namespace) => enabled.has(namespace));+};++export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): ProjectSettings => ({+ antialiasProgressImages:+ typeof settings?.antialiasProgressImages === 'boolean'+ ? settings.antialiasProgressImages+ : DEFAULT_PROJECT_SETTINGS.antialiasProgressImages,+ preferNumericAttentionStyle:+ typeof settings?.preferNumericAttentionStyle === 'boolean'+ ? settings.preferNumericAttentionStyle+ : DEFAULT_PROJECT_SETTINGS.preferNumericAttentionStyle,+ showProgressDetails:+ typeof settings?.showProgressDetails === 'boolean'+ ? settings.showProgressDetails+ : DEFAULT_PROJECT_SETTINGS.showProgressDetails,+ showProgressImagesInViewer:+ typeof settings?.showProgressImagesInViewer === 'boolean'+ ? settings.showProgressImagesInViewer+ : DEFAULT_PROJECT_SETTINGS.showProgressImagesInViewer,+ useCpuNoise: typeof settings?.useCpuNoise === 'boolean' ? settings.useCpuNoise : DEFAULT_PROJECT_SETTINGS.useCpuNoise,+});++export const normalizeWorkbenchPreferences = (preferences?: Partial<WorkbenchPreferences>): WorkbenchPreferences => ({+ confirmImageDeletion:+ typeof preferences?.confirmImageDeletion === 'boolean'+ ? preferences.confirmImageDeletion+ : DEFAULT_PREFERENCES.confirmImageDeletion,+ developerLogEnabled:+ typeof preferences?.developerLogEnabled === 'boolean'+ ? preferences.developerLogEnabled+ : DEFAULT_PREFERENCES.developerLogEnabled,+ developerLogLevel: isDeveloperLogLevel(preferences?.developerLogLevel)+ ? preferences.developerLogLevel+ : DEFAULT_PREFERENCES.developerLogLevel,+ developerLogNamespaces: normalizeDeveloperLogNamespaces(preferences?.developerLogNamespaces),+ enableInformationalPopovers:+ typeof preferences?.enableInformationalPopovers === 'boolean'+ ? preferences.enableInformationalPopovers+ : DEFAULT_PREFERENCES.enableInformationalPopovers,+ enableModelDescriptions:+ typeof preferences?.enableModelDescriptions === 'boolean'+ ? preferences.enableModelDescriptions+ : DEFAULT_PREFERENCES.enableModelDescriptions,+ language: isWorkbenchLanguage(preferences?.language) ? preferences.language : DEFAULT_PREFERENCES.language,+ reduceMotion:+ typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion,+ showFocusRegionHighlight:+ typeof preferences?.showFocusRegionHighlight === 'boolean'+ ? preferences.showFocusRegionHighlight+ : DEFAULT_PREFERENCES.showFocusRegionHighlight,+ themeId: isWorkbenchThemeId(preferences?.themeId) ? preferences.themeId : DEFAULT_PREFERENCES.themeId,+});++const parsePreferences = (raw: string | null): WorkbenchPreferences | null => {+ if (!raw) {+ return null;+ }++ try {+ return normalizeWorkbenchPreferences(JSON.parse(raw) as Partial<WorkbenchPreferences>);+ } catch {+ return null;+ }+};++/**+ * The localStorage payload: preferences plus a dirty marker for edits that+ * never reached the backend. A pending local copy outranks the server at the+ * next load, so going offline cannot silently revert a change.+ */+interface StoredSettings {+ preferences: WorkbenchPreferences;+ pendingPush?: boolean;+}++const readLocalSettings = (): StoredSettings | null => {+ if (!isBrowser()) {+ return null;+ }++ try {+ const parsed = JSON.parse(window.localStorage.getItem(getSettingsStorageKey()) ?? 'null') as+ | (Partial<StoredSettings> & Partial<WorkbenchPreferences>)+ | null;++ if (!parsed || typeof parsed !== 'object') {+ return null;+ }++ // Early builds stored the bare preferences object.+ if (!parsed.preferences) {+ return { preferences: normalizeWorkbenchPreferences(parsed) };+ }++ return {+ pendingPush: parsed.pendingPush === true || undefined,+ preferences: normalizeWorkbenchPreferences(parsed.preferences),+ };+ } catch {+ return null;+ }+};++const writeLocalSettings = (preferences: WorkbenchPreferences, pendingPush?: boolean): void => {+ if (!isBrowser()) {+ return;+ }++ const payload: StoredSettings = pendingPush ? { pendingPush, preferences } : { preferences };++ window.localStorage.setItem(getSettingsStorageKey(), JSON.stringify(payload));+};++const removeLocalSettings = (): void => {+ if (!isBrowser()) {+ return;+ }++ window.localStorage.removeItem(getSettingsStorageKey());+};++const readLegacyLocalPreferences = (): WorkbenchPreferences | null => {+ if (!isBrowser()) {+ return null;+ }++ try {+ const raw = window.localStorage.getItem(getLegacyWorkbenchStorageKey());+ const parsed = raw ? (JSON.parse(raw) as { state?: { account?: { preferences?: unknown } } }) : null;++ return parsed?.state?.account?.preferences+ ? normalizeWorkbenchPreferences(parsed.state.account.preferences as Partial<WorkbenchPreferences>)+ : null;+ } catch {+ return null;+ }+};++const loadLegacySessionPreferences = async (): Promise<WorkbenchPreferences | null> => {+ const blob = await fetchSessionBlob();++ return blob?.account.preferences ? normalizeWorkbenchPreferences(blob.account.preferences) : null;+};++const replaceSnapshot = (preferences: WorkbenchPreferences, status: WorkbenchSettingsSnapshot['status']): void => {+ store.setSnapshot({ preferences, scope: getSettingsScope(), status });+};++const pushPreferences = (preferences: WorkbenchPreferences): Promise<void> =>+ setClientStateValue(SETTINGS_CLIENT_STATE_KEY, JSON.stringify(preferences));++const resolveSettings = async (local: StoredSettings | null): Promise<WorkbenchPreferences> => {+ if (local?.pendingPush) {+ await pushPreferences(local.preferences);++ return local.preferences;+ }++ const backendPreferences = parsePreferences(await getClientStateValue(SETTINGS_CLIENT_STATE_KEY));++ if (backendPreferences) {+ return backendPreferences;+ }++ // First contact for this account: adopt whatever the legacy locations+ // hold and write the new backend key once.+ const preferences =+ (await loadLegacySessionPreferences()) ??+ local?.preferences ??+ readLegacyLocalPreferences() ??+ normalizeWorkbenchPreferences();++ await pushPreferences(preferences);++ return preferences;+};++let pendingLoad: Promise<WorkbenchPreferences> | null = null;+let pendingLoadStorageKey = '';+let loadedStorageKey: string | null = null;++/**+ * Resolve settings once per account scope (a sign-in/out switches scope and+ * reloads); later calls return the snapshot. Offline, the local copy serves+ * and the next load retries the backend.+ */+export const loadWorkbenchSettings = (): Promise<WorkbenchPreferences> => {+ const storageKey = getSettingsStorageKey();++ if (pendingLoad && pendingLoadStorageKey === storageKey) {+ return pendingLoad;+ }++ if (loadedStorageKey === storageKey) {+ return Promise.resolve(getWorkbenchPreferences());+ }++ pendingLoadStorageKey = storageKey;+ store.patchSnapshot({ scope: getSettingsScope(), status: 'loading' });++ pendingLoad = (async () => {+ const local = readLocalSettings();++ try {+ const preferences = await resolveSettings(local);++ writeLocalSettings(preferences);+ replaceSnapshot(preferences, 'ready');+ loadedStorageKey = storageKey;++ return preferences;+ } catch (error) {+ const fallback = local?.preferences ?? readLegacyLocalPreferences();+ const preferences = fallback ?? normalizeWorkbenchPreferences();++ writeLocalSettings(preferences, local?.pendingPush);+ store.setSnapshot({+ error: error instanceof Error ? error.message : 'Failed to load settings from the backend.',+ preferences,+ scope: getSettingsScope(),+ status: fallback ? 'ready' : 'error',+ });++ return preferences;+ }+ })().finally(() => {+ pendingLoad = null;+ });++ return pendingLoad;+};++export const useWorkbenchSettings = (): WorkbenchSettingsSnapshot => store.useSnapshot();++export const useWorkbenchPreferences = (): WorkbenchPreferences => store.useSnapshot().preferences;++export const getWorkbenchPreferences = (): WorkbenchPreferences => store.getSnapshot().preferences;++export const patchWorkbenchPreferences = async (preferences: Partial<WorkbenchPreferences>): Promise<void> => {+ const next = normalizeWorkbenchPreferences({ ...store.getSnapshot().preferences, ...preferences });++ replaceSnapshot(next, 'ready');+ writeLocalSettings(next, true);++ try {+ await pushPreferences(next);+ writeLocalSettings(next);+ } catch (error) {+ store.patchSnapshot({+ error: error instanceof Error ? error.message : 'Failed to save settings.',+ status: 'error',+ });+ }+};++export const clearWorkbenchSettings = async (): Promise<void> => {+ removeLocalSettings();+ replaceSnapshot(normalizeWorkbenchPreferences(), 'ready');+ loadedStorageKey = getSettingsStorageKey();++ try {+ await deleteClientStateValue(SETTINGS_CLIENT_STATE_KEY);+ } catch {+ // Backend persistence is best-effort; the local reset should still complete.+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex 28f45db2cb..eda053bbbc 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -277,6 +277,7 @@ export interface Project {*/recoveryOf?: string;recoveredAt?: string;+ settings: ProjectSettings;layout: ProjectLayoutState;invocation: InvocationControllerState;projectGraph: GraphContract;@@ -415,17 +416,71 @@ export interface AutosaveState {*/export type WorkbenchThemeId = 'dark' | 'light' | 'forest' | 'mono' | 'ultradark';+export type WorkbenchLanguage =+ | 'ar'+ | 'az'+ | 'de'+ | 'en'+ | 'es'+ | 'fi'+ | 'fr'+ | 'he'+ | 'hu'+ | 'it'+ | 'ja'+ | 'ko'+ | 'nl'+ | 'pl'+ | 'pt'+ | 'pt-BR'+ | 'ru'+ | 'sv'+ | 'tr'+ | 'ua'+ | 'vi'+ | 'zh-CN'+ | 'zh-Hant';++export type DeveloperLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';++export type DeveloperLogNamespace =+ | 'canvas'+ | 'canvas-workflow-integration'+ | 'config'+ | 'dnd'+ | 'events'+ | 'gallery'+ | 'generation'+ | 'metadata'+ | 'models'+ | 'system'+ | 'queue'+ | 'workflows';++export interface ProjectSettings {+ useCpuNoise: boolean;+ showProgressDetails: boolean;+ antialiasProgressImages: boolean;+ showProgressImagesInViewer: boolean;+ preferNumericAttentionStyle: boolean;+}+/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */export interface WorkbenchPreferences {themeId: WorkbenchThemeId;reduceMotion: boolean;showFocusRegionHighlight: boolean;confirmImageDeletion: boolean;+ language: WorkbenchLanguage;+ enableInformationalPopovers: boolean;+ enableModelDescriptions: boolean;+ developerLogEnabled: boolean;+ developerLogLevel: DeveloperLogLevel;+ developerLogNamespaces: DeveloperLogNamespace[];}export interface AccountState {activeLayoutPresetId: LayoutPresetId;- preferences: WorkbenchPreferences;}export interface WorkbenchPersistenceSnapshot {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 1e73a474c0..c155af137a 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import type { GenerateWidgetValues, MainModelConfig } from './generation/types';+import { DEFAULT_PROJECT_SETTINGS } from './settings/store';import type { GeneratedImageContract, Project, WorkbenchState } from './types';import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';@@ -548,87 +549,50 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});-describe('workbench preferences', () => {- it('defaults to the dark theme with motion enabled', () => {+describe('workbench account and project settings', () => {+ it('starts with the default layout preset and legacy-matching project settings', () => {const state = createInitialWorkbenchState();- expect(state.account.preferences).toEqual({- confirmImageDeletion: true,- reduceMotion: false,- showFocusRegionHighlight: true,- themeId: 'dark',- });- });-- it('updates the theme without dropping other preferences', () => {- let state = createInitialWorkbenchState();-- state = workbenchReducer(state, { preferences: { reduceMotion: true }, type: 'setPreferences' });- state = workbenchReducer(state, { preferences: { showFocusRegionHighlight: false }, type: 'setPreferences' });- state = workbenchReducer(state, { preferences: { themeId: 'forest' }, type: 'setPreferences' });-- expect(state.account.preferences).toEqual({- confirmImageDeletion: true,- reduceMotion: true,- showFocusRegionHighlight: false,- themeId: 'forest',- });- });-- it('preserves preferences when applying a layout preset', () => {- let state = createInitialWorkbenchState();-- state = workbenchReducer(state, { preferences: { themeId: 'mono' }, type: 'setPreferences' });- state = workbenchReducer(state, { presetId: 'gallery', type: 'applyPreset' });-- expect(state.account.activeLayoutPresetId).toBe('gallery');- expect(state.account.preferences.themeId).toBe('mono');+ expect(state.account).toEqual({ activeLayoutPresetId: 'canvas-default' });+ expect(getActiveProject(state).settings).toEqual(DEFAULT_PROJECT_SETTINGS);});- it('heals hydrated state that predates preferences', () => {+ it('drops legacy preferences carried inside persisted accounts on hydrate', () => {const initial = createInitialWorkbenchState();const legacy = {...initial,- account: { activeLayoutPresetId: initial.account.activeLayoutPresetId },+ account: { activeLayoutPresetId: 'gallery', preferences: { themeId: 'forest' } },} as unknown as WorkbenchState;const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });- expect(state.account.preferences).toEqual({- confirmImageDeletion: true,- reduceMotion: false,- showFocusRegionHighlight: true,- themeId: 'dark',- });+ expect(state.account).toEqual({ activeLayoutPresetId: 'gallery' });});- it('heals hydrated state with an unsupported theme id', () => {+ it('heals hydrated accounts that are missing a layout preset', () => {const initial = createInitialWorkbenchState();- const persisted = {- ...initial,- account: {- ...initial.account,- preferences: { reduceMotion: true, showFocusRegionHighlight: false, themeId: 'sunset' },- },- } as unknown as WorkbenchState;+ const legacy = { ...initial, account: {} } as unknown as WorkbenchState;- const state = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });+ const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });- expect(state.account.preferences).toEqual({- confirmImageDeletion: true,- reduceMotion: true,- showFocusRegionHighlight: false,- themeId: 'dark',- });+ expect(state.account.activeLayoutPresetId).toBe('canvas-default');});- it('rejects unsupported theme ids when updating preferences', () => {- const state = workbenchReducer(createInitialWorkbenchState(), {- preferences: { themeId: 'sunset' },- type: 'setPreferences',- } as unknown as Parameters<typeof workbenchReducer>[1]);+ it('updates project settings on the active project only', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ settings: { antialiasProgressImages: true, preferNumericAttentionStyle: true, useCpuNoise: false },+ type: 'setActiveProjectSettings',+ });- expect(state.account.preferences.themeId).toBe('dark');+ expect(getActiveProject(state).settings).toEqual({+ antialiasProgressImages: true,+ preferNumericAttentionStyle: true,+ showProgressDetails: false,+ showProgressImagesInViewer: true,+ useCpuNoise: false,+ });});});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex eb0a1369f6..56e269de14 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -4,11 +4,11 @@ import {isInvocationSourceAvailable,resolveInvocationRoute,} from './invocation';-import { DEFAULT_THEME_ID, isWorkbenchThemeId } from '../theme/themes';import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';import type { GallerySettings } from './gallery/settings';import type { GenerateWidgetValues, MainModelConfig } from './generation/types';import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';+import { normalizeProjectSettings } from './settings/store';import type {CanvasDocumentContract,CanvasPlacementContract,@@ -24,6 +24,7 @@ import type {LayoutPresetId,Project,ProjectLayoutState,+ ProjectSettings,ProjectUndoSnapshot,QueueItem,QueueItemStatus,@@ -35,7 +36,6 @@ import type {WidgetStateContract,WorkbenchNotification,WorkbenchNotificationKind,- WorkbenchPreferences,WorkbenchState,} from './types';@@ -103,7 +103,7 @@ type WorkbenchAction =| { type: 'clearNotifications' }| { type: 'clearErrorLog' }| { type: 'recordWidgetFailure'; failure: WidgetFailure }- | { type: 'setPreferences'; preferences: Partial<WorkbenchPreferences> }+ | { type: 'setActiveProjectSettings'; settings: Partial<ProjectSettings> }| { type: 'recordError'; message: string }| { type: 'setBackendConnectionStatus'; status: WorkbenchState['backendConnection']['status']; error?: string }| { type: 'refreshBackendData' }@@ -508,6 +508,7 @@ const ensureProjectWidgetContracts = (project: Project): Project => {return {...project,canvas: cloneCanvas(project.canvas ?? createCanvasState()),+ settings: normalizeProjectSettings(project.settings),widgetRegions: {left: legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel'] ?? defaultWidgetRegions.left,right: ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']),@@ -558,6 +559,7 @@ const createProject = (index: number, id = `project-${index}`): Project => ({name: `Project Name #${index}`,projectGraph: createProjectGraph(index, id),queue: { items: [] },+ settings: normalizeProjectSettings(),undoRedo: { future: [], past: [] },widgetGraphs: {},widgetRegions: createWidgetRegions(),@@ -616,31 +618,12 @@ const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): P},});-const normalizePreferences = (preferences?: Partial<WorkbenchPreferences>): WorkbenchPreferences => {- const themeId = isWorkbenchThemeId(preferences?.themeId) ? preferences.themeId : DEFAULT_THEME_ID;- const reduceMotion =- typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion;- const showFocusRegionHighlight =- typeof preferences?.showFocusRegionHighlight === 'boolean'- ? preferences.showFocusRegionHighlight- : DEFAULT_PREFERENCES.showFocusRegionHighlight;- const confirmImageDeletion =- typeof preferences?.confirmImageDeletion === 'boolean'- ? preferences.confirmImageDeletion- : DEFAULT_PREFERENCES.confirmImageDeletion;-- return { confirmImageDeletion, reduceMotion, showFocusRegionHighlight, themeId };-};-const normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({...state,backendConnection: { status: 'connecting' },- // Persisted snapshots from before preferences existed (or partially written- // ones) are healed by merging in defaults, so hydrate never reads `undefined`.- account: {- ...state.account,- preferences: normalizePreferences(state.account?.preferences),- },+ // Built explicitly: legacy snapshots carried preferences inside the account+ // (they live in the settings store now) and must not resurface here.+ account: { activeLayoutPresetId: state.account?.activeLayoutPresetId ?? defaultLayoutPreset.id },notifications: state.notifications ?? [],projects: state.projects.map(ensureProjectWidgetContracts),});@@ -750,7 +733,12 @@ const compileInvocationSnapshot = (seed: resolveGenerateSeed(values),shouldRandomizeSeed: false,};- const compiledGraph = compileGenerateGraph(resolvedSettings, resolvedSettings.model, route.destination).graph;+ const compiledGraph = compileGenerateGraph(+ resolvedSettings,+ resolvedSettings.model,+ route.destination,+ project.settings+ ).graph;widgetStates.generate = {...widgetStates.generate,@@ -924,18 +912,11 @@ const submitInvocationSnapshot = (};};-export const DEFAULT_PREFERENCES: WorkbenchPreferences = {- confirmImageDeletion: true,- reduceMotion: false,- showFocusRegionHighlight: true,- themeId: DEFAULT_THEME_ID,-};-export const createInitialWorkbenchState = (): WorkbenchState => {const draft = createDraftProject([]);return {- account: { activeLayoutPresetId: 'canvas-default', preferences: { ...DEFAULT_PREFERENCES } },+ account: { activeLayoutPresetId: defaultLayoutPreset.id },activeProjectId: draft.id,autosave: { status: 'idle' },backendConnection: { status: 'connecting' },@@ -1727,16 +1708,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)createNotification({ kind: action.kind, message: action.message, title: action.title }));}- case 'setPreferences': {- const preferences = normalizePreferences({ ...state.account.preferences, ...action.preferences });-- return {- ...state,- account: {- ...state.account,- preferences,- },- };+ case 'setActiveProjectSettings': {+ return updateActiveProject(state, (project) => ({+ ...project,+ settings: normalizeProjectSettings({ ...project.settings, ...action.settings }),+ }));}}};