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
refactor(settings): require resolved widget values wherever layered keys are read (#10312)
Josh Corbett2fdde2412fa4
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex f0c8d3a408..3115d27b52 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -82,6 +82,7 @@ Behavior specs live beside their owning code. Read the owner's document before c- Contracts live with the module owning their invariants. Retired `workbench/types.ts` path is an architecture violation. Workbench aggregate, widget, Canvas, persistence, settings, feature contracts each have an owner-local canonical path.- Persisted schemas and backend DTOs stay private versioned/wire values. They cross seams only through explicit serializers, hydrators, mappers.+- `platform/core/resolvedValues.ts` is a type-only brand: Workbench resolves widget values, but Feature readers such as `getGallerySettings` must require them and cannot import Workbench.- `platform/core/outputImages.ts` is the explicit shared adapter for backend invocation-output image names. Platform owns it because Queue and Nodes both need the projection and cannot import each other's private code. It recognizes only direct image, image-collection, workflow-return output contracts. Never grow it into a recursive walker of arbitrary metadata or input fields.- Imports of another feature's `core/`, `data/`, `ui/`, or runtime implementation fail.- Wildcard exports may aggregate files inside one owner. Never across an ownership seam.diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex cf69cec1af..648bcee08e 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -354,7 +354,8 @@"source:src/workbench/settings/settingsSearchShortcut.ts","source:src/workbench/settings/store.ts","source:src/workbench/shell/useWhatsNew.ts",- "source:src/workbench/shell/whatsNewStore.ts"+ "source:src/workbench/shell/whatsNewStore.ts",+ "source:src/workbench/widgetState.ts"]},"owner": "app",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 9d8671d5a6..ea0e7d348d 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -775,7 +775,8 @@"source:src/workbench/settings/settingsSearchShortcut.ts","source:src/workbench/settings/store.ts","source:src/workbench/shell/useWhatsNew.ts",- "source:src/workbench/shell/whatsNewStore.ts"+ "source:src/workbench/shell/whatsNewStore.ts",+ "source:src/workbench/widgetState.ts"],"editor-minimal-static": ["package:@ark-ui/react",diff --git a/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsxindex f032ed8c0c..aae1fbaef7 100644--- a/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx@@ -5,7 +5,9 @@ import type { DefaultSettingsModel } from '@features/models/ui/detail/defaultSetimport type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';+import { getGallerySettings } from '@features/gallery/contracts';import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { useModelsUi } from '@features/models';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';import { AddModelsView } from '@features/models/ui/add-models/AddModelsView';import { DefaultSettingsSection } from '@features/models/ui/detail/DefaultSettingsSection';@@ -51,7 +53,11 @@ vi.mock('@features/identity', async (importOriginal) => ({}));// The account preferences, kept beyond each mount as the settings store keeps them.-const accountPreferences = createExternalStore({ enableModelDescriptions: true, installInPlace: true });+const accountPreferences = createExternalStore({+ enableModelDescriptions: true,+ installInPlace: true,+ scopedDefaults: {},+});vi.mock('@workbench/settings/store', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),patchWorkbenchPreferences: (next: Record<string, unknown>) => {@@ -131,7 +137,7 @@ describe('Account Models port on the Launchpad', () => {beforeEach(() => {session.canManageModels = true;- accountPreferences.setSnapshot({ enableModelDescriptions: true, installInPlace: true });+ accountPreferences.setSnapshot({ enableModelDescriptions: true, installInPlace: true, scopedDefaults: {} });preferences.patch.mockReset();capabilitiesApi.get.mockReset();capabilitiesApi.get.mockResolvedValue(architectureCapabilitiesFixture);@@ -347,5 +353,20 @@ describe('Account Models port on the Launchpad', () => {await render(<AddModelsView />);expect(inplaceInput()?.checked).toBe(false);});++ it("hands the manager's gallery pickers the user's Gallery defaults", async () => {+ accountPreferences.setSnapshot({+ enableModelDescriptions: true,+ installInPlace: true,+ scopedDefaults: { gallery: { thumbnailFit: 'aspect' } },+ });+ const Probe = () => {+ const { galleryValues } = useModelsUi();+ return galleryValues ? getGallerySettings(galleryValues).thumbnailFit : null;+ };+ await render(<Probe />);++ expect(host.textContent).toBe('aspect');+ });});});diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxindex 2ce2c8ad92..24108b67a8 100644--- a/invokeai/frontend/webv2/src/app/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -55,6 +55,7 @@ import {useWorkbenchPreferenceSelector,} from '@workbench/settings/store';import { loadAppVersion } from '@workbench/shell/whatsNewStore';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';import i18next from 'i18next';import { Fragment, useCallback, useMemo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -128,18 +129,22 @@ const NO_ACTIVE_PROJECT = () => false;export const AccountModelsUiProvider = ({ children }: { children: ReactNode }) => {const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);const installInPlace = useWorkbenchPreferenceSelector((value) => value.installInPlace);+ const galleryValues = useWorkbenchPreferenceSelector((value) =>+ getResolvedProjectWidgetValues(undefined, 'gallery', value.scopedDefaults)+ );const { canManageModels } = useCapabilities();const adapter = useMemo<ModelsUiAdapter>(() => ({canManageModels,enableModelDescriptions,+ galleryValues,installInPlace,isProjectActive: NO_ACTIVE_PROJECT,managerProjectId: null,schedulerPolicy: schedulerPolicySource,setInstallInPlace,}),- [canManageModels, enableModelDescriptions, installInPlace]+ [canManageModels, enableModelDescriptions, galleryValues, installInPlace]);return <ModelsUiProvider adapter={adapter}>{children}</ModelsUiProvider>;diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 752ef781db..8b73b929f5 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -62,6 +62,7 @@ export {} from './core/semanticImageQuery';export {DEFAULT_GALLERY_SETTINGS,+ getGalleryChosenAutoAddBoardId,getGalleryMediaFilter,getGallerySettings,isLegacyFollowAutoAdd,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.test.tsindex 4865670ab7..c213aec98e 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts@@ -1,3 +1,4 @@+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import {@@ -9,7 +10,7 @@ import {describe('board panel sections', () => {it('starts other users’ boards collapsed, even for a panel that saved its collapsed groups before', () => {- const settings = getGallerySettings({ collapsedBoardSections: ['dates'] });+ const settings = getGallerySettings(resolvedValues({ collapsedBoardSections: ['dates'] }));expect(isGalleryBoardSectionOpen(settings, 'other-users')).toBe(false);expect(isGalleryBoardSectionOpen(settings, 'shared')).toBe(true);@@ -17,10 +18,14 @@ describe('board panel sections', () => {});it('records the groups that start collapsed as opened, and the rest as collapsed', () => {- const settings = getGallerySettings({});+ const settings = getGallerySettings(resolvedValues({}));- const opened = getGallerySettings({ ...settings, ...toggleGalleryBoardSection(settings, 'other-users', true) });- const closed = getGallerySettings({ ...opened, ...toggleGalleryBoardSection(opened, 'shared', false) });+ const opened = getGallerySettings(+ resolvedValues({ ...settings, ...toggleGalleryBoardSection(settings, 'other-users', true) })+ );+ const closed = getGallerySettings(+ resolvedValues({ ...opened, ...toggleGalleryBoardSection(opened, 'shared', false) })+ );expect(isGalleryBoardSectionOpen(opened, 'other-users')).toBe(true);expect(isGalleryBoardSectionOpen(closed, 'shared')).toBe(false);@@ -30,22 +35,24 @@ describe('board panel sections', () => {describe('project groups under Other projects', () => {it('starts with every group expanded', () => {- expect(getGallerySettings({}).collapsedProjectGroupIds).toEqual([]);+ expect(getGallerySettings(resolvedValues({})).collapsedProjectGroupIds).toEqual([]);});it('keeps distinct project ids only, dropping anything that is not a string', () => {- const settings = getGallerySettings({ collapsedProjectGroupIds: ['a', 7, null, 'b', 'a', { id: 'c' }] });+ const settings = getGallerySettings(+ resolvedValues({ collapsedProjectGroupIds: ['a', 7, null, 'b', 'a', { id: 'c' }] })+ );expect(settings.collapsedProjectGroupIds).toEqual(['b', 'a']);- expect(getGallerySettings({ collapsedProjectGroupIds: 'a' }).collapsedProjectGroupIds).toEqual([]);+ expect(getGallerySettings(resolvedValues({ collapsedProjectGroupIds: 'a' })).collapsedProjectGroupIds).toEqual([]);});it('remembers at most 200 groups, keeping the most recently collapsed', () => {const ids = Array.from({ length: 205 }, (_, index) => `project-${String(index)}`);- const stored = getGallerySettings({ collapsedProjectGroupIds: ids }).collapsedProjectGroupIds;+ const stored = getGallerySettings(resolvedValues({ collapsedProjectGroupIds: ids })).collapsedProjectGroupIds;const collapsedOneMore = toggleGalleryProjectGroup(- getGallerySettings({ collapsedProjectGroupIds: ids }),+ getGallerySettings(resolvedValues({ collapsedProjectGroupIds: ids })),'new',false);@@ -63,7 +70,7 @@ describe('project groups under Other projects', () => {ids.push('project-7', 'project-49995');const started = performance.now();- const stored = getGallerySettings({ collapsedProjectGroupIds: ids }).collapsedProjectGroupIds;+ const stored = getGallerySettings(resolvedValues({ collapsedProjectGroupIds: ids })).collapsedProjectGroupIds;const elapsedMs = performance.now() - started;expect(stored).toHaveLength(200);@@ -74,7 +81,7 @@ describe('project groups under Other projects', () => {});it('collapses and expands one group without touching the others', () => {- const settings = getGallerySettings({ collapsedProjectGroupIds: ['a'] });+ const settings = getGallerySettings(resolvedValues({ collapsedProjectGroupIds: ['a'] }));expect(toggleGalleryProjectGroup(settings, 'b', false).collapsedProjectGroupIds).toEqual(['a', 'b']);expect(toggleGalleryProjectGroup(settings, 'a', true).collapsedProjectGroupIds).toEqual([]);@@ -83,9 +90,9 @@ describe('project groups under Other projects', () => {describe('search scope', () => {it('searches the selected board unless all boards were chosen', () => {- expect(getGallerySettings({}).searchScope).toBe('board');- expect(getGallerySettings({ searchScope: 'all' }).searchScope).toBe('all');- expect(getGallerySettings({ searchScope: 'everywhere' }).searchScope).toBe('board');- expect(getGallerySettings({ searchScope: null }).searchScope).toBe('board');+ expect(getGallerySettings(resolvedValues({})).searchScope).toBe('board');+ expect(getGallerySettings(resolvedValues({ searchScope: 'all' })).searchScope).toBe('all');+ expect(getGallerySettings(resolvedValues({ searchScope: 'everywhere' })).searchScope).toBe('board');+ expect(getGallerySettings(resolvedValues({ searchScope: null })).searchScope).toBe('board');});});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex a9ce5f649e..73914c5040 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -1,3 +1,5 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';+import type { GalleryItemKind } from './items';import type { GalleryBoardOrderBy, GalleryOrderDir } from './types';@@ -176,15 +178,18 @@ export const toggleGalleryBoardSection = (: { collapsedBoardSections: toggle(settings.collapsedBoardSections, !isOpen) };};-export const getGallerySettings = (values: Record<string, unknown>): GallerySettings => {+/** Not layered, so it reads stored values. */+export const getGalleryChosenAutoAddBoardId = (values: Readonly<Record<string, unknown>>): string | null =>+ typeof values.autoAddBoardId === 'string' && values.autoAddBoardId !== '' && !isLegacyFollowAutoAdd(values)+ ? values.autoAddBoardId+ : DEFAULT_GALLERY_SETTINGS.autoAddBoardId;++export const getGallerySettings = (values: ResolvedValues): GallerySettings => {const paginationMode: GalleryPaginationMode =values.paginationMode === 'paginated' ? 'paginated' : DEFAULT_GALLERY_SETTINGS.paginationMode;return {- autoAddBoardId:- typeof values.autoAddBoardId === 'string' && values.autoAddBoardId !== '' && !isLegacyFollowAutoAdd(values)- ? values.autoAddBoardId- : DEFAULT_GALLERY_SETTINGS.autoAddBoardId,+ autoAddBoardId: getGalleryChosenAutoAddBoardId(values),boardOrderBy: isBoardOrderBy(values.boardOrderBy) ? values.boardOrderBy : DEFAULT_GALLERY_SETTINGS.boardOrderBy,boardOrderDir: isOrderDir(values.boardOrderDir) ? values.boardOrderDir : DEFAULT_GALLERY_SETTINGS.boardOrderDir,boardPanelCollapsed:diff --git a/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.ts b/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.tsindex 66edecb1c0..f7f8d8c589 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.ts@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { QueryClient } from '@tanstack/react-query';import { getGalleryAutoAddBoardId } from '@features/gallery/ui/galleryStateView';@@ -10,7 +11,7 @@ import { canAddToCachedGalleryBoard, ensureGalleryBoardDestinations } from './qu* none is cached; Uncategorized when no board takes it. An auto-add board is never redirected for want of a listing.*/export const resolveGalleryUploadBoardId = async (- galleryValues: Record<string, unknown>,+ galleryValues: ResolvedValues,client: QueryClient): Promise<string> => {await ensureGalleryBoardDestinations(client);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsxindex b4de676cb3..284e0fc689 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx@@ -12,6 +12,7 @@ import { toGalleryItemKey, toGalleryItemRef } from '@features/gallery/core/itemsimport { getGalleryDeletionSuccessor } from '@features/gallery/core/selection';import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';@@ -170,7 +171,7 @@ const createGallery = (items: GalleryItem[], selected: GalleryItem | null): GallsemanticImageQuery: null,semanticSearchText: null,// The harness shows three columns.- settings: getGallerySettings({ paginationMode: 'paginated' }),+ settings: getGallerySettings(resolvedValues({ paginationMode: 'paginated' })),starredOnly: false,});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex f217a5f540..fabf33c29a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -30,6 +30,7 @@ import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/reacimport { isGalleryImageDragData } from '@features/gallery/utility';import { getAutoSwitchFollowedLive } from '@features/queue/contracts';import { dragWithMouse } from '@platform/browser/mouseDrag.testing';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { parseDateTokens } from '@platform/search/dateTokens';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -312,7 +313,7 @@ const getStableFilter = (gallery: GalleryStateView): GalleryItemsFilter => {return stableFilters.get(identity)!;};-const DENSE_SETTINGS = { ...getGallerySettings({}), imageDensityPercent: 0 };+const DENSE_SETTINGS = { ...getGallerySettings(resolvedValues({})), imageDensityPercent: 0 };const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateView => {const items = overrides.items ?? [@@ -343,7 +344,7 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVselectionStarredOnly: false,semanticImageQuery: null,semanticSearchText: null,- settings: { ...getGallerySettings({ paginationMode: 'paginated' }), imageDensityPercent: 0 },+ settings: { ...getGallerySettings(resolvedValues({ paginationMode: 'paginated' })), imageDensityPercent: 0 },starredOnly: false,...overrides,};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex a9ad71cdaa..d1df1fc27a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -7,6 +7,7 @@ import type { GalleryUiAdapter } from '@features/gallery/react';import { ChakraProvider } from '@chakra-ui/react';import { GalleryUiProvider } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, useMemo, useState, type ReactNode } from 'react';@@ -70,7 +71,7 @@ const adapter: GalleryUiAdapter = {toggleItemSelection: noop,updateSettings: noop,},- galleryValues: {},+ galleryValues: resolvedValues(),generateValues: {},getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsxindex 4290a81e37..8051cf18d6 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx@@ -6,6 +6,7 @@ import type { QueueProgressSession } from '@features/queue/contracts';import { Box, ChakraProvider } from '@chakra-ui/react';import { DndContext } from '@dnd-kit/core';import { GalleryItemActionsProvider, GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';@@ -170,7 +171,7 @@ const Harness = ({toggleItemSelection: noop,updateSettings: (settings: Record<string, unknown>) => patch(settings),},- galleryValues,+ galleryValues: resolvedValues(galleryValues),generateValues: {},getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex d32368a0d0..6bd4d09418 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -9,6 +9,7 @@ import type {GalleryView,} from '@features/gallery/core/types';import type { QueueProgressSession } from '@features/queue/contracts';+import type { ResolvedValues } from '@platform/core/resolvedValues';import { asSingleAccountBoards } from '@features/gallery/core/boardAccess';import { createKeyedTransientStore, type KeyedTransientStore } from '@platform/state/externalStore';@@ -119,12 +120,12 @@ export interface GalleryUiAdapter {/** The server has more than one account. */boardSharing?: boolean;gallery: GalleryCommandsPort;- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;generateValues: Record<string, unknown>;/** The host narrows the server's check with its projects' own scans; rejects when the check cannot run. */getBoardMediaUsage(boardId: string, signal: AbortSignal): Promise<GalleryMediaUsageReport>;/** Null once the project is closed. */- getProjectGalleryValues?(projectId: string): Record<string, unknown> | null;+ getProjectGalleryValues?(projectId: string): ResolvedValues | null;/** The host may explain where new results still go. */noteBoardBrowsed?(boardId: string): void;getItemLabel(item: GalleryItemRef): Promise<string | null>;@@ -225,7 +226,7 @@ export const useHostGalleryBoards = (boards: readonly GalleryBoard[] | undefined/** A host without a workbench (the Launchpad) supplies one with GalleryHostProvider. */export interface GalleryHost {- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;notifications: GalleryNotificationsPort;projectId?: string;projectName: string;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetHeaderActions.browser.test.tsxindex 0f21875461..553579a41c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetHeaderActions.browser.test.tsx@@ -6,6 +6,7 @@ import { ChakraProvider } from '@chakra-ui/react';import { DEFAULT_GALLERY_SETTINGS, getGallerySettings } from '@features/gallery/core/settings';import { galleryBoardsOptions } from '@features/gallery/data/queries';import { GalleryUiProvider } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';@@ -60,7 +61,7 @@ let queryClient: QueryClient;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const render = async (values: Record<string, unknown>) => {- const settings = getGallerySettings(values);+ const settings = getGallerySettings(resolvedValues(values));queryClient.setQueryData(galleryBoardsOptions({includeArchived: settings.showArchivedBoards,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsxindex 8962cf6e37..4713b5bfa4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.browser.test.tsx@@ -2,6 +2,7 @@ import type { GalleryImageItem } from '@features/gallery/core/items';import { ChakraProvider } from '@chakra-ui/react';import { requestGalleryItemReveal } from '@features/gallery/core/selection';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, type ComponentProps } from 'react';@@ -127,7 +128,7 @@ const adapter: GalleryUiAdapter = {toggleItemSelection: noop,updateSettings: noop,},- galleryValues: { galleryPage: 0, selectedBoardId: 'none' },+ galleryValues: resolvedValues({ galleryPage: 0, selectedBoardId: 'none' }),generateValues: {},getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex c826b3c1ca..ef08b8fbf9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -1,6 +1,7 @@import type { GalleryImageItem, GalleryItem, GalleryVideoItem } from '@features/gallery/core/items';import type { GalleryBoard, GeneratedImageContract } from '@features/gallery/core/types';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import {@@ -80,7 +81,7 @@ describe('gallery state view', () => {const values = { selectedBoardId: 'board-1' };expect(getGallerySelectedBoardId(values, [])).toBe('board-1');- expect(getGalleryStateView(values, [], null).selectedBoardId).toBe('board-1');+ expect(getGalleryStateView(resolvedValues(values), [], null).selectedBoardId).toBe('board-1');});/** Missing imported destinations fall back to the project's board instead of scattering output into Uncategorized. */@@ -92,7 +93,7 @@ describe('gallery state view', () => {const values = { projectBoardId: 'project-board', selectedBoardId: 'missing-board' };expect(getGallerySelectedBoardId(values, projectBoards)).toBe('project-board');- expect(getGalleryStateView(values, projectBoards, []).selectedBoardId).toBe('project-board');+ expect(getGalleryStateView(resolvedValues(values), projectBoards, []).selectedBoardId).toBe('project-board');});it('never substitutes unfiltered recents for a listing the current scope does not have', () => {@@ -103,7 +104,7 @@ describe('gallery state view', () => {selectedBoardId: 'board-1',selectedImageName: 'image:elsewhere.png',};- const gallery = getGalleryStateView(values, boards, null);+ const gallery = getGalleryStateView(resolvedValues(values), boards, null);expect(gallery.items).toEqual([]);expect(gallery.selectedItemKey).toBeNull();@@ -111,7 +112,7 @@ describe('gallery state view', () => {it('parses persisted gallery settings with safe defaults', () => {const gallery = getGalleryStateView(- { boardOrderBy: 'board_name', mediaFilter: 'audio', starredSectionCollapsed: 'yes' },+ resolvedValues({ boardOrderBy: 'board_name', mediaFilter: 'audio', starredSectionCollapsed: 'yes' }),boards,[]);@@ -142,10 +143,13 @@ describe('gallery state view', () => {starredSectionCollapsed: false,thumbnailFit: 'square',});- expect(getGalleryStateView({ starredSectionCollapsed: true }, boards, []).settings.starredSectionCollapsed).toBe(- true+ expect(+ getGalleryStateView(resolvedValues({ starredSectionCollapsed: true }), boards, []).settings+ .starredSectionCollapsed+ ).toBe(true);+ expect(getGalleryStateView(resolvedValues({ mediaFilter: 'video' }), boards, []).settings.mediaFilter).toBe(+ 'video');- expect(getGalleryStateView({ mediaFilter: 'video' }, boards, []).settings.mediaFilter).toBe('video');});it('exposes the selection page only when its stamp names the listing the grid shows', () => {@@ -165,13 +169,13 @@ describe('gallery state view', () => {};const pageOf = (values: Record<string, unknown>, stamp: Record<string, unknown> = {}) =>getGalleryStateView(- { ...stamped, ...values, selectedImageQuery: { ...stamped.selectedImageQuery, ...stamp } },+ resolvedValues({ ...stamped, ...values, selectedImageQuery: { ...stamped.selectedImageQuery, ...stamp } }),boards,[]).revealTargetPage;expect(pageOf({})).toBe(2);- expect(getGalleryStateView(stamped, boards, []).page).toBe(0);+ expect(getGalleryStateView(resolvedValues(stamped), boards, []).page).toBe(0);expect(pageOf({ selectedBoardId: 'board-1' })).toBeNull();expect(pageOf({ paginationMode: 'infinite' })).toBeNull();expect(pageOf({}, { galleryView: 'assets' })).toBeNull();@@ -201,7 +205,7 @@ describe('gallery state view', () => {it('qualifies legacy names and preserves ordered mixed-media selection keys', () => {const gallery = getGalleryStateView(- { selectedImageNames: ['a.png', 'video:shared', 'image:shared', 7] },+ resolvedValues({ selectedImageNames: ['a.png', 'video:shared', 'image:shared', 7] }),boards,[]) as ReturnType<typeof getGalleryStateView> & { selectedItemKeys?: string[] };@@ -209,7 +213,9 @@ describe('gallery state view', () => {expect(gallery.selectedItemKeys).toEqual(['image:a.png', 'video:shared', 'image:shared']);expect((- getGalleryStateView({ selectedImageName: 'a.png' }, boards, []) as ReturnType<typeof getGalleryStateView> & {+ getGalleryStateView(resolvedValues({ selectedImageName: 'a.png' }), boards, []) as ReturnType<+ typeof getGalleryStateView+ > & {selectedItemKeys?: string[];}).selectedItemKeys@@ -220,12 +226,12 @@ describe('gallery state view', () => {const image = createImageItem('shared');const video = createVideoItem('shared');const gallery = getGalleryStateView(- {+ resolvedValues({compareImage: image,selectedImage: video,selectedImageName: 'video:shared',selectedImageNames: ['image:shared', 'video:shared'],- },+ }),boards,[image, video]) as ReturnType<typeof getGalleryStateView> & {@@ -294,18 +300,18 @@ describe('getGalleryAutoAddBoardId', () => {const anyBoard = () => true;it('sends results to the project inbox by default, wherever the gallery browses', () => {- expect(getGalleryAutoAddBoardId({ projectBoardId: 'project', selectedBoardId: 'picked' }, anyBoard)).toBe(- 'project'- );+ expect(+ getGalleryAutoAddBoardId(resolvedValues({ projectBoardId: 'project', selectedBoardId: 'picked' }), anyBoard)+ ).toBe('project');// What earlier builds stored for following the selected board, their default, reads as the default now.expect(getGalleryAutoAddBoardId(- { autoAddBoardId: 'follow', projectBoardId: 'project', selectedBoardId: 'picked' },+ resolvedValues({ autoAddBoardId: 'follow', projectBoardId: 'project', selectedBoardId: 'picked' }),anyBoard)).toBe('project');// A gallery with no inbox, such as a Library-only one, falls back to Uncategorized.- expect(getGalleryAutoAddBoardId({ selectedBoardId: 'picked' }, anyBoard)).toBe('none');+ expect(getGalleryAutoAddBoardId(resolvedValues({ selectedBoardId: 'picked' }), anyBoard)).toBe('none');});it('sends results a view-only board refuses to the project inbox, followed or fixed', () => {@@ -313,14 +319,18 @@ describe('getGalleryAutoAddBoardId', () => {expect(getGalleryAutoAddBoardId(- { followSelectedBoard: true, projectBoardId: 'inbox', selectedBoardId: 'shared' },+ resolvedValues({ followSelectedBoard: true, projectBoardId: 'inbox', selectedBoardId: 'shared' }),viewOnly)).toBe('inbox');- expect(getGalleryAutoAddBoardId({ autoAddBoardId: 'shared', projectBoardId: 'inbox' }, viewOnly)).toBe('inbox');- expect(getGalleryAutoAddBoardId({ autoAddBoardId: 'shared' }, viewOnly)).toBe('none');+ expect(+ getGalleryAutoAddBoardId(resolvedValues({ autoAddBoardId: 'shared', projectBoardId: 'inbox' }), viewOnly)+ ).toBe('inbox');+ expect(getGalleryAutoAddBoardId(resolvedValues({ autoAddBoardId: 'shared' }), viewOnly)).toBe('none');// Uncategorized is always the caller's own.- expect(getGalleryAutoAddBoardId({ autoAddBoardId: 'none', projectBoardId: 'inbox' }, () => false)).toBe('none');+ expect(+ getGalleryAutoAddBoardId(resolvedValues({ autoAddBoardId: 'none', projectBoardId: 'inbox' }), () => false)+ ).toBe('none');});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex b0d9c7c491..4ce84c90d7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -1,4 +1,5 @@import type { GalleryBoard, GalleryImage, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { IconRadioMenuProps } from '@platform/ui/Menu';import type { TFunction } from 'i18next';@@ -197,7 +198,7 @@ export const settleGalleryValues = (};export const getGallerySearchScope = (values: Record<string, unknown>): GallerySearchScope =>- getGallerySettings(values).searchScope === 'all' && isGallerySearchActive(values) ? 'all' : 'board';+ values.searchScope === 'all' && isGallerySearchActive(values) ? 'all' : 'board';export const getGalleryRawSelectedBoardId = (values: Record<string, unknown>): string | null =>typeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;@@ -222,7 +223,7 @@ export const getGalleryDefaultDestinationBoardId = (values: Record<string, unkno/** The selected board only while `followSelectedBoard` is on; a board `canAddTo` refuses sends results to the inbox. */export const getGalleryAutoAddBoardId = (- values: Record<string, unknown>,+ values: ResolvedValues,canAddTo: (boardId: string) => boolean): string | null => {const { autoAddBoardId, followSelectedBoard } = getGallerySettings(values);@@ -302,7 +303,7 @@ export interface GallerySelectedImageQuery {starredOnly: boolean;}-export const getGallerySelectedImageQuery = (values: Record<string, unknown>): GallerySelectedImageQuery => {+export const getGallerySelectedImageQuery = (values: ResolvedValues): GallerySelectedImageQuery => {const query =values.selectedImageQuery && typeof values.selectedImageQuery === 'object'? (values.selectedImageQuery as Partial<GallerySelectedImageQuery>)@@ -362,7 +363,7 @@ export const getGalleryCompareImage = (values: Record<string, unknown>): GalleryselectedImageName: null,});-export const getGalleryAnchoredWindowPage = (values: Record<string, unknown>): number => {+export const getGalleryAnchoredWindowPage = (values: ResolvedValues): number => {const page = getGalleryPage(values);return getGallerySettings(values).paginationMode === 'infinite' && page > 0 ? page : 0;@@ -424,7 +425,7 @@ export const getGalleryListing = (};export const getGalleryStateView = (- values: Record<string, unknown>,+ values: ResolvedValues,backendBoards: GalleryBoard[],backendItems: GalleryItem[] | null,starredStripItems: readonly GalleryItem[] = []diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsxindex 66f02d1889..af36c6c163 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx@@ -8,6 +8,7 @@ import { ChakraProvider } from '@chakra-ui/react';import { legacyGeneratedImageToGalleryItem } from '@features/gallery/core/items';import { GalleryUiProvider } from '@features/gallery/react';import { GalleryHostProvider } from '@features/gallery/ui/GalleryUiContext';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, useCallback, useState } from 'react';@@ -163,7 +164,7 @@ const MultiAddHost = ({ initialSelection }: { initialSelection: GalleryPickerSelconst OPEN_DIALOG = '[role="dialog"][data-state="open"]';/** A host without a workbench (the Launchpad): no Gallery widget scope to seed from or reveal. */-const launchpadHost: GalleryHost = { galleryValues: {}, notifications, projectName: '' };+const launchpadHost: GalleryHost = { galleryValues: resolvedValues(), notifications, projectName: '' };const renderPicker = async (picker?: React.ReactElement, { withoutWorkbench = false } = {}) => {const content = picker ?? (diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 74f62f268e..bf9cf09e75 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -3,6 +3,7 @@ import type { GalleryUiAdapter } from '@features/gallery/react';import { getGallerySettings } from '@features/gallery/core/settings';import { GalleryUiProvider } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -116,7 +117,7 @@ const Probe = ({ref: Ref<GalleryActions>;selectedBoardId: string;}) => {- const { autoAddBoardId } = getGallerySettings(galleryValues);+ const { autoAddBoardId } = getGallerySettings(resolvedValues(galleryValues));const currentGalleryLocationRef = useRef({ autoAddBoardId, galleryView, selectedBoardId });// Match GalleryWidgetView's render-assigned live-read port.@@ -204,10 +205,13 @@ const adapter: GalleryUiAdapter = {toggleItemSelection: noop,updateSettings,},- galleryValues: {},+ galleryValues: resolvedValues(),generateValues: {},getItemLabel: () => Promise.resolve(null),- getProjectGalleryValues: (projectId: string) => mocks.projectGalleryValues(projectId),+ getProjectGalleryValues: (projectId: string) => {+ const values = mocks.projectGalleryValues(projectId);+ return values && resolvedValues(values);+ },liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,@@ -250,7 +254,7 @@ const renderProbe = async () => {await act(() => {root?.render(<QueryClientProvider client={new QueryClient()}>- <GalleryUiProvider adapter={{ ...adapter, galleryValues }}>+ <GalleryUiProvider adapter={{ ...adapter, galleryValues: resolvedValues(galleryValues) }}><Probe galleryView={galleryView} ref={actionsRef} selectedBoardId={selectedBoardId} /></GalleryUiProvider></QueryClientProvider>@@ -502,7 +506,9 @@ describe('optimistic board updates', () => {await act(() => {root?.render(<QueryClientProvider client={new QueryClient()}>- <GalleryUiProvider adapter={{ ...adapter, galleryValues, projectId: 'project-2' }}>+ <GalleryUiProvider+ adapter={{ ...adapter, galleryValues: resolvedValues(galleryValues), projectId: 'project-2' }}+ ><Probe galleryView={galleryView} ref={actionsRef} selectedBoardId="none" /></GalleryUiProvider></QueryClientProvider>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsxindex 3462a9c0b3..0c956585e1 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx@@ -9,6 +9,7 @@ import {invalidateGallery,patchGalleryItemCaches,} from '@features/gallery/data/queryCache';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { act, useEffect } from 'react';@@ -30,8 +31,8 @@ vi.mock('@features/gallery/data/backend', async (importOriginal) => ({}));const TOTAL = 12_000;-const settings = getGallerySettings({ paginationMode: 'infinite' });-const paginatedSettings = getGallerySettings({ paginationMode: 'paginated' });+const settings = getGallerySettings(resolvedValues({ paginationMode: 'infinite' }));+const paginatedSettings = getGallerySettings(resolvedValues({ paginationMode: 'paginated' }));let latestData: GalleryData | null = null;const readRequests = () =>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 799f324bb1..1eda4f374e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -1,6 +1,7 @@import type { GalleryUiAdapter } from '@features/gallery/react';import { GalleryUiProvider } from '@features/gallery/react';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -98,7 +99,7 @@ const adapter: GalleryUiAdapter = {toggleItemSelection: noop,updateSettings: noop,},- galleryValues: {},+ galleryValues: resolvedValues(),generateValues: {},getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsxindex b5f09cb72e..baa8e33f32 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx@@ -1,5 +1,6 @@import type { ModelConfig } from '@features/models/core/types';import type { CalibrationGraphCompiler } from '@features/models/core/workingMemory';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { ReactNode } from 'react';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';@@ -56,6 +57,8 @@ export interface ModelsUiAdapter {/** Whether this session may open the Model Manager; its route redirects everyone else away. */canManageModels: boolean;enableModelDescriptions: boolean;+ /** The user's Gallery defaults, for the manager's pickers. */+ galleryValues?: ResolvedValues;/** Add Models' "Install in place" choice, an account preference. */installInPlace: boolean;isProjectActive: (projectId: string) => boolean;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsxindex 2dc43197db..8cd435ceb5 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelImageUpload.tsx@@ -2,12 +2,14 @@import type { GalleryItem } from '@features/gallery';import type { GalleryHost, GalleryPickerAccept } from '@features/gallery/picker';import type { ModelConfig } from '@features/models/core/types';+import type { ResolvedValues } from '@platform/core/resolvedValues';import { Box, Image } from '@chakra-ui/react';import { GalleryMediaSlot } from '@features/gallery/mediaSlot';import { GalleryHostProvider } from '@features/gallery/picker';import { deleteModelImage, getModelImageUrl, updateModelImage } from '@features/models/data/api';import { markCoverImageChanged, useModelsSelector } from '@features/models/data/modelsStore';+import { useModelsUi } from '@features/models/ui/ModelsUiContext';import { useNotify } from '@features/models/ui/useModelsNotify';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';@@ -17,8 +19,7 @@ import { useTranslation } from 'react-i18next';const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);const IMAGE_ONLY: GalleryPickerAccept = ['image'];-/** The model manager lives on the Launchpad: no project board to seed from and no Gallery widget to reveal. */-const NO_GALLERY_VALUES: Record<string, unknown> = {};+const NO_GALLERY_DEFAULTS = {} as ResolvedValues;interface ModelImageUploadProps {model: Pick<ModelConfig, 'cover_image' | 'key' | 'name'>;@@ -38,16 +39,17 @@ const ModelImageUploadForModel = ({ model, onError, onUpdated }: ModelImageUploa// Setting and removing share one busy flag: the slot hosts one action at a time.const { isBusy, run } = useScopedAction();const notify = useNotify();+ const { galleryValues } = useModelsUi();const galleryHost = useMemo<GalleryHost>(() => ({- galleryValues: NO_GALLERY_VALUES,+ galleryValues: galleryValues ?? NO_GALLERY_DEFAULTS,notifications: {add: ({ kind, message, title }) => notify[kind](title, message),reportError: ({ message }) => notify.error(message),},projectName: '',}),- [notify]+ [galleryValues, notify]);const value = useMemo(() => (hasImage ? { kind: 'image' as const, name: t('models.modelCoverAlt', { name: model.name }) } : null),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex 7793aaff22..7ce058cac5 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -2,6 +2,7 @@ import type { GalleryItemRef } from '@features/gallery/contracts';import type { ProjectGraphState, ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';import type { WorkflowLibrarySort, WorkflowLibrarySortDirection } from '@features/workflow/data/libraryBrowseStore';import type { WorkflowLibraryCardSize } from '@features/workflow/ui/library/workflowThumbnail';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { WorkbenchThemeId } from '@theme/themes';import type { ComponentType, ReactNode } from 'react';@@ -47,7 +48,7 @@ export interface WorkflowProjectPersistence {}export interface WorkflowProjectSnapshot {- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;id: string;isWorkflowRunning: boolean;/** The active workflow's editable document. */diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsxindex 73b05e67de..9eea327a98 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx@@ -10,6 +10,7 @@ import { WorkflowUiProvider, WorkflowGraphPreviewProvider } from '@features/workimport { setWorkflowLibraryTab } from '@features/workflow/ui/workflowUiStore';import { createProjectGraph } from '@features/workflow/utility';import { settleAnimations } from '@platform/browser/settleAnimations.testing';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -187,7 +188,11 @@ const adapter = {notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },openAddModels: vi.fn(),} as unknown as WorkflowUiAdapter;-const galleryHost = { galleryValues: {}, notifications: { add: vi.fn(), reportError: vi.fn() }, projectName: '' };+const galleryHost = {+ galleryValues: resolvedValues(),+ notifications: { add: vi.fn(), reportError: vi.fn() },+ projectName: '',+};const previewAdapter = {openDocumentInNewProject: vi.fn(),focusSource: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsxindex 67d5d95024..dc893f564c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx@@ -10,6 +10,7 @@ import { ChakraProvider } from '@chakra-ui/react';import { GalleryHostProvider } from '@features/gallery/picker';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utility';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act, StrictMode, type ComponentProps, type ReactNode } from 'react';@@ -99,7 +100,7 @@ vi.mock('@features/workflow/queries', async (importOriginal) => ({}));const GALLERY_HOST: GalleryHost = {- galleryValues: {},+ galleryValues: resolvedValues(),notifications: { add: vi.fn(), reportError: vi.fn() },projectName: '',};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsxindex 60997d9a12..8785ee1cb3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -41,6 +41,7 @@ import {} from '@features/workflow/utility';import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';import { settleAnimations } from '@platform/browser/settleAnimations.testing';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';@@ -60,7 +61,7 @@ const selectMenuItem = async (item: HTMLElement | null | undefined) => {};const GALLERY_HOST: GalleryHost = {- galleryValues: {},+ galleryValues: resolvedValues(),notifications: { add: vi.fn(), reportError: vi.fn() },projectName: '',};diff --git a/invokeai/frontend/webv2/src/platform/core/resolvedValues.testing.ts b/invokeai/frontend/webv2/src/platform/core/resolvedValues.testing.tsnew file mode 100644index 0000000000..c4455ebdb6--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/core/resolvedValues.testing.ts@@ -0,0 +1,3 @@+import type { ResolvedValues } from './resolvedValues';++export const resolvedValues = (values: Record<string, unknown> = {}): ResolvedValues => values as ResolvedValues;diff --git a/invokeai/frontend/webv2/src/platform/core/resolvedValues.ts b/invokeai/frontend/webv2/src/platform/core/resolvedValues.tsnew file mode 100644index 0000000000..288da259a4--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/core/resolvedValues.ts@@ -0,0 +1,4 @@+declare const resolvedValuesBrand: unique symbol;++/** Widget values with the user's defaults applied, so readers of layered keys cannot be handed stored pins. */+export type ResolvedValues = Readonly<Record<string, unknown>> & { readonly [resolvedValuesBrand]: true };diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex a5d0afb2f0..53c884c7dd 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { ProjectLayoutState } from '@workbench/layoutContracts';import type { Project } from '@workbench/projectContracts';import type { EffectiveProjectSettings } from '@workbench/settings/contracts';@@ -309,7 +310,7 @@ export const useActiveProjectSettingsSelector = <Selected,>(/** A widget's values as it reads them: the active project's pins over the user's defaults for the widget's type. */export const useWidgetValuesSelector = <Selected,>(widgetId: WidgetTypeId,- selector: (values: Record<string, unknown>) => Selected,+ selector: (values: ResolvedValues) => Selected,isEqual?: EqualityFn<Selected>): Selected =>useWorkbenchSelector(@@ -319,7 +320,7 @@ export const useWidgetValuesSelector = <Selected,>(export const useWidgetInstanceValuesSelector = <Selected,>(instanceId: WidgetInstanceId,- selector: (values: Record<string, unknown>) => Selected,+ selector: (values: ResolvedValues) => Selected,isEqual?: EqualityFn<Selected>): Selected =>useWorkbenchSelector(@@ -331,7 +332,7 @@ export const useWidgetInstanceValuesSelector = <Selected,>(export const useProjectWidgetInstanceValuesSelector = <Selected,>(projectId: string,instanceId: WidgetInstanceId,- selector: (values: Record<string, unknown>) => Selected,+ selector: (values: ResolvedValues) => Selected,isEqual?: EqualityFn<Selected>): Selected =>useWorkbenchSelector((snapshot) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.tsindex bf89402303..7e6884a4fa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts@@ -348,6 +348,23 @@ describe('saveCanvasToGallery', () => {});});+ it('records the compositing the user default resolves to when the project pins none', async () => {+ const harness = createHarness();++ await saveCanvasToGallery({+ engine: harness.engine,+ getProject: harness.getProject,+ project: harness.project,+ region: 'canvas',+ scopedDefaults: { canvas: { outputOnlyMaskedRegions: false } },+ uploadImage: harness.uploadImage,+ });++ expect(harness.uploadImage.mock.calls[0]?.[1]?.metadata).toMatchObject({+ canvas_v3_metadata: { settings: { compositing: { outputOnlyMaskedRegions: false } } },+ });+ });+it.each(['closed-project', 'mismatched-document', 'expired-account'] as const)('does not upload a %s after pending paint uploads finish',async (reason) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.tsindex ccd55f7e31..7935ef63f4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts@@ -1,5 +1,6 @@import type { ControlLayerGraphInput } from '@features/generation/graph';import type { ModelConfig } from '@features/models';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type {AdjustmentRefusal,CanvasDocumentContractV3,@@ -126,7 +127,7 @@ const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, u};};-const toCanvasSaveBoardId = (galleryValues: Record<string, unknown>): string | undefined => {+const toCanvasSaveBoardId = (galleryValues: ResolvedValues): string | undefined => {const boardId = getGalleryAutoAddBoardId(galleryValues, canAddToCachedGalleryBoard);return boardId !== null && boardId !== 'none' ? boardId : undefined;@@ -161,7 +162,7 @@ export const saveCanvasToGallery = async (options: {/** The originating project's current immutable state, read after export to pair metadata with its document. */getProject: (projectId: string) => Project | null;project: Project;- /** The user's defaults captured with `project`: the destination follows the Gallery's resolved settings. */+ /** The user's defaults captured with `project`. */scopedDefaults: ScopedDefaults;uploadImage?: typeof uploadCanvasImage;}): Promise<SaveCanvasToGalleryResult> => {@@ -181,7 +182,7 @@ export const saveCanvasToGallery = async (options: {if (!capturedProject || capturedProject.canvas.document !== exported.document) {return { status: 'stale' };}- const canvasValues = getProjectWidgetValues(capturedProject, 'canvas');+ const canvasValues = getResolvedProjectWidgetValues(capturedProject, 'canvas', scopedDefaults);const metadata = {...buildCanvasSaveMetadata(capturedProject, exported.rect),canvas_v3_metadata: recordCanvasMetadata(exported.document, {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.tsindex 03a32652a4..2fde33bca3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts@@ -1,5 +1,6 @@import type { GalleryImage } from '@features/gallery';import type { GenerateModelConfig, ComponentModelConfig } from '@features/generation/contracts';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { CanvasDocumentContractV3, CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';import type { Project } from '@workbench/projectContracts';import type { WorkbenchCommands } from '@workbench/workbenchStore';@@ -75,7 +76,8 @@ const readCanvasSettings = (metadata: Record<string, unknown>): Record<string, uconst settings = record && isRecord(record.settings) ? record.settings : null;if (settings && isRecord(settings.compositing)) {const raw = settings.compositing;- const normalized = readCanvasCompositingSettings(raw);+ // Resolved when recorded.+ const normalized = readCanvasCompositingSettings(raw as ResolvedValues);for (const key of Object.values(CANVAS_COMPOSITING_KEYS)) {const value = raw[key],canonical = normalized[key];diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 28da08202f..ecb841be5a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -316,7 +316,7 @@ export const useImageActions = ({const getLatestWidgetValues = (widgetId: 'gallery' | 'generate' | 'video') => {const project = getLatestProject();- return project ? getResolvedProjectWidgetValues(project, widgetId, queries.getSnapshot().scopedDefaults) : {};+ return getResolvedProjectWidgetValues(project, widgetId, queries.getSnapshot().scopedDefaults);};const getLatestGenerateValues = () => getLatestWidgetValues('generate');const getLatestVideoValues = () => getLatestWidgetValues('video');diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.tsindex 62cb7f66e2..6fd522c4b7 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts@@ -1,34 +1,35 @@+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import { getImageMapClusterEps, MAX_CLUSTER_EPS, MIN_CLUSTER_EPS } from './imageMapSettings';describe('getImageMapClusterEps', () => {it('reads a chosen strength', () => {- expect(getImageMapClusterEps({ clusterEps: 0.25 })).toBe(0.25);+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: 0.25 }))).toBe(0.25);});it('means "derive it" when unset', () => {// The default, and the state the control returns to when cleared.- expect(getImageMapClusterEps({})).toBeNull();- expect(getImageMapClusterEps({ clusterEps: null })).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({}))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: null }))).toBeNull();});it('rejects stored values the endpoint would refuse', () => {// Persisted widget values survive upgrades and hand-edited project files, so a bad one must fall back to the// heuristic rather than 422 every points request and leave the map permanently empty.- expect(getImageMapClusterEps({ clusterEps: 0 })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: -1 })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: Number.NaN })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: Infinity })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: '0.2' })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: MIN_CLUSTER_EPS / 2 })).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: 0 }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: -1 }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: Number.NaN }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: Infinity }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: '0.2' }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: MIN_CLUSTER_EPS / 2 }))).toBeNull();// And the high side: the endpoint caps eps at 2.0, so a larger stored value 422s every refresh and strands the map.- expect(getImageMapClusterEps({ clusterEps: MAX_CLUSTER_EPS + 1 })).toBeNull();- expect(getImageMapClusterEps({ clusterEps: 1000 })).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: MAX_CLUSTER_EPS + 1 }))).toBeNull();+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: 1000 }))).toBeNull();});it('keeps the bounds the control and the endpoint agree on', () => {- expect(getImageMapClusterEps({ clusterEps: MIN_CLUSTER_EPS })).toBe(MIN_CLUSTER_EPS);- expect(getImageMapClusterEps({ clusterEps: MAX_CLUSTER_EPS })).toBe(MAX_CLUSTER_EPS);+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: MIN_CLUSTER_EPS }))).toBe(MIN_CLUSTER_EPS);+ expect(getImageMapClusterEps(resolvedValues({ clusterEps: MAX_CLUSTER_EPS }))).toBe(MAX_CLUSTER_EPS);});});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.tsindex f319ad1da5..aef493ed4f 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts@@ -1,9 +1,9 @@-export const getImageMapClickSelectsCluster = (values: Record<string, unknown>): boolean =>- values.clickSelectsCluster === true;+import type { ResolvedValues } from '@platform/core/resolvedValues';++export const getImageMapClickSelectsCluster = (values: ResolvedValues): boolean => values.clickSelectsCluster === true;/** Labels are drawn unless the user has turned them off. */-export const getImageMapShowClusterLabels = (values: Record<string, unknown>): boolean =>- values.showClusterLabels !== false;+export const getImageMapShowClusterLabels = (values: ResolvedValues): boolean => values.showClusterLabels !== false;/** Lowest eps the backend will cluster with; below it the server floors the value anyway. */export const MIN_CLUSTER_EPS = 0.01;@@ -11,7 +11,7 @@ export const MIN_CLUSTER_EPS = 0.01;export const MAX_CLUSTER_EPS = 2;/** The user's DBSCAN eps, or null (the default, and the way back) while the server's adaptive heuristic chooses. */-export const getImageMapClusterEps = (values: Record<string, unknown>): number | null => {+export const getImageMapClusterEps = (values: ResolvedValues): number | null => {const raw = values.clusterEps;// Bounded at BOTH ends by the endpoint's range. A persisted value outside it (an imported project, a hand-editeddiff --git a/invokeai/frontend/webv2/src/workbench/settings/README.md b/invokeai/frontend/webv2/src/workbench/settings/README.mdindex 5c3c895154..be102cc046 100644--- a/invokeai/frontend/webv2/src/workbench/settings/README.md+++ b/invokeai/frontend/webv2/src/workbench/settings/README.md@@ -10,7 +10,7 @@ Each field declares a scope: `preference` (account, or install when nobody is siAccount preferences (`WorkbenchPreferences`), the saved lists among them (aspect ratios, Generate presets, rebalance presets), are stored as one blob: each write sends the whole of it, and the last writer wins. An older build, or a tab still holding an older snapshot, drops the keys it does not know, or the list as it last read it, on its next preference write.-A `project` field resolves as the project's pin, then the user's default, then the owner's built-in. Pins are the keys present in the widget instance's `state.values`, or the optional generation flags in `ProjectSettings`; persistence keeps them raw. The generation flags (CPU noise, NSFW checker, watermark) are the Generate widget's settings, behind its cog, but they are project settings: every generation in the project reads them, and they pin on the project whichever widgets it has. Defaults live in `WorkbenchPreferences.scopedDefaults`, keyed by widget type id (`gallery`, `canvas`, `preview`, `image-map`, and `generate`, whose record layers over `ProjectSettings`, never over the Generate widget's values), each holding only keys the user chose (a default equal to the built-in is removed). `getLayeredSettings` in `projectSettings.ts` is the one list of layerable keys: resolution merges only those, the settings store drops any other, and the document codec reads its frozen built-ins (see `projects/README.md`). The workbench store seeds the mirror of the defaults when it is created and the runtime keeps it current; reads resolve at the generic seams (`getResolvedProjectWidgetValues`, `getEffectiveProjectSettings`), a project without the widget reading the defaults alone. A widget's runtime `getSnapshot` returns resolved values while `set` replaces raw pins, so widgets write with `patch`. Inside a project the dialog and gear popover edit pins. A widget owner's pins live on the project's instance of its type (`getProjectWidgetInstance`), the one every reader resolves, since layered widgets allow one instance and aliases such as `gallery:center` share it; a requested instance target only fences, staying editable while it exists with the owner's type. Without one (the Launchpad, or a project lacking that widget) the same field edits the default (never for the Generate section, which pins on the project), and its section says "Defaults for every project. A project can pin its own value." There is no unavailable state: search results are always editable. `useLayeredSetting(ownerId, key, target, read, builtIn, field)` is the one binding seam for layered fields: it returns value, layer, setter and disabled state, fences pin writes against stale account/project/instance, and disables a requested target that is no longer current. Shell disposes target-bound editing when projects change.+A `project` field resolves as the project's pin, then the user's default, then the owner's built-in. Pins are the keys present in the widget instance's `state.values`, or the optional generation flags in `ProjectSettings`; persistence keeps them raw. The generation flags (CPU noise, NSFW checker, watermark) are the Generate widget's settings, behind its cog, but they are project settings: every generation in the project reads them, and they pin on the project whichever widgets it has. Defaults live in `WorkbenchPreferences.scopedDefaults`, keyed by widget type id (`gallery`, `canvas`, `preview`, `image-map`, and `generate`, whose record layers over `ProjectSettings`, never over the Generate widget's values), each holding only keys the user chose (a default equal to the built-in is removed). `getLayeredSettings` in `projectSettings.ts` is the one list of layerable keys: resolution merges only those, the settings store drops any other, and the document codec reads its frozen built-ins (see `projects/README.md`). The workbench store seeds the mirror of the defaults when it is created and the runtime keeps it current; reads resolve at the generic seams (`getResolvedProjectWidgetValues`, `getEffectiveProjectSettings`), a project without the widget reading the defaults alone. Resolved reads return `ResolvedValues`, and readers of layerable keys accept only that type, so stored pins fail to compile there; `getProjectWidgetValues` stays raw for writes and persistence. Exception: `stripInfiniteWindowAnchor` reads the pinned `paginationMode` raw, because a project document has no account defaults. A widget's runtime `getSnapshot` returns resolved values while `set` replaces raw pins, so widgets write with `patch`. Inside a project the dialog and gear popover edit pins. A widget owner's pins live on the project's instance of its type (`getProjectWidgetInstance`), the one every reader resolves, since layered widgets allow one instance and aliases such as `gallery:center` share it; a requested instance target only fences, staying editable while it exists with the owner's type. Without one (the Launchpad, or a project lacking that widget) the same field edits the default (never for the Generate section, which pins on the project), and its section says "Defaults for every project. A project can pin its own value." There is no unavailable state: search results are always editable. `useLayeredSetting(ownerId, key, target, read, builtIn, field)` is the one binding seam for layered fields: it returns value, layer, setter and disabled state, fences pin writes against stale account/project/instance, and disables a requested target that is no longer current. Shell disposes target-bound editing when projects change.Settings host owns dialog's presence lifecycle and keeps its root mounted through closing. Body deferred until first opening, stays present during exit, unmounts afterward. Quick-popover handoff carries both instance target and original gear for focus restoration.diff --git a/invokeai/frontend/webv2/src/workbench/settings/useLayeredSetting.ts b/invokeai/frontend/webv2/src/workbench/settings/useLayeredSetting.tsindex eef3384828..76042f1d5c 100644--- a/invokeai/frontend/webv2/src/workbench/settings/useLayeredSetting.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/useLayeredSetting.ts@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { SettingDefinition, SettingLayer, SettingsTarget } from '@platform/ui/settings/contracts';import type { Project } from '@workbench/projectContracts';import type { WorkbenchSnapshot } from '@workbench/workbenchStore';@@ -29,6 +30,10 @@ export type LayeredSettingValue = boolean | string | number | null;const EMPTY: Readonly<Record<string, unknown>> = {};+const asUnpinned = (defaults: Readonly<Record<string, unknown>>): ResolvedValues => defaults as ResolvedValues;++export const readBuiltIn = <V>(read: (values: ResolvedValues) => V): V => read(asUnpinned(EMPTY));+/** A value as a settings row names it: a select's option label, On/Off, the number; `null` is "Automatic". */export const formatSettingValue = (field: SettingDefinition, value: LayeredSettingValue, t: TFunction): string => {if (value === null) {@@ -69,9 +74,10 @@ const getPin = (pins: object, key: string): unknown =>const getResolvedValues = (snapshot: WorkbenchSnapshot, ownerId: string, target: SettingsTarget) => {const project = snapshot.activeProject;if (ownerId === PROJECT_SETTINGS_OWNER) {- return getEffectiveProjectSettings(project.settings, snapshot.scopedDefaults[PROJECT_SETTINGS_OWNER]) as Readonly<- Record<string, unknown>- >;+ return getEffectiveProjectSettings(+ project.settings,+ snapshot.scopedDefaults[PROJECT_SETTINGS_OWNER]+ ) as unknown as ResolvedValues;}return resolveWidgetValues(getTargetInstance(project, ownerId, target), snapshot.scopedDefaults);};@@ -84,7 +90,7 @@ export const useLayeredSetting = <V extends LayeredSettingValue>(ownerId: string,key: string,target: SettingsTarget | undefined,- read: (values: Readonly<Record<string, unknown>>) => V,+ read: (values: ResolvedValues) => V,builtIn: V,field: SettingDefinition): { value: V; layer: SettingLayer | undefined; set: (value: V) => void; disabled: boolean } => {@@ -94,7 +100,7 @@ export const useLayeredSetting = <V extends LayeredSettingValue>(const commands = useOptionalWorkbenchCommands();const queries = useOptionalWorkbenchQueries();const defaults = useWorkbenchPreferenceSelector((preferences) => preferences.scopedDefaults[ownerId] ?? EMPTY);- const defaultValue = read(defaults);+ const defaultValue = read(asUnpinned(defaults));const hasDefault = Object.hasOwn(defaults, key);const pinned = useOptionalWorkbenchSelector((snapshot) => {const pins = target ? getPins(snapshot.activeProject, ownerId, target) : null;@@ -134,7 +140,7 @@ export const useLayeredSetting = <V extends LayeredSettingValue>(}const current = getWorkbenchPreferences().scopedDefaults[ownerId] ?? EMPTY;// A default equal to the built-in is no default: the key goes, so the record keeps only real choices.- if (read({ ...current, [key]: stored }) === builtIn) {+ if (read(asUnpinned({ ...current, [key]: stored })) === builtIn) {void clearScopedDefault(ownerId, [key]);} else {void patchScopedDefault(ownerId, { [key]: stored });@@ -238,7 +244,7 @@ export const useLayeredSetting = <V extends LayeredSettingValue>([key, ownerId]);const valueText = useCallback(- (values: Readonly<Record<string, unknown>>) => formatSettingValue(field, read(values), t),+ (defaults: Readonly<Record<string, unknown>>) => formatSettingValue(field, read(asUnpinned(defaults)), t),[field, read, t]);@@ -286,7 +292,7 @@ export const useLayeredSetting = <V extends LayeredSettingValue>(const prior = readDefault();const written = { ...(getWorkbenchPreferences().scopedDefaults[ownerId] ?? EMPTY), [key]: pin };// `writeDefault` drops a default equal to the built-in, so the default it leaves is either the pin or nothing.- const writesDefault = read(written) !== builtIn;+ const writesDefault = read(asUnpinned(written)) !== builtIn;writeDefault(pin);clearPin();const isDefaultAsWritten = () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgetState.test.ts b/invokeai/frontend/webv2/src/workbench/widgetState.test.tsindex 342a3e1bbb..25dd14f3eb 100644--- a/invokeai/frontend/webv2/src/workbench/widgetState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetState.test.ts@@ -31,6 +31,8 @@ describe('resolveWidgetValues', () => {expect(getGallerySettings(getResolvedProjectWidgetValues(pinned, 'gallery', defaults)).thumbnailFit).toBe('square');// The pins themselves are untouched: persistence and write paths read these.expect(getProjectWidgetValues(following, 'gallery')).toEqual({ showDateBoards: true });+ // @ts-expect-error Readers of layered keys reject stored pins.+ getGallerySettings(getProjectWidgetValues(following, 'gallery'));});it("returns the instance's own values while its type has no defaults", () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgetState.ts b/invokeai/frontend/webv2/src/workbench/widgetState.tsindex 558f74a6aa..6841ac4d19 100644--- a/invokeai/frontend/webv2/src/workbench/widgetState.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetState.ts@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { Project } from '@workbench/projectContracts';import type { ScopedDefaults } from '@workbench/settings/contracts';import type { WidgetInstanceContract, WidgetStateContract, WidgetTypeId } from '@workbench/widgetContracts';@@ -27,10 +28,7 @@ export const getProjectWidgetInstance = (export const getProjectWidgetState = (project: WidgetInstanceHolder, widgetId: WidgetTypeId): WidgetStateContract =>getProjectWidgetInstance(project, widgetId)?.state ?? emptyWidgetState(widgetId);-/**- * Stored values; for a layered key (`getLayeredSettings`) that is the pin alone; {@link getResolvedProjectWidgetValues}- * is the resolved read. Write paths and persistence read these.- */+/** Stored pins, for writes and persistence; readers of layered keys need the resolved reads below. */export const getProjectWidgetValues = (project: WidgetInstanceHolder,widgetId: WidgetTypeId@@ -39,7 +37,7 @@ export const getProjectWidgetValues = (/** Per defaults record, per pins object: the merge, so repeated reads of unchanged inputs keep their identity. */// Created on first use: a module-scope `new WeakMap()` reads a global, which makes the module side-effectful to// Rolldown and keeps it (and every barrel re-exporting through it) out of tree-shaking.-let resolvedValuesCache: WeakMap<object, WeakMap<object, Record<string, unknown>>> | undefined;+let resolvedValuesCache: WeakMap<object, WeakMap<object, ResolvedValues>> | undefined;/*** `values` over the user's defaults for widget type `typeId`, taking from the defaults only the type's layerable keys@@ -50,11 +48,11 @@ export const applyWidgetDefaults = (values: Record<string, unknown>,typeId: WidgetTypeId,defaults: ScopedDefaults-): Record<string, unknown> => {+): ResolvedValues => {const typeDefaults = defaults[typeId];const layered = typeDefaults ? getLayeredSettings().widgetValues[typeId] : undefined;if (!typeDefaults || !layered || !Object.keys(typeDefaults).some((key) => Object.hasOwn(layered, key))) {- return values;+ return values as ResolvedValues;}resolvedValuesCache ??= new WeakMap();let byValues = resolvedValuesCache.get(typeDefaults);@@ -64,12 +62,13 @@ export const applyWidgetDefaults = (}let resolved = byValues.get(values);if (!resolved) {- resolved = { ...values };+ const merged = { ...values };for (const key of Object.keys(typeDefaults)) {if (Object.hasOwn(layered, key) && !Object.hasOwn(values, key)) {- resolved[key] = typeDefaults[key];+ merged[key] = typeDefaults[key];}}+ resolved = merged as ResolvedValues;byValues.set(values, resolved);}return resolved;@@ -79,20 +78,19 @@ export const applyWidgetDefaults = (export const resolveWidgetValues = (instance: WidgetInstanceContract | undefined,defaults: ScopedDefaults-): Record<string, unknown> =>- instance ? applyWidgetDefaults(instance.state.values, instance.typeId, defaults) : EMPTY_WIDGET_VALUES;+): ResolvedValues =>+ instance+ ? applyWidgetDefaults(instance.state.values, instance.typeId, defaults)+ : (EMPTY_WIDGET_VALUES as ResolvedValues);-/**- * {@link getProjectWidgetValues} with the user's defaults applied under the project's pins; a project without the- * widget reads the defaults alone, as a new instance would.- */+/** The project's pins over the user's defaults; without the widget or a project, the defaults alone. */export const getResolvedProjectWidgetValues = (- project: WidgetInstanceHolder,+ project: WidgetInstanceHolder | undefined,widgetId: WidgetTypeId,defaults: ScopedDefaults-): Record<string, unknown> =>+): ResolvedValues =>applyWidgetDefaults(- getProjectWidgetInstance(project, widgetId)?.state.values ?? EMPTY_WIDGET_VALUES,+ (project && getProjectWidgetInstance(project, widgetId)?.state.values) ?? EMPTY_WIDGET_VALUES,widgetId,defaults);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex 3daee2b73d..314fee06cd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { CanvasDocumentContractV3, Rect } from '@workbench/canvas-engine/api';import type { CanvasGallerySaveRegion, CreateFromBboxDestination } from '@workbench/canvas-operations/api';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */@@ -90,7 +91,7 @@ const selectModelBase = (project: Project): string | null => {};/** The project's clamped compositing mask blur, which fit-to-masks clears so the feathered edge stays in frame. */-const selectMaskBlur = (values: Record<string, unknown>): number => readCanvasCompositingSettings(values).maskBlur;+const selectMaskBlur = (values: ResolvedValues): number => readCanvasCompositingSettings(values).maskBlur;const selectModelVariant = (project: Project): string | null => {const values = getProjectWidgetValues(project, 'generate') as { model?: { variant?: unknown } } | undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.tsindex 088534335e..12d68a8dc7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts@@ -1,3 +1,4 @@+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import {@@ -41,22 +42,24 @@ const DEFAULTS = {describe('canvasSettings persistence mapping', () => {it('applies each setting default when values are missing', () => {expect(resolveCanvasSettings(undefined)).toEqual(DEFAULTS);- expect(resolveCanvasSettings({})).toEqual(DEFAULTS);+ expect(resolveCanvasSettings(resolvedValues({}))).toEqual(DEFAULTS);});it('reads persisted booleans over the defaults', () => {- const resolved = resolveCanvasSettings({- [CANVAS_BBOX_OVERLAY_KEY]: true,- [CANVAS_CHECKERBOARD_KEY]: false,- [CANVAS_CLIP_TO_BBOX_KEY]: true,- [CANVAS_INVERT_BRUSH_SCROLL_KEY]: true,- [CANVAS_OUTPUT_ONLY_MASKED_REGIONS_KEY]: false,- [CANVAS_RULE_OF_THIRDS_KEY]: true,- [CANVAS_SHOW_BBOX_KEY]: false,- [CANVAS_SHOW_GRID_KEY]: true,- [CANVAS_SHOW_PROGRESS_KEY]: false,- [CANVAS_SNAP_TO_GRID_KEY]: false,- });+ const resolved = resolveCanvasSettings(+ resolvedValues({+ [CANVAS_BBOX_OVERLAY_KEY]: true,+ [CANVAS_CHECKERBOARD_KEY]: false,+ [CANVAS_CLIP_TO_BBOX_KEY]: true,+ [CANVAS_INVERT_BRUSH_SCROLL_KEY]: true,+ [CANVAS_OUTPUT_ONLY_MASKED_REGIONS_KEY]: false,+ [CANVAS_RULE_OF_THIRDS_KEY]: true,+ [CANVAS_SHOW_BBOX_KEY]: false,+ [CANVAS_SHOW_GRID_KEY]: true,+ [CANVAS_SHOW_PROGRESS_KEY]: false,+ [CANVAS_SNAP_TO_GRID_KEY]: false,+ })+ );expect(resolved).toEqual({[CANVAS_BBOX_OVERLAY_KEY]: true,[CANVAS_CHECKERBOARD_KEY]: false,@@ -72,10 +75,15 @@ describe('canvasSettings persistence mapping', () => {});it('falls back to the default for a non-boolean persisted value', () => {- expect(readCanvasBooleanSetting({ [CANVAS_CHECKERBOARD_KEY]: 'nope' }, settingByKey(CANVAS_CHECKERBOARD_KEY))).toBe(- true- );- expect(readCanvasBooleanSetting({ [CANVAS_SHOW_GRID_KEY]: 1 }, settingByKey(CANVAS_SHOW_GRID_KEY))).toBe(false);+ expect(+ readCanvasBooleanSetting(+ resolvedValues({ [CANVAS_CHECKERBOARD_KEY]: 'nope' }),+ settingByKey(CANVAS_CHECKERBOARD_KEY)+ )+ ).toBe(true);+ expect(+ readCanvasBooleanSetting(resolvedValues({ [CANVAS_SHOW_GRID_KEY]: 1 }), settingByKey(CANVAS_SHOW_GRID_KEY))+ ).toBe(false);});it('maps every setting to a unique persisted key', () => {@@ -93,9 +101,13 @@ describe('canvasSettings persistence mapping', () => {describe('canvasSettingsEqual', () => {it('is true for equal maps and false when any setting differs', () => {- const base = resolveCanvasSettings({});- expect(canvasSettingsEqual(base, resolveCanvasSettings({}))).toBe(true);- expect(canvasSettingsEqual(base, resolveCanvasSettings({ [CANVAS_SHOW_GRID_KEY]: true }))).toBe(false);- expect(canvasSettingsEqual(base, resolveCanvasSettings({ [CANVAS_SHOW_BBOX_KEY]: false }))).toBe(false);+ const base = resolveCanvasSettings(resolvedValues({}));+ expect(canvasSettingsEqual(base, resolveCanvasSettings(resolvedValues({})))).toBe(true);+ expect(canvasSettingsEqual(base, resolveCanvasSettings(resolvedValues({ [CANVAS_SHOW_GRID_KEY]: true })))).toBe(+ false+ );+ expect(canvasSettingsEqual(base, resolveCanvasSettings(resolvedValues({ [CANVAS_SHOW_BBOX_KEY]: false })))).toBe(+ false+ );});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.tsindex 88a61e7f7e..f5585b8572 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts@@ -1,5 +1,7 @@/** Per-project canvas preferences, outside undo history; engine-backed ones feed stores one way. */+import type { ResolvedValues } from '@platform/core/resolvedValues';+import { CANVAS_COMPOSITING_KEYS, DEFAULT_CANVAS_COMPOSITING } from './invoke/canvasCompositing';/** Which engine boolean store a setting feeds (settings without one are consumed elsewhere in the frontend). */@@ -122,14 +124,14 @@ export type ResolvedCanvasSettings = Record<string, boolean>;/** Reads one boolean setting from a widget's `state.values`, applying its default when unset/non-boolean. */export const readCanvasBooleanSetting = (- values: Record<string, unknown> | undefined,+ values: ResolvedValues | undefined,setting: CanvasBooleanSetting): boolean => {const raw = values?.[setting.key];return typeof raw === 'boolean' ? raw : setting.defaultValue;};-export const resolveCanvasSettings = (values: Record<string, unknown> | undefined): ResolvedCanvasSettings => {+export const resolveCanvasSettings = (values: ResolvedValues | undefined): ResolvedCanvasSettings => {const resolved: ResolvedCanvasSettings = {};for (const setting of CANVAS_SETTINGS) {resolved[setting.key] = readCanvasBooleanSetting(values, setting);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.tsindex b616cc4766..23d26457ad 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.ts@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { AccountScope } from '@platform/state/accountLifecycle';import type { QueryClient } from '@tanstack/react-query';import type {@@ -34,7 +35,7 @@ export const importCanvasFileDrop = async ({destination: CanvasImageDropData['destination'];files: File[];/** The project's gallery values when the files were dropped, which name its auto-add board. */- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;notifications: WorkbenchNotificationCommands;/** The account the files were dropped in. */owner: AccountScope;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.test.tsindex e8d4f3a5a6..fb25e836fb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.test.ts@@ -1,3 +1,4 @@+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import { DEFAULT_CANVAS_COMPOSITING, readCanvasCompositingSettings } from './canvasCompositing';@@ -22,14 +23,16 @@ describe('readCanvasCompositingSettings', () => {});it('reads valid persisted values', () => {- const settings = readCanvasCompositingSettings({- coherenceEdgeSize: 32,- coherenceMinDenoise: 0.2,- coherenceMode: 'Box Blur',- infillMethod: 'patchmatch',- maskBlur: 8,- outputOnlyMaskedRegions: false,- });+ const settings = readCanvasCompositingSettings(+ resolvedValues({+ coherenceEdgeSize: 32,+ coherenceMinDenoise: 0.2,+ coherenceMode: 'Box Blur',+ infillMethod: 'patchmatch',+ maskBlur: 8,+ outputOnlyMaskedRegions: false,+ })+ );expect(settings.coherenceEdgeSize).toBe(32);expect(settings.coherenceMinDenoise).toBe(0.2);expect(settings.coherenceMode).toBe('Box Blur');@@ -39,17 +42,19 @@ describe('readCanvasCompositingSettings', () => {});it('falls back to defaults for invalid enum values', () => {- const settings = readCanvasCompositingSettings({ coherenceMode: 'Wobble', infillMethod: 'magic' });+ const settings = readCanvasCompositingSettings(resolvedValues({ coherenceMode: 'Wobble', infillMethod: 'magic' }));expect(settings.coherenceMode).toBe('Gaussian Blur');expect(settings.infillMethod).toBe('lama');});it('clamps numeric ranges and rounds integers', () => {- const settings = readCanvasCompositingSettings({- coherenceEdgeSize: -5,- coherenceMinDenoise: 5,- maskBlur: 12.7,- });+ const settings = readCanvasCompositingSettings(+ resolvedValues({+ coherenceEdgeSize: -5,+ coherenceMinDenoise: 5,+ maskBlur: 12.7,+ })+ );expect(settings.coherenceEdgeSize).toBe(0);expect(settings.coherenceMinDenoise).toBe(1);expect(settings.maskBlur).toBe(13);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.tsindex a22c50b453..98791a747c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts@@ -1,5 +1,7 @@/** Per-project compositing policy; defaults mirror legacy infill/coherence/mask behavior. */+import type { ResolvedValues } from '@platform/core/resolvedValues';+/** The infill methods the outpaint graph can request (legacy `zInfillMethod`). */export type CanvasInfillMethod = 'patchmatch' | 'lama' | 'cv2' | 'color' | 'tile';@@ -88,10 +90,8 @@ const readInfillColor = (value: unknown): CanvasInfillColor => {};/** Return complete compositing settings with legacy defaults for invalid/missing fields and valid-range clamping. */-export const readCanvasCompositingSettings = (- values: Record<string, unknown> | undefined-): CanvasCompositingSettings => {- const v = values ?? {};+export const readCanvasCompositingSettings = (values: ResolvedValues | undefined): CanvasCompositingSettings => {+ const v: Readonly<Record<string, unknown>> = values ?? {};const d = DEFAULT_CANVAS_COMPOSITING;const coherenceMode = v[CANVAS_COMPOSITING_KEYS.coherenceMode];const infillMethod = v[CANVAS_COMPOSITING_KEYS.infillMethod];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 2ed43aaa3e..a9aad7eefa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -11,6 +11,7 @@ import type { ComposeForGenerationOptions, ComposeForGenerationResult } from '@wimport type { CanvasInputIssue, ControlLayerVerdict, RegionalLayerVerdict } from '@workbench/canvasGenerationInputs';import type { ControlModelMemory } from '@workbench/controlModelResolution';import type { ExpandedPositivePrompts, ResultDestination } from '@workbench/invocationContracts';+import type { CanvasCompositingSettings } from '@workbench/widgets/canvas/invoke/canvasCompositing';import type { WorkbenchCommands, WorkbenchNotificationCommands } from '@workbench/workbenchStore';import { compileCanvasGraph, type CanvasCompileMode } from '@features/generation/canvasGraph';@@ -26,10 +27,6 @@ import {import { getCanvasEngine, getCanvasOperations, recordCanvasMetadata } from '@workbench/canvas-operations/api';import { createCanvasInputJudge } from '@workbench/canvasGenerationInputs';import { getWorkbenchPreferences } from '@workbench/settings/store';-import {- DEFAULT_CANVAS_COMPOSITING,- type CanvasCompositingSettings,-} from '@workbench/widgets/canvas/invoke/canvasCompositing';import type { CanvasInvocationFailure, CanvasInvocationNotice } from './canvasInvocationFailure';@@ -247,8 +244,8 @@ export interface PrepareCanvasInvocationArgs {canvasValues?: Record<string, unknown>;strength: number;signal?: AbortSignal;- /** Persisted compositing settings, already defaulted and clamped by the caller; legacy defaults when omitted. */- compositing?: CanvasCompositingSettings;+ /** From resolved canvas values, so user defaults apply. */+ compositing: CanvasCompositingSettings;commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;formatCanvasInvocationFailure: RunCanvasInvocationDeps['formatCanvasInvocationFailure'];}@@ -269,7 +266,7 @@ export const prepareCanvasInvocation = async (args: PrepareCanvasInvocationArgs)const signal = args.signal ? AbortSignal.any([args.signal, owner.signal]) : owner.signal;await runCanvasInvocation({- compositing: args.compositing ?? DEFAULT_CANVAS_COMPOSITING,+ compositing: args.compositing,destination: args.destination,commands: args.commands,expansion: args.expansion,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsxindex dee84dc7ea..5826968f04 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { SettingFieldProps } from '@platform/ui/settings/contracts';import { SettingControl } from '@platform/ui/settings/SettingControl';@@ -9,7 +10,7 @@ import { CANVAS_SETTINGS, readCanvasBooleanSetting } from './canvasSettings';export const Field = ({ field, surface, target }: SettingFieldProps) => {const definition = CANVAS_SETTINGS.find((setting) => setting.key === field.id);const read = useCallback(- (values: Readonly<Record<string, unknown>>) => (definition ? readCanvasBooleanSetting(values, definition) : false),+ (values: ResolvedValues) => (definition ? readCanvasBooleanSetting(values, definition) : false),[definition]);const { disabled, layer, set, value } = useLayeredSetting(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/settingsBindings.tsxindex 63b8579c0f..c15f541abe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/settingsBindings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/settingsBindings.tsx@@ -1,14 +1,13 @@import type { GallerySettings } from '@features/gallery/contracts';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { SettingFieldProps, SettingLayer } from '@platform/ui/settings/contracts';import { getGallerySettings } from '@features/gallery/contracts';import { SettingControl } from '@platform/ui/settings/SettingControl';-import { useLayeredSetting } from '@workbench/settings/useLayeredSetting';+import { readBuiltIn, useLayeredSetting } from '@workbench/settings/useLayeredSetting';import { useOptionalWorkbenchCommands, useOptionalWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';-const EMPTY = {};-/** Settings that reorder or repaginate the grid, so a paginated gallery starts again at its first page. */const RESETS_PAGE = new Set(['imageOrderDir', 'paginationMode']);@@ -48,14 +47,14 @@ export const Field = ({ field, surface, target }: SettingFieldProps) => {const read = useMemo(() =>isImageSize- ? (values: Readonly<Record<string, unknown>>) => 100 - getGallerySettings(values).imageDensityPercent- : (values: Readonly<Record<string, unknown>>) => {+ ? (values: ResolvedValues) => 100 - getGallerySettings(values).imageDensityPercent+ : (values: ResolvedValues) => {const value = getGallerySettings(values)[field.id as keyof GallerySettings];return typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string' ? value : null;},[field.id, isImageSize]);- const { disabled, layer, set, value } = useLayeredSetting('gallery', key, target, read, read(EMPTY), field);+ const { disabled, layer, set, value } = useLayeredSetting('gallery', key, target, read, readBuiltIn(read), field);const commands = useOptionalWorkbenchCommands();const queries = useOptionalWorkbenchQueries();const projectId = target?.projectId;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsxindex 9562d96c95..f9d4b1322b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx@@ -2,12 +2,10 @@ import type { SettingFieldProps } from '@platform/ui/settings/contracts';import { SettingControl } from '@platform/ui/settings/SettingControl';import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';-import { useLayeredSetting } from '@workbench/settings/useLayeredSetting';+import { readBuiltIn, useLayeredSetting } from '@workbench/settings/useLayeredSetting';import { ClusterStrengthField } from '@workbench/widgets/image-map/ClusterStrengthField';import { useCallback } from 'react';-const EMPTY = {};-export const Field = (props: SettingFieldProps) => {// Its empty state means "derive it", which no shared control expresses.if (props.field.id === 'clusterEps') {@@ -19,7 +17,14 @@ export const Field = (props: SettingFieldProps) => {const BooleanField = ({ field, surface, target }: SettingFieldProps) => {const read = field.id === 'clickSelectsCluster' ? getImageMapClickSelectsCluster : getImageMapShowClusterLabels;- const { disabled, layer, set, value } = useLayeredSetting('image-map', field.id, target, read, read(EMPTY), field);+ const { disabled, layer, set, value } = useLayeredSetting(+ 'image-map',+ field.id,+ target,+ read,+ readBuiltIn(read),+ field+ );const onChange = useCallback((next: boolean | string | number) => {if (typeof next === 'boolean' && (field.id === 'clickSelectsCluster' || field.id === 'showClusterLabels')) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsxindex d1e2dadde5..a31207fc3a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSaveToBoardSubmenu.browser.test.tsx@@ -4,6 +4,7 @@ import type { GalleryBoard } from '@features/gallery';import { ChakraProvider, Menu, Portal } from '@chakra-ui/react';import { getGallerySettings } from '@features/gallery/contracts';import { galleryBoardsOptions, getGalleryListingBoardsQuery } from '@features/gallery/queries';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { SaveIcon } from 'lucide-react';@@ -100,7 +101,7 @@ const hover = async (target: HTMLElement): Promise<void> => {const render = async (action: LayerContextAction, onSelect = vi.fn()) => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });- const listing = galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings({})));+ const listing = galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings(resolvedValues({}))));queryClient.setQueryData(listing.queryKey, [board('mine', ['read', 'add_media']), board('read-only', ['read'])]);host = document.createElement('div');document.body.append(host);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsxindex 98e36f9c63..772bbb0a9e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx@@ -19,7 +19,7 @@ import {} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { getProjectWidgetValues } from '@workbench/widgetState';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { createInstance } from 'i18next';import { act, createRef, useImperativeHandle, useState, type Ref } from 'react';@@ -329,7 +329,7 @@ const sketchesBoard: GalleryBoard = {const listBoards = (panelBoards: GalleryBoard[], destinationBoards: GalleryBoard[]) => {const listing = galleryBoardsOptions(- getGalleryListingBoardsQuery(getGallerySettings(getProjectWidgetValues(mocks.project, 'gallery')))+ getGalleryListingBoardsQuery(getGallerySettings(getResolvedProjectWidgetValues(mocks.project, 'gallery', {}))));queryClient.setQueryData(listing.queryKey, panelBoards, { updatedAt: Date.now() - 1_000 });queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, destinationBoards);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.tsindex b6e9c1dcef..4dfcf0abc9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts@@ -5,6 +5,7 @@ import {galleryKeys,getGalleryListingBoardsQuery,} from '@features/gallery/queries';+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { QueryClient, QueryObserver } from '@tanstack/react-query';@@ -112,7 +113,10 @@ describe('saveLayerToBoard', () => {]);const client = createClient();await client.fetchQuery(galleryBoardsOptions({ includeArchived: true }));- const panel = new QueryObserver(client, galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings({}))));+ const panel = new QueryObserver(+ client,+ galleryBoardsOptions(getGalleryListingBoardsQuery(getGallerySettings(resolvedValues({}))))+ );const unsubscribe = panel.subscribe(() => undefined);await vi.waitFor(() => expect(panel.getCurrentResult().data?.some((board) => board.id === 'board-7')).toBe(true));const itemList = seedItemList(client, 'board-7');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.tsindex 73b220bbb8..ef65a63798 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.ts@@ -1,4 +1,5 @@import type { GalleryItem } from '@features/gallery/contracts';+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { AccountScope } from '@platform/state/accountLifecycle';import type { QueryClient } from '@tanstack/react-query';import type {@@ -31,7 +32,7 @@ export const importPreviewFileDrop = async ({files: File[];gallery: Pick<WorkbenchGalleryCommands, 'selectItemInItsBoard' | 'setCompareItem'>;/** The project's gallery values when the files were dropped, which name its auto-add board. */- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;notifications: WorkbenchNotificationCommands;/** The account the files were dropped in. */owner: AccountScope;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.tsindex 04ba80ef4b..bb95f8f771 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts@@ -1,3 +1,4 @@+import { resolvedValues } from '@platform/core/resolvedValues.testing';import { describe, expect, it } from 'vitest';import { getNextPreviewComparisonMode } from './PreviewCompare';@@ -11,7 +12,7 @@ describe('preview comparison settings', () => {['restores the side-by-side mode', { comparisonMode: 'side-by-side' }, 'side-by-side'],['restores the hover mode', { comparisonMode: 'hover' }, 'hover'],])('%s', (_, persisted, expected) => {- expect(getPreviewComparisonMode(persisted)).toBe(expected);+ expect(getPreviewComparisonMode(resolvedValues(persisted))).toBe(expected);});it('cycles all three comparison modes in order', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.tsindex 18597a9892..b6707445a3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts@@ -1,8 +1,10 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';+export type PreviewComparisonMode = 'slider' | 'side-by-side' | 'hover';export const DEFAULT_PREVIEW_COMPARISON_MODE: PreviewComparisonMode = 'slider';-export const getPreviewComparisonMode = (values: Record<string, unknown>): PreviewComparisonMode => {+export const getPreviewComparisonMode = (values: ResolvedValues): PreviewComparisonMode => {const mode = values.comparisonMode;return mode === 'side-by-side' || mode === 'hover' ? mode : DEFAULT_PREVIEW_COMPARISON_MODE;@@ -10,8 +12,7 @@ export const getPreviewComparisonMode = (values: Record<string, unknown>): Previexport const getPreviewMetadataOpen = (values: Record<string, unknown>): boolean => values.metadataOpen === true;-export const getPreviewFilmstripVisible = (values: Record<string, unknown>): boolean =>- values.filmstripVisible !== false;+export const getPreviewFilmstripVisible = (values: ResolvedValues): boolean => values.filmstripVisible !== false;/** Whether the Preview's videos loop: on until the viewer turns it off in the player. */export const getPreviewVideoLoop = (values: Record<string, unknown>): boolean => values.videoLoop !== false;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsxindex 0c8881348c..2e5eb7c90c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsBindings.tsx@@ -1,21 +1,21 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { SettingFieldProps } from '@platform/ui/settings/contracts';import { SettingControl } from '@platform/ui/settings/SettingControl';-import { useLayeredSetting } from '@workbench/settings/useLayeredSetting';+import { readBuiltIn, useLayeredSetting } from '@workbench/settings/useLayeredSetting';import { useCallback } from 'react';import { getPreviewComparisonMode, getPreviewFilmstripVisible } from './previewSettings';-const EMPTY = {};-export const Field = ({ field, surface, target }: SettingFieldProps) => {- const read = field.id === 'comparisonMode' ? getPreviewComparisonMode : getPreviewFilmstripVisible;+ const read: (values: ResolvedValues) => boolean | string =+ field.id === 'comparisonMode' ? getPreviewComparisonMode : getPreviewFilmstripVisible;const { disabled, layer, set, value } = useLayeredSetting<boolean | string>('preview',field.id,target,read,- read(EMPTY),+ readBuiltIn(read),field);const onChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.ts b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.tsindex 48706d6e17..a064e3c58d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.ts@@ -1,3 +1,4 @@+import type { ResolvedValues } from '@platform/core/resolvedValues';import type { AccountScope } from '@platform/state/accountLifecycle';import type { WidgetTypeId } from '@workbench/widgetContracts';@@ -13,7 +14,7 @@ import { useTranslation } from 'react-i18next';/** What a dropped upload is fenced to, captured at the drop. */export interface DroppedFileUploadContext {/** The project's resolved gallery values at the drop, which name its auto-add board. */- galleryValues: Record<string, unknown>;+ galleryValues: ResolvedValues;owner: AccountScope;projectId: string;}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 51bd01c253..4b5eb3482b 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -72,6 +72,8 @@ import {stripInfiniteWindowAnchor,stripUnresolvableGallerySearch,gallerySemanticReferenceKey,+ getGalleryChosenAutoAddBoardId,+ getGalleryMediaFilter,getGallerySettings,toGalleryMediaKind,parseGallerySemanticReference,@@ -3563,7 +3565,7 @@ const removeGalleryItemsFromAllProjects = (/** Its own inbox is left out: it exists only with the project and goes with it. */export const getProjectGalleryBoardReferences = (project: Project): string[] => {const values = getWidgetValues(project, 'gallery');- const { autoAddBoardId } = getGallerySettings(values);+ const autoAddBoardId = getGalleryChosenAutoAddBoardId(values);const references = new Set<string>();for (const boardId of [@@ -4364,7 +4366,7 @@ const getRankingStampFields = (return semanticKey? {boardId: getGallerySelectionBoardId(values),- mediaKind: toGalleryMediaKind(getGallerySettings(values).mediaFilter) ?? null,+ mediaKind: toGalleryMediaKind(getGalleryMediaFilter(values)) ?? null,semanticKey,}: { semanticKey: null };