Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(generation): reset the frame to native size and remember Auto Process
Josh Corbetta3675e390529
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 72e8a0f565..6d77151990 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2798,6 +2798,11 @@"removeConceptNamed": "Remove {{name}}","removeReferenceImage": "Remove reference image","render": "Render",+ "resetSize": "Reset size",+ "resetSizeModelDefaults": "Model defaults",+ "resetSizeOptimalForCurrentRatio": "Optimal size for current ratio",+ "resetSizeOptimalForRatio": "Optimal size for {{ratio}}",+ "resetSizeSquareNative": "Square at native size","resetAllToModelDefaults": "Reset all to model defaults","resizeNegativePrompt": "Resize negative prompt","resizePositivePrompt": "Resize positive prompt",@@ -2812,8 +2817,6 @@"selectModelFirst": "Select a model first","selectTextLlm": "Select Text LLM","selectVisionModel": "Select vision model",- "setOptimalSize": "Set optimal size",- "setOptimalSizeDescription": "Set size to the model's optimal pixel count","size": "Size","sizeRecommended": "Recommended ✓","steps": "Steps",@@ -3267,19 +3270,30 @@"selectMoveTool": "Select move tool","selectShapeTool": "Select shape tool","selectTextTool": "Select text tool",- "selectTransformTool": "Select transform tool",+ "selectTransformTool": "Transform selected layer","selectViewTool": "Select view tool","toggleNonRasterLayers": "Hide control, guidance and mask layers","undo": "Undo canvas edit","groupLayers": "Group selected layers","ungroupLayers": "Ungroup selected layers","swapColors": "Swap foreground and background colors",- "resetColors": "Reset colors to black and white"+ "resetColors": "Reset colors to black and white",+ "zoomTo100": "Zoom to 100%",+ "zoomTo200": "Zoom to 200%",+ "zoomTo400": "Zoom to 400%",+ "zoomTo800": "Zoom to 800%"},"contextMenu": {- "createError": "Couldn't create from BBox",- "createFromBbox": "Create From BBox",- "createdFromBbox": "Added {{destination}} from BBox",+ "createError": "Couldn't create from the frame",+ "createFromBbox": "Create From Frame",+ "createdFromBbox": "Added {{destination}} from the frame",+ "cropAllLayersToBbox": "Crop all layers to frame",+ "cropAllNothing": "Every layer already fits the frame",+ "cropAllNothingUnlocked": "Every unlocked layer already fits the frame",+ "croppedAllLayers_one": "Cropped {{count}} layer to the frame",+ "croppedAllLayers_other": "Cropped {{count}} layers to the frame",+ "croppedAllLayersSkipped_one": "{{count}} locked layer skipped",+ "croppedAllLayersSkipped_other": "{{count}} locked layers skipped","empty": "This region has no visible raster content.","newControlLayer": "New Control Layer","newGlobalReferenceImage": "New Global Reference Image",@@ -3289,7 +3303,7 @@"referenceImageAdded": "Added reference image","referenceImageFull": "The selected model can't accept more reference images.","referenceImageUnsupported": "The selected model doesn't support reference images.",- "saveBboxToGallery": "Save BBox to Gallery",+ "saveBboxToGallery": "Save Frame to Gallery","saveCanvasToGallery": "Save Canvas to Gallery","saveError": "Couldn't save to gallery","saveToGallery": "Save to Gallery",@@ -3341,9 +3355,9 @@"previousStagedCandidate": "Previous staged candidate","selectStagedCandidate": "Select staged candidate {{number}}","settings": {- "bboxOverlay": "Show bbox overlay",+ "bboxOverlay": "Dim outside frame","checkerboard": "Checkerboard background",- "clipToBbox": "Clip strokes to bbox",+ "clipToBbox": "Clip strokes to frame","clearCaches": "Clear caches","clearHistory": "Clear history","grid": "Show grid",@@ -3364,6 +3378,7 @@},"showStagedResultPreview": "Show staged result preview","showStagingThumbnails": "Show staging thumbnails",+ "transformPending": "Waiting for the stroke to save…","staging": {"acceptStopMessage": "Stopping the rest of its batch, which shows as cancelled in the queue.","acceptStopTitle": "Result accepted",@@ -3498,13 +3513,16 @@"gradient": "Gradient","label": "Tools","lasso": "Lasso select",+ "lassoHelp": "Draw a freehand or polygon outline to select pixels on the active layer. Fill, erase, or move them to a new layer. Doesn't change the generation frame.","marquee": "Marquee select",+ "marqueeHelp": "Drag a rectangle or ellipse to select pixels on the active layer. Fill, erase, or move them to a new layer. Doesn't change the generation frame.","move": "Move","sam": "Select object","shape": "Shape","text": "Text","transform": "Transform",- "view": "View"+ "view": "View",+ "withHotkey": "{{label}} ({{hotkey}})"}},"workflow": {@@ -3730,9 +3748,9 @@"convertToRegionalGuidance": "Convert to regional guidance","cropBusy": "Finish the current canvas action before cropping this layer.","cropFailed": "The layer could not be cropped.",- "cropLayerToBbox": "Crop layer to bbox",+ "cropLayerToBbox": "Crop layer to frame","cropUnsupported": "This layer cannot be cropped.",- "cropped": "Layer cropped to bbox.",+ "cropped": "Layer cropped to frame.","cutaway": "Cutaway with layer below","cutout": "Cutout with layer below","delete": "Delete layer",@@ -3747,7 +3765,7 @@"enableTransparencyEffect": "Enable transparent preview","exclude": "Exclude layer below","extractMaskedArea": "Extract masked area",- "fitToBbox": "Fit to bbox",+ "fitToBbox": "Fit to frame","disableLayer": "Disable layer","enableLayer": "Enable layer","disableSelected": "Disable selected",@@ -3813,7 +3831,12 @@"showModifiers": "Show modifiers","addDenoiseLimit": "Add denoise limit","addNoise": "Add noise",- "addRegenerateRegion": "Add regenerate region"+ "addRegenerateRegion": "Add regenerate region",+ "addRegenerateRegionDescription": "Regenerate where this layer has content, as a live inpaint mask.",+ "mergeMasks": "Merge masks",+ "mergeMasksIneligible": "Merge masks needs two or more enabled, unlocked inpaint masks with content.",+ "removeFromGroup": "Remove from group",+ "transformIneligible": "Transform works on enabled raster and control layers with content."},"control": {"apply": "Apply",@@ -3980,6 +4003,7 @@"preview": "Preview","processFailed": "The filter could not run.","replace": "Replace",+ "resetSettings": "Reset settings","running": "Running filter…","sourceOverBudget": "Not enough memory is free to read this layer for the filter.","statusCommitting": "Applying filter…",@@ -3990,12 +4014,12 @@},"selectObject": {"autoProcess": "Auto Process",- "bbox": "BBox",- "bboxActive": "Bounding box active",- "bboxInactive": "No bounding box",+ "bbox": "Box",+ "bboxActive": "Box prompt set",+ "bboxInactive": "No box prompt","errorDecode": "The object preview could not be decoded.","errorEmpty": "The layer has no visible content to select.",- "errorInvalid": "Add an object prompt, point, or bounding box before processing.",+ "errorInvalid": "Add an object prompt, point, or box before processing.","errorLocked": "Select Object cannot finish while canvas editing is locked.","errorNoOutput": "Select Object finished without producing an image.","errorNotReady": "The layer source is not ready. Try again when it finishes loading.",diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex 072abb78e7..f1572171c6 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -32,6 +32,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';import { shallowEqual } from '@platform/state/selectors';import { type QueryClient, QueryObserver, useQueryClient } from '@tanstack/react-query';+import { resetGenerateDims } from '@workbench/canvasDimsSync';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';import {getWorkbenchPreferences,@@ -308,8 +309,11 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode[generation, promptHistoryItems]);const settingsGroup = useMemo<GenerationUiAdapter['settings']>(- () => ({ patchGenerateSettings: generation.patchSettings }),- [generation]+ () => ({+ patchGenerateSettings: generation.patchSettings,+ resetDimensions: (values, projectId) => resetGenerateDims(store, values, projectId),+ }),+ [generation, store]);const { canManagePromptTemplates, canManageSharedSystemPrompts } = useCapabilities();const capabilitiesGroup = useMemo<GenerationUiAdapter['capabilities']>(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsxindex d8fd6865b3..c958aa8b15 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx@@ -2,6 +2,11 @@import type { GenerateSettings, MainModelConfig } from '@features/generation/core/types';import { ChakraProvider } from '@chakra-ui/react';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';import { createExternalStoreCore } from '@platform/state/externalStoreCore';import { system } from '@theme/system';@@ -9,7 +14,8 @@ import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';import { GenerateDimensionFields } from './GenerateDimensionFields';@@ -37,6 +43,11 @@ void i18n.use(initReactI18next).init({height: 'Height',lockAspectRatio: 'Lock aspect ratio',megapixelsValue: '{{value}} MP',+ resetSize: 'Reset size',+ resetSizeModelDefaults: 'Model defaults',+ resetSizeOptimalForCurrentRatio: 'Optimal size for current ratio',+ resetSizeOptimalForRatio: 'Optimal size for {{ratio}}',+ resetSizeSquareNative: 'Square at native size',size: 'Size',swapWidthAndHeight: 'Swap width and height',unlockAspectRatio: 'Unlock aspect ratio',@@ -62,28 +73,30 @@ const settle = (action: () => void): Promise<void> =>});});-const render = async (settings: Partial<GenerateSettings>) => {+const render = async (settings: Partial<GenerateSettings>, model: MainModelConfig = sd1Model) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);const onCommit = vi.fn();+ const onResetSize = vi.fn();await settle(() => {root?.render(<ChakraProvider value={system}><I18nextProvider i18n={i18n}><GenerateDimensionFields- draft={createExternalStoreCore({ ...getDefaultGenerateSettings(sd1Model), ...settings })}+ draft={createExternalStoreCore({ ...getDefaultGenerateSettings(model), ...settings })}projectId="project"- selectedModel={sd1Model}+ selectedModel={model}onCommit={onCommit}+ onResetSize={onResetSize}/></I18nextProvider></ChakraProvider>);});- return onCommit;+ return { onCommit, onResetSize };};const lockButton = () =>@@ -93,16 +106,18 @@ const lockButton = () =>const bracket = () => host?.querySelector('[data-part="bracket"]')?.parentElement ?? null;const presetTrigger = () => host?.querySelector<HTMLButtonElement>('[role="combobox"]') ?? null;-afterEach(async () => {+const unmountAndReset = async () => {await settle(() => root?.unmount());host?.remove();host = null;root = null;-});+};++afterEach(unmountAndReset);describe('GenerateDimensionFields aspect ratio', () => {it('reshapes the size to a chosen preset and locks it', async () => {- const onCommit = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 1024, width: 1024 });+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 1024, width: 1024 });expect(lockButton()?.getAttribute('aria-label')).toBe('Lock aspect ratio');expect(bracket()?.hasAttribute('data-locked')).toBe(false);@@ -121,7 +136,7 @@ describe('GenerateDimensionFields aspect ratio', () => {it('shows the lock engaged while a preset is selected and unlocking returns to Free', async () => {// A preset implies ratio lock even when the stored flag is false.- const onCommit = await render({+ const { onCommit } = await render({aspectRatioId: '16:9',aspectRatioIsLocked: false,aspectRatioValue: 16 / 9,@@ -145,7 +160,7 @@ describe('GenerateDimensionFields aspect ratio', () => {});it('locking in Free captures the current ratio', async () => {- const onCommit = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 800, width: 1024 });+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 800, width: 1024 });await settle(() => lockButton()?.click());@@ -160,7 +175,7 @@ describe('GenerateDimensionFields aspect ratio', () => {it('locking names the preset the current size already matches', async () => {// The same gesture in the canvas geometry form shows "4:3" for these dimensions.- const onCommit = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 768, width: 1024 });+ const { onCommit } = await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 768, width: 1024 });await settle(() => lockButton()?.click());@@ -174,7 +189,7 @@ describe('GenerateDimensionFields aspect ratio', () => {});it('swaps width and height and mirrors the preset', async () => {- const onCommit = await render({+ const { onCommit } = await render({aspectRatioId: '16:9',aspectRatioIsLocked: true,aspectRatioValue: 16 / 9,@@ -192,3 +207,155 @@ describe('GenerateDimensionFields aspect ratio', () => {});});});++describe('GenerateDimensionFields Reset size', () => {+ const resetSizeButton = () => host?.querySelector<HTMLButtonElement>('button[aria-label="Reset size"]') ?? null;+ const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ const menuItem = (label: string) => menuItems().find((item) => item.textContent?.startsWith(label)) ?? null;+ const openMenu = () => settle(() => resetSizeButton()?.click());+ // Zag selects on a real pointer release, which a synthetic click() does not send.+ const choose = async (label: string) => {+ const item = menuItem(label);+ if (!item) {+ throw new Error(`no "${label}" choice`);+ }+ await userEvent.click(item);+ await settle(() => undefined);+ };++ beforeEach(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ afterEach(() => {+ resetArchitectureCapabilities();+ });++ it('lists each choice with the size it sets and resets to a locked square at the native size', async () => {+ const { onCommit, onResetSize } = await render({+ aspectRatioId: '2:3',+ aspectRatioIsLocked: true,+ aspectRatioValue: 2 / 3,+ height: 768,+ width: 512,+ });++ await openMenu();++ // SD 1.5 is native at 512 on an 8px grid: 512² reshaped to 2:3 is 418×627, snapped to 416×624.+ expect(menuItems().map((item) => item.textContent)).toEqual([+ 'Square at native size512×512',+ 'Optimal size for 2:3416×624',+ ]);++ await choose('Square at native size');++ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({+ aspectRatioId: '1:1',+ aspectRatioIsLocked: true,+ aspectRatioValue: 1,+ height: 512,+ width: 512,+ });+ expect(onCommit).not.toHaveBeenCalled();+ });++ it('keeps an unlocked free ratio when resetting to its optimal size', async () => {+ const { onResetSize } = await render({+ aspectRatioId: 'Free',+ aspectRatioIsLocked: false,+ height: 400,+ width: 800,+ });++ await openMenu();+ // 512² at 2:1 is 724×362, snapped to 728×360.+ expect(menuItem('Optimal size for current ratio')?.textContent).toBe('Optimal size for current ratio728×360');++ await choose('Optimal size for current ratio');++ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 360, width: 728 });+ });++ it('names a locked free ratio in the app locale', async () => {+ i18n.addResourceBundle('de', 'translation', i18n.getResourceBundle('en', 'translation'));+ await i18n.changeLanguage('de');+ try {+ await render({+ aspectRatioId: 'Free',+ aspectRatioIsLocked: true,+ aspectRatioValue: 2.5,+ height: 400,+ width: 1000,+ });+ await openMenu();++ // 512² at 5:2 is 809.5×323.8, snapped to 808×320.+ expect(menuItem('Optimal size for 2,5:1')?.textContent).toBe('Optimal size for 2,5:1808×320');+ } finally {+ await i18n.changeLanguage('en');+ }+ });++ it('marks the applied choices current and disabled, and drops an optimal size that is the native square', async () => {+ await render({ aspectRatioId: '1:1', aspectRatioIsLocked: true, aspectRatioValue: 1, height: 512, width: 512 });++ await openMenu();++ const square = menuItem('Square at native size');+ expect(square?.getAttribute('aria-current')).toBe('true');+ expect(square?.getAttribute('aria-disabled')).toBe('true');+ expect(menuItems()).toHaveLength(1);+ await unmountAndReset();++ // The same size under a free ratio is not yet the locked square.+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: 1, height: 512, width: 512 });+ await openMenu();+ expect(menuItem('Square at native size')?.hasAttribute('aria-current')).toBe(false);+ expect(menuItem('Square at native size')?.hasAttribute('aria-disabled')).toBe(false);+ });++ it('offers model defaults only for a model that sets its own size', async () => {+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 512, width: 512 });+ await openMenu();+ expect(menuItem('Model defaults')).toBeNull();+ await unmountAndReset();++ const sizedModel: MainModelConfig = { ...sd1Model, default_settings: { height: 768, width: 640 } };+ const { onResetSize } = await render(+ { aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 512, width: 512 },+ sizedModel+ );+ await openMenu();+ expect(menuItem('Model defaults')?.textContent).toBe('Model defaults640×768');++ await choose('Model defaults');++ expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 768, width: 640 });+ });++ it('opens from the keyboard and applies the highlighted choice', async () => {+ const { onResetSize } = await render({+ aspectRatioId: '2:3',+ aspectRatioIsLocked: true,+ aspectRatioValue: 2 / 3,+ height: 768,+ width: 512,+ });++ resetSizeButton()?.focus();+ await userEvent.keyboard('{Enter}');+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('role')).toBe('menu'));+ await userEvent.keyboard('{ArrowDown}');+ await userEvent.keyboard('{ArrowDown}');+ await userEvent.keyboard('{Enter}');++ await vi.waitFor(() => expect(onResetSize).toHaveBeenCalledExactlyOnceWith({ height: 624, width: 416 }));+ });++ it('has no footer optimal-size button', async () => {+ await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, height: 384, width: 384 });++ expect(host?.textContent).not.toContain('Set optimal size');+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsxindex ec98116da2..8e9533fe1c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx@@ -1,7 +1,7 @@/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { AspectRatioId, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { Badge, Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { Badge, Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { getDefaultGenerateSettings, getGenerationDimensions } from '@features/generation/core/baseGenerationPolicies';import {ASPECT_RATIO_MAP,@@ -13,9 +13,11 @@ import {MIN_DIMENSION,} from '@features/generation/core/settings';import { useExternalStoreSelector } from '@platform/state/selectors';-import { Button, IconButton, Tooltip } from '@platform/ui';+import { IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';import { ScrubberField } from '@platform/ui/ScrubberField';-import { ArrowLeftRightIcon, LockIcon } from 'lucide-react';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { ArrowLeftRightIcon, CheckIcon, LockIcon, RotateCcwIcon } from 'lucide-react';import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -35,6 +37,8 @@ interface GenerateDimensionFieldsProps {projectId: string;selectedModel: GenerateModelConfig | undefined;onCommit: (patch: Partial<GenerateSettings>) => void;+ /** Applies a Reset size choice at once; on the canvas it resizes the frame around its centre. */+ onResetSize: (patch: Partial<GenerateSettings>) => void;}type Dimensions = Pick<GenerateSettings, 'height' | 'width'>;@@ -84,6 +88,75 @@ const PREVIEW_PAD_PX = 10;const clampToRange = (value: number): number => Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, value));+/** Whether the model sets a size of its own; otherwise its defaults are just the architecture's optimal size. */+const hasModelDefaultSize = (model: GenerateModelConfig | undefined): boolean => {+ const defaults = model?.default_settings;++ return Number.isFinite(defaults?.width) || Number.isFinite(defaults?.height);+};++const RESET_SIZE_MENU_POSITIONING = { placement: 'bottom-end' } as const;++interface ResetSizeChoice {+ value: string;+ label: string;+ size: Dimensions;+ /** Already applied: shown checked and disabled. */+ isCurrent: boolean;+ onSelect: () => void;+}++/** The ratio row's Reset size menu; each choice shows the size it sets. */+const ResetSizeMenu = ({ choices }: { choices: readonly ResetSizeChoice[] }) => {+ const { t } = useTranslation();+ const ids = useTooltipTriggerIds();+ const label = t('widgets.generate.resetSize');++ return (+ <Menu.Root ids={ids} positioning={RESET_SIZE_MENU_POSITIONING}>+ <Menu.Trigger asChild>+ <Tooltip content={label} ids={ids}>+ <IconButton aria-label={label} size="sm" variant="outline">+ <RotateCcwIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="15rem">+ {choices.map((choice) => (+ <Menu.Item+ key={choice.value}+ aria-current={choice.isCurrent ? 'true' : undefined}+ disabled={choice.isCurrent}+ value={choice.value}+ onSelect={choice.onSelect}+ >+ <HStack gap="2" minW="0" w="full">+ <Icon+ as={CheckIcon}+ aria-hidden+ boxSize="3.5"+ color="fg.subtle"+ flexShrink={0}+ opacity={choice.isCurrent ? 1 : 0}+ />+ <Text flex="1" fontSize="md" truncate>+ {choice.label}+ </Text>+ <Text color="fg.subtle" flexShrink={0} fontSize="sm" fontVariantNumeric="tabular-nums">+ {`${choice.size.width}×${choice.size.height}`}+ </Text>+ </HStack>+ </Menu.Item>+ ))}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};+/** Respect ratio lock during drag and snap to the grid on release; arrow keys move by one grid step. */const SizePreview = ({current,@@ -255,10 +328,11 @@ const selectDimensionSettings = pickGenerateSettings([export const GenerateDimensionFields = ({draft,onCommit,+ onResetSize,projectId,selectedModel,}: GenerateDimensionFieldsProps) => {- const { t } = useTranslation();+ const { i18n, t } = useTranslation();const { CanvasRenderSize: CanvasRenderSizeSlot, project } = useGenerationUi();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectDimensionSettings);const secondsPerRun = useGenerationQueueInsights(selectSecondsPerRun);@@ -399,16 +473,84 @@ export const GenerateDimensionFields = ({});};- const optimizeSize = () => {- const optimal = dimensions.optimal;- const ratio = isRatioConstrained- ? getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })- : displayDimensions.height > 0- ? displayDimensions.width / displayDimensions.height- : 1;+ const resetSize = (patch: Partial<GenerateSettings>) => {+ pendingDimensionsRef.current = null;+ setDraftDimensions(null);+ onResetSize(patch);+ };- commitSettings(calculateNewSize(ratio, optimal * optimal, dimensionGrid));+ const nativeSide = clampDimension(dimensions.optimal, dimensionGrid);+ const optimalRatio = isRatioConstrained+ ? getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })+ : dimensionRatio;+ // The model's pixel budget reshaped to the ratio the section holds.+ const optimalSize = calculateNewSize(optimalRatio, dimensions.optimal * dimensions.optimal, dimensionGrid);+ const isAtSize = (size: Dimensions) =>+ displayDimensions.width === size.width && displayDimensions.height === size.height;+ // A preset by its name and a locked free ratio as `W:1`; an unlocked free ratio is just whatever the size is now.+ const optimalLabel =+ settings.aspectRatioId !== 'Free'+ ? t('widgets.generate.resetSizeOptimalForRatio', { ratio: settings.aspectRatioId })+ : settings.aspectRatioIsLocked+ ? t('widgets.generate.resetSizeOptimalForRatio', {+ ratio: `${new Intl.NumberFormat(i18n.resolvedLanguage, { maximumFractionDigits: 2 }).format(optimalRatio)}:1`,+ })+ : t('widgets.generate.resetSizeOptimalForCurrentRatio');++ const resetToModelDefaults = () => {+ if (modelDefaults) {+ resetSize({ height: modelDefaults.height, width: modelDefaults.width });+ }};+ // Only a size the model sets itself is worth offering; otherwise its defaults are the native square.+ const modelDefaultSize =+ modelDefaults && hasModelDefaultSize(selectedModel)+ ? { height: modelDefaults.height, width: modelDefaults.width }+ : null;++ const resetSizeChoices: readonly ResetSizeChoice[] = [+ {+ isCurrent:+ isAtSize({ height: nativeSide, width: nativeSide }) &&+ settings.aspectRatioId === '1:1' &&+ settings.aspectRatioIsLocked,+ label: t('widgets.generate.resetSizeSquareNative'),+ // The field set choosing the 1:1 preset writes.+ onSelect: () =>+ resetSize({+ aspectRatioId: '1:1',+ aspectRatioIsLocked: true,+ aspectRatioValue: 1,+ height: nativeSide,+ width: nativeSide,+ }),+ size: { height: nativeSide, width: nativeSide },+ value: 'square-native',+ },+ // A square ratio's optimal size is the native square, which the first choice already sets.+ ...(optimalSize.width === nativeSide && optimalSize.height === nativeSide+ ? []+ : [+ {+ isCurrent: isAtSize(optimalSize),+ label: optimalLabel,+ onSelect: () => resetSize(optimalSize),+ size: optimalSize,+ value: 'optimal-for-ratio',+ },+ ]),+ ...(modelDefaultSize+ ? [+ {+ isCurrent: isAtSize(modelDefaultSize),+ label: t('widgets.generate.resetSizeModelDefaults'),+ onSelect: resetToModelDefaults,+ size: modelDefaultSize,+ value: 'model-defaults',+ },+ ]+ : []),+ ];// The recommendation reshapes the model's pixel budget to the live aspect ratio.const recommendedDimensions = calculateNewSize(@@ -416,9 +558,6 @@ export const GenerateDimensionFields = ({dimensions.optimal * dimensions.optimal,dimensionGrid);- const isAtRecommendedSize =- displayDimensions.width === recommendedDimensions.width &&- displayDimensions.height === recommendedDimensions.height;const frameLabel = `${displayDimensions.width}x${displayDimensions.height}`;// The optimal-side stop is scalar; recommended dimensions preserve the live ratio.@@ -443,12 +582,9 @@ export const GenerateDimensionFields = ({const isResized = renderSize.width !== displayDimensions.width || renderSize.height !== displayDimensions.height;const isAtRecommendedRenderSize =renderSize.width === recommendedDimensions.width && renderSize.height === recommendedDimensions.height;- // In canvas mode, resizing the frame only adds something while it renders at its own size: Auto has not already- // grown it toward the optimum and Custom has not set a size of its own.- const offersOptimalSize = !isAtRecommendedSize && !isResized;const footer = (- <HStack gap="2" justify="space-between" minH="5" mt="auto">+ <HStack gap="2" minH="5" mt="auto"><Text color="fg.muted" fontSize="xs">{isResized ? `${renderSize.width}×${renderSize.height} · ` : ''}{t('widgets.generate.megapixelsValue', {@@ -460,13 +596,6 @@ export const GenerateDimensionFields = ({? ` · ${t('widgets.generate.secondsPerRun', { value: Math.round(secondsPerRun) })}`: ''}</Text>- {offersOptimalSize ? (- <Tooltip content={t('widgets.generate.setOptimalSizeDescription')}>- <Button color="fg.muted" size="sm" variant="ghost" onClick={optimizeSize}>- {t('widgets.generate.setOptimalSize')}- </Button>- </Tooltip>- ) : null}</HStack>);@@ -497,14 +626,7 @@ export const GenerateDimensionFields = ({displayDimensions.width === modelDefaults.width &&displayDimensions.height === modelDefaults.height}- onReset={- modelDefaults- ? () => {- setDraftDimensions(null);- commitDimensions({ height: modelDefaults.height, width: modelDefaults.width });- }- : undefined- }+ onReset={modelDefaults ? resetToModelDefaults : undefined}><HStack alignItems="center" gap="1"><Stack flex="1" gap={DIMENSION_ROW_GAP} minW="0">@@ -526,6 +648,7 @@ export const GenerateDimensionFields = ({value={settings.aspectRatioId}onChange={setAspectRatioId}/>+ <ResetSizeMenu choices={resetSizeChoices} /><Box css={SWAP_COLUMN_CSS}><Tooltip content={t('widgets.generate.swapWidthAndHeight')}><IconButtondiff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsxindex 4c83f094b9..817ee66baf 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx@@ -141,6 +141,7 @@ let root: Root | null = null;let queryClient = new QueryClient();let projectValues = new Map<string, ExternalStoreCore<Record<string, unknown>>>();let patches: Array<{ patch: Record<string, unknown>; projectId: string | undefined }> = [];+let sizeResets: Array<{ patch: Record<string, unknown>; projectId: string | undefined }> = [];(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const storedValues = (projectId = 'project-1') => {@@ -184,6 +185,10 @@ const createStableGroups = () => ({patches.push({ patch, projectId });storedValues(projectId).patchSnapshot(patch);},+ resetDimensions: (patch: Record<string, unknown>, projectId?: string) => {+ sizeResets.push({ patch, projectId });+ storedValues(projectId).patchSnapshot(patch);+ },},});let stableGroups = createStableGroups();@@ -279,6 +284,7 @@ beforeEach(async () => {['project-2', createExternalStoreCore<Record<string, unknown>>({ ...INITIAL_VALUES, steps: 50 })],]);patches = [];+ sizeResets = [];stableGroups = createStableGroups();// Seeded, never-stale reads keep late responses from landing inside a counted window.queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });@@ -510,6 +516,40 @@ describe('GenerateSettingsForm render isolation', () => {expect(patches).toEqual([{ patch: { steps: 31 }, projectId: 'project-1' }]);});+ it('applies a size reset at once, superseding a pending size edit that can then never land after it', async () => {+ await settle(() =>+ storedValues().patchSnapshot({+ aspectRatioId: '2:3',+ aspectRatioIsLocked: true,+ aspectRatioValue: 2 / 3,+ height: 1216,+ width: 832,+ })+ );+ await settle(() =>+ host!.querySelector<HTMLButtonElement>('button[aria-label="widgets.generate.resetSize"]')?.click()+ );+ const menu = document.querySelector<HTMLElement>('[role="menu"]');+ // Highlights the first choice, Square at native size.+ await settle(() => menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));++ // A width step still inside its debounce window, then the reset.+ await settle(() => {+ sliderNamed('widgets.generate.width').dispatchEvent(+ new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' })+ );+ menu?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));+ });+ await settle(noop, 400);++ // SDXL is native at 1024.+ expect(sizeResets).toEqual([+ { patch: { aspectRatioId: '1:1', aspectRatioValue: 1, height: 1024, width: 1024 }, projectId: 'project-1' },+ ]);+ expect(patches).toEqual([]);+ expect(storedValues().getSnapshot()).toMatchObject({ aspectRatioIsLocked: true, height: 1024, width: 1024 });+ });+it('batches fast edits to several fields into one patch on the project they were made in', async () => {await stepSteps();await stepSteps();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsxindex 981f5770eb..3a6e328efd 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx@@ -24,6 +24,7 @@ import { GenerateGuidanceSection } from './GenerateGuidanceSection';import { GenerateModelCard } from './GenerateModelCard';import { GenerateRefinerSection } from './GenerateRefinerSection';import { GenerateRenderSection } from './GenerateRenderSection';+import { useGenerationUi } from './GenerationUiContext';import { GeneratePromptFields } from './promptFields';const GENERATE_INPUT_DEBOUNCE_MS = 250;@@ -54,6 +55,7 @@ export const GenerateSettingsForm = ({settings,supportedModels,}: GenerateSettingsFormProps) => {+ const { resetDimensions } = useGenerationUi().settings;const [draft] = useState(() => createExternalStoreCore(settings));const latestSettingsRef = useRef(settings);const pendingUpdateRef = useRef<PendingGenerateSettingsUpdate>(null);@@ -215,8 +217,9 @@ export const GenerateSettingsForm = ({[draft, onCommitSettings]);- const commitPatchImmediately = useCallback(- (patch: Partial<GenerateSettings>) => {+ /** Folds pending edits under `patch` and hands the change to `send` now, so no late debounce can follow it. */+ const sendPatchNow = useCallback(+ (patch: Partial<GenerateSettings>, send: (patch: Partial<GenerateSettings>, projectId: string) => void) => {const previousSettings = latestSettingsRef.current;const nextSettings = applyGenerateSettingsPatch(applyGenerateSettingsUpdate(latestSettingsRef.current, pendingUpdateRef.current),@@ -231,9 +234,19 @@ export const GenerateSettingsForm = ({pendingUpdateRef.current = null;latestSettingsRef.current = nextSettings;draft.setSnapshot(nextSettings);- onPatchSettings(getChangedGenerateSettingsPatch(previousSettings, nextSettings), projectIdRef.current);+ send(getChangedGenerateSettingsPatch(previousSettings, nextSettings), projectIdRef.current);},- [draft, onPatchSettings]+ [draft]+ );++ const commitPatchImmediately = useCallback(+ (patch: Partial<GenerateSettings>) => sendPatchNow(patch, onPatchSettings),+ [onPatchSettings, sendPatchNow]+ );++ const commitSizeReset = useCallback(+ (patch: Partial<GenerateSettings>) => sendPatchNow(patch, resetDimensions),+ [resetDimensions, sendPatchNow]);return (@@ -259,7 +272,13 @@ export const GenerateSettingsForm = ({onCommitImmediate={commitPatchImmediately}/>- <GenerateDimensionFields draft={draft} projectId={projectId} selectedModel={selectedModel} onCommit={commit} />+ <GenerateDimensionFields+ draft={draft}+ projectId={projectId}+ selectedModel={selectedModel}+ onCommit={commit}+ onResetSize={commitSizeReset}+ /><GenerateGuidanceSectiondraft={draft}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxindex 7afd6d613f..b8dc40d7f9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -166,6 +166,11 @@ export interface GenerationUiAdapter {};settings: {patchGenerateSettings(values: Partial<GenerateSettings>, projectId?: string, origin?: 'user' | 'system'): void;+ /**+ * Applies a Reset size choice: the same patch, marked as a reset so a surface that frames the size (the canvas)+ * can keep its centre rather than its top-left. Generation does not know which surface that is.+ */+ resetDimensions(values: Partial<GenerateSettings>, projectId?: string): void;};}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.tsnew file mode 100644index 0000000000..1170641317--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.ts@@ -0,0 +1,78 @@+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type { LayerExportGuard } from '@workbench/canvas-engine/engine';++import { createCanvasOperationController } from '@workbench/canvas-operations/operationController';+import { createCanvasOperationStores } from '@workbench/canvas-operations/operationStores';+import { describe, expect, it, vi } from 'vitest';++import type { CanvasSelectObjectCoordinatorDeps } from './contracts';++import { createSelectObjectOperationCoordinator } from './SelectObjectCoordinator';++const layer: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: 'source',+ isEnabled: true,+ isLocked: false,+ name: 'Source',+ opacity: 1,+ source: { fill: '#fff', height: 12, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 16 },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+};+const guard: LayerExportGuard = { cacheVersion: 1, documentGeneration: 1, layer, layerId: layer.id, projectId: 'p1' };++const createCoordinator = (readAutoProcessPreference: () => boolean) => {+ const stores = createCanvasOperationStores();+ const deps: CanvasSelectObjectCoordinatorDeps = {+ captureGuard: () => guard,+ clearOtherOperation: vi.fn(),+ clearPreview: vi.fn(),+ commitGenerated: vi.fn(),+ commitMask: vi.fn(),+ controller: createCanvasOperationController({ isGuardCurrent: (candidate) => candidate === guard }),+ decodePreview: vi.fn(),+ exportSource: vi.fn(),+ invalidateOverlay: vi.fn(),+ isGuardCurrent: (candidate) => candidate === guard,+ isInteractionLocked: () => false,+ isSamToolActive: () => true,+ prepareStart: () => ({+ guard,+ layerId: layer.id,+ layerName: layer.name,+ layerType: 'raster',+ sourceRect: { height: 12, width: 16, x: 0, y: 0 },+ status: 'ready',+ }),+ projectId: 'p1',+ publishPreview: vi.fn(),+ readAutoProcessPreference,+ replaceSelection: vi.fn(),+ replaceTemporaryRestoreTool: vi.fn(),+ runGraph: vi.fn(),+ selectLayer: vi.fn(),+ setSamTool: vi.fn(),+ setViewTool: vi.fn(),+ stores,+ uploadIntermediate: vi.fn(),+ };+ return { coordinator: createSelectObjectOperationCoordinator(deps), stores };+};++describe('createSelectObjectOperationCoordinator', () => {+ it('starts each session from the Auto Process preference as it stands at that start', () => {+ let preference = true;+ const { coordinator, stores } = createCoordinator(() => preference);++ expect(coordinator.start(layer.id)).toBe('started');+ expect(stores.samSession.get()?.autoProcess).toBe(true);++ coordinator.cancel();+ preference = false;++ expect(coordinator.start(layer.id)).toBe('started');+ expect(stores.samSession.get()?.autoProcess).toBe(false);+ coordinator.cancel();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.tsindex fa8c23587d..e496c27ab7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts@@ -224,6 +224,7 @@ export const createSelectObjectOperationCoordinator = (runGraph: deps.runGraph,uploadIntermediate: deps.uploadIntermediate,},+ initialAutoProcess: deps.readAutoProcessPreference?.() ?? false,operation,});const installed = session;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.tsindex af4ae913e8..aad565317a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts@@ -196,6 +196,8 @@ export interface CanvasSelectObjectCoordinatorDeps {readonly controller: CanvasOperationController;readonly projectId: string;isInteractionLocked(): boolean;+ /** Reads the account's Auto Process preference when a session starts; absent means off. */+ readAutoProcessPreference?(): boolean;prepareStart(layerId: string): SelectObjectStartContext;selectLayer(layerId: string): void;clearOtherOperation(): void;@@ -384,6 +386,7 @@ export interface CreateSelectObjectSessionOptions<T> {cleanupPreview(): void;isGuardCurrent(guard: LayerExportGuard): boolean;};+ initialAutoProcess?: boolean;operation: CanvasOperationSession;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.tsindex c92f73125a..ed4a55b6f2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts@@ -27,6 +27,8 @@ export interface CanvasEngineOptions extends Omit<*/ensureProjectOnServer(): Promise<void>;getMainModelBase?: () => string | null;+ /** The account's Select Object Auto Process preference; the widget layer injects the settings read. */+ readSelectObjectAutoProcess?: () => boolean;selectObjectDeps?: {uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;runGraph(options: {@@ -63,7 +65,7 @@ export type CanvasEngine = CoreCanvasEngineImplementation;/** Application composition root: owns SAM/filter sessions, queues, uploads, and their core capability adapters. */export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine => {- const { ensureProjectOnServer, filterDeps, selectObjectDeps, ...coreOptions } = options;+ const { ensureProjectOnServer, filterDeps, readSelectObjectAutoProcess, selectObjectDeps, ...coreOptions } = options;const owner = captureAccountScope();const uploadLifetime = new AbortController();let projectMissingAt = -Infinity;@@ -164,6 +166,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =isSamToolActive: host.isSamToolActive,prepareStart: host.prepareSelectObjectStart,projectId: options.projectId,+ readAutoProcessPreference: readSelectObjectAutoProcess,publishPreview: (preview) => host.publishSamPreview(preview),replaceSelection: (preview, signal) => host.replaceSelection(preview.guard, preview.image, preview.rect, signal),replaceTemporaryRestoreTool: host.replaceTemporaryRestoreTool,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.tsindex 2e4d48eb14..e9e6035117 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts@@ -44,7 +44,10 @@ const deferred = <T>() => {return { promise, resolve };};-const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {}) => {+const createHarness = (+ overrides: Partial<SelectObjectSessionDeps<string>> = {},+ { initialAutoProcess }: { initialAutoProcess?: boolean } = {}+) => {let currentGuard: LayerExportGuard | null = guard;let controllerSubscriber: (() => void) | null = null;const unsubscribe = vi.fn();@@ -84,7 +87,7 @@ const createHarness = (overrides: Partial<SelectObjectSessionDeps<string>> = {})if (!operation) {throw new Error('expected Select Object operation');}- const session = createSelectObjectSession({ deps, operation });+ const session = createSelectObjectSession({ deps, initialAutoProcess, operation });session.update({ input: { prompt: 'cat', type: 'prompt' } });return {controller,@@ -575,6 +578,17 @@ describe('createSelectObjectSession', () => {expect(harness.session.getSnapshot().sourceGuard).toBe(replacementGuard);});+ it('starts from the seeded auto-process preference and runs the first valid input after the debounce', async () => {+ vi.useFakeTimers();+ const harness = createHarness({}, { initialAutoProcess: true });++ expect(harness.session.getSnapshot()).toMatchObject({ autoProcess: true, status: 'scheduled' });+ await vi.advanceTimersByTimeAsync(999);+ expect(harness.deps.exportSource).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());+ });+it('debounces auto-processing for one second and manual processing runs immediately', async () => {vi.useFakeTimers();const harness = createHarness();@@ -860,7 +874,7 @@ describe('createSelectObjectSession', () => {expect(harness.session.getSnapshot()).toMatchObject({ preview: null, sourceGuard: null, status: 'ready' });});- it('reset cancels work and scheduling, clears preview/cache, and restores defaults', async () => {+ it('reset cancels work and scheduling, clears preview/cache, and restores defaults except auto-process', async () => {vi.useFakeTimers();const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();const harness = createHarness({ runGraph: vi.fn(() => graph.promise) });@@ -874,7 +888,7 @@ describe('createSelectObjectSession', () => {await expect(pending).resolves.toBe('stale');expect(harness.session.getSnapshot()).toEqual({applyPolygonRefinement: false,- autoProcess: false,+ autoProcess: true,error: null,input: { prompt: '', type: 'prompt' },invert: false,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.tsindex ef80c6b04c..1aadbf0cb5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts@@ -62,6 +62,8 @@ export interface SelectObjectSessionDeps<T> {export interface CreateSelectObjectSessionOptions<T> {deps: SelectObjectSessionDeps<T>;+ /** Auto Process is an account preference; the session starts from it and Reset keeps it. */+ initialAutoProcess?: boolean;operation: CanvasOperationSession;}@@ -86,9 +88,9 @@ export interface SelectObjectSession<T> {dispose(): void;}-const defaultState = <T>(): SelectObjectSessionState<T> => ({+const defaultState = <T>(autoProcess: boolean): SelectObjectSessionState<T> => ({applyPolygonRefinement: false,- autoProcess: false,+ autoProcess,error: null,input: { prompt: '', type: 'prompt' },invert: false,@@ -161,7 +163,7 @@ class SamSessionFailure extends Error {export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOptions<T>): SelectObjectSession<T> => {const { deps, operation } = options;- let state = defaultState<T>();+ let state = defaultState<T>(options.initialAutoProcess ?? false);let source: SelectObjectPreparedSource | null = null;let requestToken = 0;let lastPublishedHash: string | null = null;@@ -529,7 +531,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOoperation.reset();source = null;lastPublishedHash = null;- publishState(defaultState<T>());+ publishState(defaultState<T>(state.autoProcess));},subscribe: (listener) => {if (disposed) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsindex 1d82499ae7..5078e3f02f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@ -5,6 +5,7 @@ import { galleryImageUrls } from '@features/gallery/utility';import { getModelsSnapshot } from '@features/models';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';+import { getWorkbenchPreferences } from '@workbench/settings/store';import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';import {@@ -100,6 +101,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {imageResolver: createImageResolver(),fonts,mutationPort: createCanvasProjectMutationPort(store, projectId),+ readSelectObjectAutoProcess: () => getWorkbenchPreferences().selectObjectAutoProcess,reportError: notifications.reportError,}),[fonts, liveEngines, notifications.reportError, persistence, projectId, store]diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 4e8cd173d1..d3310b821e 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -9,11 +9,17 @@ import {architectureCapabilitiesFixture,seedArchitectureCapabilities,} from '@features/generation/core/architectureCapabilities.testing';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import type { CanvasProjectMutation } from './canvasProjectMutations';-import { type CanvasDimsSnapshot, createCanvasDimsSync, reconcileCanvasDims } from './canvasDimsSync';+import {+ type CanvasDimsSnapshot,+ createCanvasDimsSync,+ reconcileCanvasDims,+ resetGenerateDims,+ resizeBboxAroundCentre,+} from './canvasDimsSync';import { getProjectWidgetValues } from './widgetState';import { createWorkbenchStore } from './workbenchStore';@@ -265,6 +271,82 @@ const setupCanvasStore = () => {return { getSyncDispatches: () => syncDispatches, store, sync };};+describe('resizeBboxAroundCentre (pure)', () => {+ it('keeps the centre of the frame', () => {+ // Centre (516, 708); a 1024 square around it starts at (4, 196).+ expect(resizeBboxAroundCentre(bbox(832, 1216, 100, 100), { height: 1024, width: 1024 })).toEqual(+ bbox(1024, 1024, 4, 196)+ );+ });++ it('rounds a half-pixel offset from an odd size difference to whole pixels', () => {+ // 10 + (513 - 512) / 2 = 10.5 and 20 + (512 - 515) / 2 = 18.5.+ expect(resizeBboxAroundCentre(bbox(513, 512, 10, 20), { height: 515, width: 512 })).toEqual(bbox(512, 515, 11, 19));+ // -0.5 rounds to zero, not negative zero.+ expect(resizeBboxAroundCentre(bbox(513, 512, 0, 0), { height: 512, width: 514 }).x).toBe(0);+ });+});++describe('resetGenerateDims (wiring)', () => {+ seedArchitectureCapabilities();++ const SQUARE_RESET = {+ aspectRatioId: '1:1',+ aspectRatioIsLocked: true,+ aspectRatioValue: 1,+ height: 1024,+ width: 1024,+ } as const;++ it('resizes the canvas frame around its centre with system writes only, then settles', () => {+ const { store, sync } = setupCanvasStore();+ dispatchCanvas(store, { bbox: { height: 1216, width: 832, x: 100, y: 100 }, type: 'setCanvasBbox' });+ const apply = vi.spyOn(store.commands.canvas, 'apply');++ resetGenerateDims(store, SQUARE_RESET);++ const { bbox: nextBbox, values } = getActiveGenerate(store.getState());+ expect(nextBbox).toEqual({ height: 1024, width: 1024, x: 4, y: 196 });+ expect(values).toMatchObject(SQUARE_RESET);+ expect(store.getState().projects[0]?.invocation.sourceId).toBe('canvas');+ // Frame writes stay out of canvas history.+ expect(apply.mock.calls.length).toBeGreaterThan(0);+ for (const call of apply.mock.calls) {+ expect(call[2]).toBe('system');+ }++ // Frame and size now agree, so the next reconciliation writes nothing.+ apply.mockClear();+ store.commands.generation.patchSettings({ steps: 31 });+ expect(apply).not.toHaveBeenCalled();+ expect(getActiveGenerate(store.getState()).bbox).toEqual({ height: 1024, width: 1024, x: 4, y: 196 });++ // A later size edit keeps the top-left as before.+ store.commands.generation.patchSettings({ width: 512 });+ expect(getActiveGenerate(store.getState()).bbox).toEqual({ height: 1024, width: 512, x: 4, y: 196 });+ sync.dispose();+ });++ it('changes only the fields when the project is not generating into the canvas', () => {+ const store = createWorkbenchStore();+ store.commands.generation.setSource('generate');+ store.commands.generation.toggleSourceLock();+ store.commands.generation.patchSettings({ height: 1216, model, modelKey: model.key, width: 832 });+ dispatchCanvas(store, { bbox: { height: 1216, width: 832, x: 100, y: 100 }, type: 'setCanvasBbox' });+ const sync = createCanvasDimsSync(store);+ const apply = vi.spyOn(store.commands.canvas, 'apply');++ resetGenerateDims(store, SQUARE_RESET);++ expect(getActiveGenerate(store.getState())).toMatchObject({+ bbox: { height: 1216, width: 832, x: 100, y: 100 },+ values: SQUARE_RESET,+ });+ expect(apply).not.toHaveBeenCalled();+ sync.dispose();+ });+});+describe('createCanvasDimsSync (wiring)', () => {seedArchitectureCapabilities();diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.tsindex 97f05db48b..13c33a0a6c 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.ts@@ -122,6 +122,48 @@ export const reconcileCanvasDims = ({return { kind: 'none' };};+/** The frame resized to `size` around its centre; the position rounds to whole pixels. */+export const resizeBboxAroundCentre = (bbox: Bbox, size: Pick<Bbox, 'height' | 'width'>): Bbox => ({+ height: size.height,+ width: size.width,+ // `+ 0` folds the -0 that rounding a small negative offset yields.+ x: Math.round(bbox.x + (bbox.width - size.width) / 2) + 0,+ y: Math.round(bbox.y + (bbox.height - size.height) / 2) + 0,+});++/**+ * Applies a Generate size reset. On a project generating into the canvas, the frame then keeps its centre rather than+ * its top-left: the patch lands first, the sync resizes the frame at its top-left as for any size edit, and the centred+ * frame replaces that in the same turn. The patch is a person's edit like any other; the frame writes are `system`, so+ * canvas history records none of them.+ */+export const resetGenerateDims = (+ store: Pick<CanvasDimsSyncStore, 'commands' | 'getState'>,+ values: Parameters<WorkbenchCommands['generation']['patchSettings']>[0],+ projectId?: string+): void => {+ const findProject = () => {+ const state = store.getState();+ const targetId = projectId ?? state.activeProjectId;+ return state.projects.find((candidate) => candidate.id === targetId);+ };+ const before = findProject();+ const anchor = before?.invocation.sourceId === 'canvas' ? before.canvas.document.bbox : null;++ store.commands.generation.patchSettings(values, projectId);++ const after = findProject();+ if (!anchor || !after || after.invocation.sourceId !== 'canvas') {+ return;+ }+ // The sync has snapped the frame to the model grid; centre that size rather than the raw values.+ const current = after.canvas.document.bbox;+ const centred = resizeBboxAroundCentre(anchor, current);+ if (centred.x !== current.x || centred.y !== current.y) {+ store.commands.canvas.apply(after.id, { bbox: centred, type: 'setCanvasBbox' }, 'system');+ }+};+/** The minimal workbench store surface the sync depends on. */export interface CanvasDimsSyncStore {commands: {diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex b173db5d85..1c3cf99d1a 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -92,6 +92,8 @@ export interface WorkbenchPreferences {workflowEdgesBehindNodes: boolean;/** Raise text and border contrast on every theme (a11y). */highContrast: boolean;+ /** Select Object processes each prompt edit automatically; kept across sessions, Reset, and reloads. */+ selectObjectAutoProcess: boolean;/** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */customHotkeys: Record<string, string[]>;/** Generate panel section open/closed overrides keyed by section id; absent = section default. */diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex b04734654e..2579ca9b39 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -395,6 +395,16 @@ describe('normalizeWorkbenchPreferences appearance', () => {});});+describe('normalizeWorkbenchPreferences canvas operations', () => {+ it('keeps Select Object auto-process off unless it was stored as on', () => {+ expect(store.normalizeWorkbenchPreferences({}).selectObjectAutoProcess).toBe(false);+ expect(+ store.normalizeWorkbenchPreferences({ selectObjectAutoProcess: 'true' as never }).selectObjectAutoProcess+ ).toBe(false);+ expect(store.normalizeWorkbenchPreferences({ selectObjectAutoProcess: true }).selectObjectAutoProcess).toBe(true);+ });+});+describe('normalizeWorkbenchPreferences workflow editor', () => {it('keeps connections above nodes unless the preference is explicitly on', () => {expect(store.normalizeWorkbenchPreferences({}).workflowEdgesBehindNodes).toBe(false);diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 7bf67bbeda..3841b16a90 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -69,6 +69,7 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {promptFontSize: 'default',queueJobsScope: 'all',reduceMotion: false,+ selectObjectAutoProcess: false,showPromptSyntaxHighlighting: true,showFocusRegionHighlight: true,themeId: DEFAULT_THEME_ID,@@ -356,6 +357,10 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferences: DEFAULT_PREFERENCES.alphaNoticeAcknowledged,reduceMotion:typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion,+ selectObjectAutoProcess:+ typeof preferences?.selectObjectAutoProcess === 'boolean'+ ? preferences.selectObjectAutoProcess+ : DEFAULT_PREFERENCES.selectObjectAutoProcess,showFocusRegionHighlight:typeof preferences?.showFocusRegionHighlight === 'boolean'? preferences.showFocusRegionHighlightdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsxindex 8cf3479aa8..db4e397371 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx@@ -136,6 +136,7 @@ const renderSizeSection = async (project: HarnessProject) => {projectId="project"selectedModel={SD1_MODEL}onCommit={vi.fn()}+ onResetSize={vi.fn()}/>);};@@ -148,7 +149,7 @@ const badgeText = () =>)?.textContent;const statusText = () =>[...(host?.querySelectorAll('p') ?? [])].find((element) => element.textContent?.includes('MP'))?.textContent;-const optimalSizeButton = () => page.getByRole('button', { name: 'Set optimal size' });+const resetSizeButton = () => page.getByRole('button', { name: 'Reset size' });const renderAt = () => page.getByRole('combobox', { name: 'Render at' });/** The dashed ghost in the size preview, in preview pixels. */@@ -336,26 +337,14 @@ describe('Size section in canvas mode', () => {await expect.element(width).toHaveValue('1608');});- it('offers the optimal frame size only while the frame renders at its own size', async () => {- // An undersized frame: Auto grows it and Custom sets its own, so resizing the frame adds nothing.+ it('offers the Reset size menu in every render mode, without a footer optimal-size button', async () => {await renderSizeSection(createProject({ frame: { height: 384, width: 384 }, model: SD1_MODEL }));- await expect.element(optimalSizeButton()).not.toBeInTheDocument();+ await expect.element(resetSizeButton()).toBeInTheDocument();await chooseRenderAt('Custom');- await expect.element(optimalSizeButton()).not.toBeInTheDocument();+ await expect.element(resetSizeButton()).toBeInTheDocument();await chooseRenderAt('Frame size');- await expect.element(optimalSizeButton()).toBeInTheDocument();- await unmount();-- // An oversized frame: Auto never shrinks it.- await renderSizeSection(createProject({ frame: { height: 768, width: 768 }, model: SD1_MODEL }));- await expect.element(optimalSizeButton()).toBeInTheDocument();- await unmount();-- // A frame already at the recommended size has nothing to offer in any mode.- await renderSizeSection(- createProject({ canvas: { scaleMethod: 'none' }, frame: { height: 512, width: 512 }, model: SD1_MODEL })- );- await expect.element(optimalSizeButton()).not.toBeInTheDocument();+ await expect.element(resetSizeButton()).toBeInTheDocument();+ await expect.element(page.getByRole('button', { name: 'Set optimal size' })).not.toBeInTheDocument();});it('leaves the Size section as it is when the canvas is not the invocation source', async () => {@@ -371,7 +360,7 @@ describe('Size section in canvas mode', () => {await expect.element(renderAt()).not.toBeInTheDocument();expect(badgeText()).toBe('384x384');expect(statusText()).toMatch(/^0\.15 MP/);- await expect.element(optimalSizeButton()).toBeInTheDocument();+ await expect.element(resetSizeButton()).toBeInTheDocument();// The ghost is the recommended 512x512, not the canvas's custom render size.expect(ghostSize()).toEqual([88, 88]);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsxindex 6ffc40f0bd..6f0db1a6ed 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx@@ -223,9 +223,11 @@ describe('filter operation form', () => {expect(footer).toContain('Portrait · Raster layer');expect(footer).toContain('role="status"');- // Auto-process on: no Process verb; Reset then Apply then Cancel.+ // Auto-process on: no Process verb; Reset settings then Apply then Cancel.expect(footer).not.toContain('>Process<');- expect(footer.indexOf('>Reset<')).toBeLessThan(footer.indexOf('>Apply<'));+ expect(footer).not.toContain('>Reset<');+ expect(footer.indexOf('>Reset settings<')).toBeGreaterThan(-1);+ expect(footer.indexOf('>Reset settings<')).toBeLessThan(footer.indexOf('>Apply<'));expect(footer.indexOf('>Apply<')).toBeLessThan(footer.indexOf('>Cancel<'));});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsxindex 4157443afd..8a2f649276 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx@@ -236,7 +236,7 @@ const FilterFooter = ({ engine, isExternalInteractionLocked }: ToolFooterProps)/></Box><Button disabled={!eligibility.canReset} flexShrink={0} variant="ghost" onClick={reset}>- {t('widgets.layers.selectObject.reset')}+ {t('widgets.layers.rasterFilter.resetSettings')}</Button>{session.autoProcess ? null : (<Buttondiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.tsindex eae998295a..1833037fd7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts@@ -22,8 +22,15 @@ import {SamModeToggle,SamStatusSlot,SamVisualInput,+ toggleSamSetting,} from './SamOptions';+const { patchWorkbenchPreferences } = vi.hoisted(() => ({ patchWorkbenchPreferences: vi.fn(() => Promise.resolve()) }));+vi.mock('@workbench/settings/store', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ patchWorkbenchPreferences,+}));+const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {eager: true,import: 'default',@@ -346,7 +353,7 @@ describe('single-row SAM inputs', () => {expect(en.widgets.layers.selectObject.autoProcess).toBe('Auto Process');expect(en.widgets.layers.selectObject.isolatedPreview).toBe('Isolated Preview');expect(en.widgets.layers.selectObject.settings).toBe('Select Object settings');- expect(en.widgets.layers.selectObject.bbox).toBe('BBox');+ expect(en.widgets.layers.selectObject.bbox).toBe('Box');expect(en.widgets.layers.selectObject.technicalDetails).toBe('Technical details');expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{name}}');expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{width}}');@@ -456,6 +463,28 @@ describe('getSamActionHandlers', () => {});});+describe('toggleSamSetting', () => {+ it('saves an applied Auto Process change as the account preference, and nothing else', () => {+ const updateSelectObjectSession = vi.fn(() => 'updated' as const);++ toggleSamSetting({ updateSelectObjectSession }, 'autoProcess', true);+ toggleSamSetting({ updateSelectObjectSession }, 'isolatedPreview', false);++ expect(updateSelectObjectSession).toHaveBeenNthCalledWith(1, { autoProcess: true });+ expect(updateSelectObjectSession).toHaveBeenNthCalledWith(2, { isolatedPreview: false });+ expect(patchWorkbenchPreferences).toHaveBeenCalledExactlyOnceWith({ selectObjectAutoProcess: true });+ });++ it('keeps the preference when the session refuses the change', () => {+ patchWorkbenchPreferences.mockClear();++ toggleSamSetting({ updateSelectObjectSession: () => 'blocked' }, 'autoProcess', false);+ toggleSamSetting({ updateSelectObjectSession: () => 'stale' }, 'autoProcess', false);++ expect(patchWorkbenchPreferences).not.toHaveBeenCalled();+ });+});+describe('select object regions', () => {it('splits mode, points and invert into the bar, settings and secondary commands into More, and keeps Apply / Cancel in status', () => {const session = snapshot({@@ -496,7 +525,7 @@ describe('select object regions', () => {// Input group: mode, points, bbox indicator, invert switch — no verbs.expect(input.indexOf('>Visual<')).toBeLessThan(input.indexOf('aria-label="Include 1"'));- expect(input.indexOf('aria-label="Include 1"')).toBeLessThan(input.indexOf('No bounding box'));+ expect(input.indexOf('aria-label="Include 1"')).toBeLessThan(input.indexOf('No box prompt'));expect(input).toContain('>Invert<');expect(input).not.toContain('>Process<');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsxindex f43a199302..98b8aa08eb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx@@ -34,6 +34,7 @@ import {type SamModel,type SelectObjectSaveTarget,} from '@workbench/canvas-operations/api';+import { patchWorkbenchPreferences } from '@workbench/settings/store';import { useSamSession } from '@workbench/widgets/canvas/engineStoreHooks';import { PropertySwitchRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';import { ChevronDownIcon, SquareMinusIcon, SquarePlusIcon } from 'lucide-react';@@ -150,6 +151,18 @@ export const getSamActionHandlers = (operations: CanvasOperationCapability) => (save: (target: SelectObjectSaveTarget) => void operations.saveSelectObjectSession(target, keepSamImageIntermediate),});+/** Auto Process is also the account's preference, so the next session starts from the person's last choice. */+export const toggleSamSetting = (+ operations: Pick<CanvasOperationCapability, 'updateSelectObjectSession'>,+ key: 'applyPolygonRefinement' | 'autoProcess' | 'isolatedPreview',+ value: boolean+): void => {+ const result = operations.updateSelectObjectSession({ [key]: value });+ if (key === 'autoProcess' && result === 'updated') {+ void patchWorkbenchPreferences({ selectObjectAutoProcess: value });+ }+};+export const getSamActionEligibility = (session: SamSessionSnapshot,isExternalInteractionLocked = false@@ -475,7 +488,7 @@ const SamSettingsGroup = ({ engine, isSurfaceInteractionLocked }: ToolFormProps)isProcessing={isSamProcessingStatus(session.status)}session={session}onModelChange={(model) => operations.updateSelectObjectSession({ model })}- onToggle={(key, value) => operations.updateSelectObjectSession({ [key]: value })}+ onToggle={(key, value) => toggleSamSetting(operations, key, value)}/>);};