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(upscale): add image upscale workflow
joshistoasta4e108cb44bf
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 92979f3b67..b95c110a18 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -623,6 +623,7 @@"project": "Project","queue": "Queue","serverStatus": "Server Status",+ "upscale": "Upscale","versionStatus": "Version","workflow": "Workflow"},@@ -774,6 +775,89 @@"maskBlur": "Mask blur"}},+ "upscale": {+ "addLora": "LoRAs",+ "advanced": "Advanced",+ "batchCount": "Batch count",+ "bundledVae": "Bundled VAE",+ "cfgScale": "CFG scale",+ "clipSkip": "CLIP skip",+ "controlNetChanged": "Tile ControlNet changed to {{name}}.",+ "controlNetCleared": "The incompatible Tile ControlNet was cleared.",+ "creativity": "Creativity",+ "creativityHelp": "Higher values invent more detail and increase prompt influence.",+ "detailGuidance": "Detail guidance",+ "enableNegativePrompt": "Enable negative prompt",+ "generation": "Generation",+ "inputSize": "Input",+ "inputImageAlt": "Upscale input image",+ "largeOutput": "Large output",+ "largeOutputDescription": "This output may take substantially longer and require more VRAM. Check tile settings before queueing.",+ "lorasRemoved": "Removed {{count}} incompatible LoRA model(s).",+ "loraWeight": "{{name}} weight",+ "mainModel": "Main model",+ "mainModelRequired": "Select an SD1.5 or SDXL main model.",+ "negativePrompt": "Negative prompt",+ "notReady": "Upscale is not ready",+ "outputMegapixels": "Output area",+ "outputSize": "Output",+ "positivePrompt": "Positive prompt",+ "presetDescriptions": {+ "artistic": "Allow substantial reinterpretation for a stylized result.",+ "balanced": "Add detail while keeping the original image recognizable.",+ "conservative": "Preserve composition and minimize invented detail.",+ "creative": "Permit visible new detail while retaining the main structure."+ },+ "presetValues": "Creativity {{creativity}} · Structure {{structure}}",+ "presets": {+ "artistic": "Artistic",+ "balanced": "Balanced",+ "conservative": "Conservative",+ "creative": "Creative"+ },+ "prompts": "Prompts",+ "random": "Random",+ "ready": "Ready",+ "readyDescription": "The upscale graph is ready to queue.",+ "removeImage": "Remove image",+ "removeLora": "Remove {{name}}",+ "replaceImage": "Replace upscale input image",+ "replaceOrDrop": "Replace or drop another image",+ "scale": "Scale",+ "scaleHelp": "Output dimensions are the source dimensions multiplied by this value.",+ "scheduler": "Scheduler",+ "seed": "Seed",+ "selectLora": "Select a compatible LoRA…",+ "selectMainModel": "Select an SD1.5 or SDXL model…",+ "selectSpandrelModel": "Select a Spandrel model…",+ "selectTileControlNet": "Select a Tile or Union ControlNet…",+ "shuffleSeed": "Shuffle seed",+ "settingsAdjusted": "Adjusted incompatible settings",+ "shared": "Shared",+ "sharedPromptDescription": "This is the project prompt shared with Generate. For upscaling, describe medium, texture, and style rather than new scene content.",+ "sourceAndTreatment": "Source & treatment",+ "spandrelModel": "Spandrel model",+ "spandrelModelHelp": "The first-pass upscaler. Choose a model suited to photography, illustration, or linework.",+ "spandrelModelRequired": "Select a Spandrel image-to-image model.",+ "steps": "Steps",+ "structure": "Structure",+ "structureHelp": "Higher values preserve the source composition more strictly.",+ "tileControlNet": "Tile ControlNet",+ "tileControlNetHelp": "Guides detail generation with the source image and must match the main model architecture.",+ "tileControlNetRequired": "Select a compatible Tile or Union ControlNet.",+ "tileOverlap": "Tile overlap",+ "tileOverlapHelp": "More overlap reduces seams but increases processing and memory use.",+ "tileSize": "Tile size",+ "tileSizeHelp": "Larger tiles may improve continuity but require more VRAM.",+ "unsupportedFile": "Upscale accepts PNG, JPEG, and WebP images.",+ "upscale": "Upscale",+ "uploadImage": "Upload upscale input image",+ "uploadOrDrop": "Upload a PNG, JPEG, or WebP, or drop one image from Gallery",+ "uploadingImage": "Uploading image…",+ "vae": "VAE",+ "vaeCleared": "The incompatible VAE was cleared.",+ "vaePrecision": "VAE precision"+ },"graph": {"setSource": "Set Source","viewGraph": "View Graph"diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex c5cd158854..1d526b37c0 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -17,10 +17,11 @@ import { createCanvasDimsSync } from './canvasDimsSync';import { configureDiagnostics } from './diagnostics/logger';import { addImagesToGalleryBoard } from './gallery/api';import { getQueueItemResultImages, resumeQueueProcessor, type QueueItemResultImageOptions } from './generation/api';-import { sanitizeBatchCount } from './generation/batch';import { normalizeGenerateSettings } from './generation/settings';+import { getQueueItemSnapshotBatchCount } from './queueSnapshot';import { shouldSubmitPendingQueueItem } from './queueSubmission';import { useWorkbenchPreferenceSelector } from './settings/store';+import { normalizeUpscaleWidgetValues } from './upscale/settings';import {useWorkbenchDispatch,useWorkbenchHasHydrated,@@ -39,23 +40,21 @@ const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {const toErrorMessage = (error: unknown): string =>getApiErrorMessage(error, error instanceof Error ? error.message : String(error));-const getSnapshotBatchCount = (queueItem: QueueItem): number => {- const batchCount = queueItem.snapshot.widgetStates.generate?.values.batchCount;-- return sanitizeBatchCount(batchCount);-};-type QueueItemBackendSubmission =| { kind: 'generate'; request: EnqueueGenerateRequest }| { kind: 'workflow'; request: EnqueueWorkflowRequest }| { error: string; kind: 'invalid' };const COMPILED_GENERATE_RESULT_NODE_ID = 'canvas_output';+const COMPILED_UPSCALE_RESULT_NODE_ID = 'upscale_output';export const getQueueItemResultImageOptions = (queueItem: QueueItem): QueueItemResultImageOptions | undefined => {if (queueItem.snapshot.sourceId === 'generate' || queueItem.snapshot.sourceId === 'canvas') {return { resultNodeIds: [COMPILED_GENERATE_RESULT_NODE_ID] };}+ if (queueItem.snapshot.sourceId === 'upscale') {+ return { resultNodeIds: [COMPILED_UPSCALE_RESULT_NODE_ID] };+ }return undefined;};@@ -128,10 +127,36 @@ export const createQueueItemBackendSubmission = (};}+ if (queueItem.snapshot.sourceId === 'upscale') {+ const upscaleValues = normalizeUpscaleWidgetValues(queueItem.snapshot.widgetStates.upscale?.values);++ if (!upscaleValues) {+ return { error: 'upscale queue item is missing upscale submission metadata.', kind: 'invalid' };+ }++ return {+ kind: 'generate',+ request: {+ batchCount: upscaleValues.batchCount,+ destination: queueItem.snapshot.destination,+ graph,+ negativePrompt: upscaleValues.negativePromptEnabled ? upscaleValues.negativePrompt : '',+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: upscaleValues.positivePrompt,+ positivePromptNodeId: 'positive_prompt',+ projectId: project.id,+ seed: upscaleValues.seed,+ seedNodeId: 'seed',+ shouldRandomizeSeed: upscaleValues.shouldRandomizeSeed,+ sourceQueueItemId: queueItem.id,+ },+ };+ }+return {kind: 'workflow',request: {- batchCount: getSnapshotBatchCount(queueItem),+ batchCount: getQueueItemSnapshotBatchCount(queueItem),destination: queueItem.snapshot.destination,graph,projectId: project.id,diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.tsindex c9c264c7ac..348e368ea8 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts@@ -1,6 +1,6 @@import type { CanvasStagingCandidateContract, CanvasStateContractV2, QueueItem } from './types';-import { sanitizeBatchCount } from './generation/batch';+import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from './queueSnapshot';export interface CanvasQueuePlaceholderSlot {height: number;@@ -34,11 +34,12 @@ const getFiniteNumber = (value: unknown, fallback: number): number =>const getSubmittedBboxSize = (item: QueueItem): { height: number; width: number } => {const { bbox } = item.snapshot.canvas.document;-- return {+ const bboxSize = {height: Math.max(1, Math.round(getFiniteNumber(bbox.height, item.snapshot.canvas.document.height))),width: Math.max(1, Math.round(getFiniteNumber(bbox.width, item.snapshot.canvas.document.width))),};++ return item.snapshot.sourceId === 'upscale' ? getQueueItemSnapshotDimensions(item, bboxSize) : bboxSize;};const getExpectedImageCount = (item: QueueItem): number => {@@ -46,9 +47,7 @@ const getExpectedImageCount = (item: QueueItem): number => {return item.backendItemIds.length;}- return sanitizeBatchCount(- item.snapshot.generate?.values.batchCount ?? item.snapshot.widgetStates.generate?.values.batchCount- );+ return getQueueItemSnapshotBatchCount(item);};/** Collision-safe candidate value identity used with the selected slot index for guarded acceptance. */diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.tsindex a07b9f82a1..70b24f9d0b 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts@@ -251,7 +251,7 @@ const addLoraSelectors = (return loader;};-const addLoraCollectionLoader = (+export const addLoraCollectionLoader = (graph: BackendGraphContract,loras: GenerateLora[],model: GenerateModelConfig,diff --git a/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.test.ts b/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.test.tsnew file mode 100644index 0000000000..39467b31eb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { applyProjectPromptDraft, getPromptDraftFromValues, migrateProjectPromptDraft } from './projectPromptDraft';++describe('project prompt draft', () => {+ it('normalizes missing prompt values', () => {+ expect(getPromptDraftFromValues({})).toEqual({+ negativePrompt: '',+ negativePromptEnabled: true,+ positivePrompt: '',+ });+ });++ it('patches only shared prompt fields', () => {+ const values = { negativePrompt: 'old', positivePrompt: 'old', positivePromptHeightPx: 120 };++ expect(applyProjectPromptDraft(values, { positivePrompt: 'new' })).toEqual({+ negativePrompt: 'old',+ negativePromptEnabled: true,+ positivePrompt: 'new',+ positivePromptHeightPx: 120,+ });+ });++ it('seeds an empty Generate prompt from a legacy Upscale prompt', () => {+ expect(+ migrateProjectPromptDraft(+ { positivePrompt: '', positivePromptHeightPx: 96 },+ { negativePrompt: 'blur', negativePromptEnabled: false, positivePrompt: 'fine detail' }+ )+ ).toEqual({+ negativePrompt: 'blur',+ negativePromptEnabled: false,+ positivePrompt: 'fine detail',+ positivePromptHeightPx: 96,+ });+ });++ it('keeps a non-empty Generate prompt during migration', () => {+ const generateValues = { negativePrompt: '', positivePrompt: 'generate prompt' };++ expect(migrateProjectPromptDraft(generateValues, { positivePrompt: 'upscale prompt' })).toBe(generateValues);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.ts b/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.tsnew file mode 100644index 0000000000..d7caa493a6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/projectPromptDraft.ts@@ -0,0 +1,61 @@+import type { Project } from '@workbench/types';++import { getProjectWidgetValues } from '@workbench/widgetState';++export interface ProjectPromptDraft {+ negativePrompt: string;+ negativePromptEnabled: boolean;+ positivePrompt: string;+}++export type ProjectPromptDraftPatch = Partial<ProjectPromptDraft>;++export const getPromptDraftFromValues = (values: Record<string, unknown>): ProjectPromptDraft => ({+ negativePrompt: typeof values.negativePrompt === 'string' ? values.negativePrompt : '',+ negativePromptEnabled: values.negativePromptEnabled !== false,+ positivePrompt: typeof values.positivePrompt === 'string' ? values.positivePrompt : '',+});++export const getProjectPromptDraft = (project: Project): ProjectPromptDraft =>+ getPromptDraftFromValues(getProjectWidgetValues(project, 'generate'));++export const areProjectPromptDraftsEqual = (left: ProjectPromptDraft, right: ProjectPromptDraft): boolean =>+ left.positivePrompt === right.positivePrompt &&+ left.negativePrompt === right.negativePrompt &&+ left.negativePromptEnabled === right.negativePromptEnabled;++export const applyProjectPromptDraft = (+ values: Record<string, unknown>,+ patch: ProjectPromptDraftPatch+): Record<string, unknown> => {+ const current = getPromptDraftFromValues(values);+ const next: ProjectPromptDraft = {+ negativePrompt: typeof patch.negativePrompt === 'string' ? patch.negativePrompt : current.negativePrompt,+ negativePromptEnabled:+ typeof patch.negativePromptEnabled === 'boolean' ? patch.negativePromptEnabled : current.negativePromptEnabled,+ positivePrompt: typeof patch.positivePrompt === 'string' ? patch.positivePrompt : current.positivePrompt,+ };++ return areProjectPromptDraftsEqual(current, next) ? values : { ...values, ...next };+};++const hasPromptContent = (draft: ProjectPromptDraft): boolean =>+ draft.positivePrompt.trim().length > 0 || draft.negativePrompt.trim().length > 0;++/**+ * Generate owns the project prompt draft. Older projects may have prompt text stored only in+ * Upscale, so seed Generate from it when Generate has no prompt content of its own.+ */+export const migrateProjectPromptDraft = (+ generateValues: Record<string, unknown>,+ legacyUpscaleValues: Record<string, unknown>+): Record<string, unknown> => {+ const generateDraft = getPromptDraftFromValues(generateValues);+ const legacyUpscaleDraft = getPromptDraftFromValues(legacyUpscaleValues);++ if (hasPromptContent(generateDraft) || !hasPromptContent(legacyUpscaleDraft)) {+ return generateValues;+ }++ return applyProjectPromptDraft(generateValues, legacyUpscaleDraft);+};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex 78f92d4886..fa809f9c6a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -5,6 +5,8 @@ import type { GalleryBoard, GalleryImage } from '@workbench/gallery/api';import { Dialog, HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';import { Button, MenuContent, Tooltip } from '@workbench/components/ui';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';import {AsteriskIcon,ChevronRightIcon,@@ -338,6 +340,17 @@ const SingleImageMenuItems = ({const handleRecallClipSkip = useRecallImageDataHandler(actions, image, 'clipSkip');const handleSelectForCompare = useSelectForCompareHandler(actions, image);const handleUseAsReferenceImage = useUseAsReferenceImageHandler(actions, image);+ const dispatch = useWorkbenchDispatch();+ const openWidget = useOpenWorkbenchWidget();+ const handleSendToUpscale = useCallback(() => {+ openWidget('upscale', { preferredRegions: ['left'] });+ dispatch({+ type: 'patchWidgetValues',+ values: { inputImage: { height: image.height, image_name: image.imageName, width: image.width } },+ widgetId: 'upscale',+ });+ dispatch({ sourceId: 'upscale', type: 'setInvocationSource' });+ }, [dispatch, image.height, image.imageName, image.width, openWidget]);return (<>@@ -395,7 +408,7 @@ const SingleImageMenuItems = ({/></ContextSubMenu><Menu.Separator borderColor="border.subtle" />- <ContextMenuItem disabled icon={ScanIcon} label="Send to Upscale" value="send-to-upscale" />+ <ContextMenuItem icon={ScanIcon} label="Send to Upscale" value="send-to-upscale" onClick={handleSendToUpscale} /><ContextMenuItemdisabled={!actions.canUseAsReferenceImage}icon={ImageIcon}diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex 09422dac88..7e608bbc9a 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -7,11 +7,13 @@ import type {MainModelConfig,VaeModelConfig,} from './generation/types';+import type { ModelConfig } from './models/types';import type { InvocationRoute, WidgetId } from './types';import { getDefaultGenerateSettings } from './generation/baseGenerationPolicies';import { getInvocationRouteInput, resolveInvocationRoute, resolveInvocationRouteInput } from './invocation';import { submitResolvedInvocation } from './invocationSubmit';+import { createDefaultUpscaleWidgetValues } from './upscale/settings';import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };@@ -57,6 +59,24 @@ const unknownExternalModel: GenerateModelConfig = {type: 'external_image_generator',};+const upscaleModel = (key: string, type: string, base: string, name = key): ModelConfig => ({+ base,+ file_size: 1,+ format: 'checkpoint',+ hash: `${key}-hash`,+ key,+ name,+ path: key,+ source: key,+ source_type: 'path',+ type,+});+const upscaleModels = [+ upscaleModel('sdxl-upscale', 'main', 'sdxl'),+ upscaleModel('spandrel-upscale', 'spandrel_image_to_image', 'any'),+ upscaleModel('tile-upscale', 'controlnet', 'sdxl', 'SDXL Tile ControlNet'),+];+const createGenerateValues = (model: GenerateModelConfig = animaModel,overrides: Partial<GenerateWidgetValues> = {}@@ -124,6 +144,67 @@ describe('resolveInvocationRoute', () => {});});+describe('resolveInvocationRoute — upscale source', () => {+ const route: InvocationRoute = {+ destination: 'gallery',+ destinationLocked: false,+ sourceId: 'upscale',+ sourceLocked: false,+ };++ const createInput = () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: {+ ...createDefaultUpscaleWidgetValues(upscaleModels),+ inputImage: { height: 512, image_name: 'input.png', width: 768 },+ },+ widgetId: 'upscale',+ });++ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;++ return getInvocationRouteInput(project);+ };++ it('is ready only with a mounted widget and installed compatible required models', () => {+ expect(resolveInvocationRouteInput(createInput(), 'global', route, upscaleModels)).toMatchObject({+ sourceValid: true,+ validationReasons: [],+ });++ const input = createInput();+ const withoutWidget = { ...input, mountedWidgetIds: input.mountedWidgetIds.filter((id) => id !== 'upscale') };+ const missingTile = upscaleModels.filter((model) => model.key !== 'tile-upscale');++ expect(resolveInvocationRouteInput(withoutWidget, 'global', route, upscaleModels).validationReasons).toContain(+ 'The Upscale widget is not mounted in this project.'+ );+ expect(resolveInvocationRouteInput(input, 'global', route, missingTile).validationReasons).toContain(+ 'SDXL Tile ControlNet is no longer installed.'+ );+ });++ it('rejects unsupported main-model bases and non-Tile ControlNets', () => {+ const input = createInput();+ const values = {+ ...input.upscaleValues,+ model: upscaleModel('flux-upscale', 'main', 'flux', 'FLUX'),+ tileControlnetModel: upscaleModel('depth-upscale', 'controlnet', 'flux', 'FLUX Depth ControlNet'),+ };+ const models = [values.model, values.tileControlnetModel, upscaleModels[1]!];+ const result = resolveInvocationRouteInput({ ...input, upscaleValues: values }, 'global', route, models);++ expect(result.sourceValid).toBe(false);+ expect(result.validationReasons).toContain('Upscale supports only SD1.5 and SDXL main models.');+ expect(result.validationReasons).toContain(+ 'The Tile ControlNet must match the main model base and be a Tile or Union model.'+ );+ });+});+describe('resolveInvocationRoute — canvas source', () => {const canvasRoute: InvocationRoute = {destination: 'canvas',diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex afb7af8619..fdcade7c62 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -16,6 +16,7 @@ import {isSupportedGenerateModel,} from './generation/baseGenerationPolicies';import { normalizeGenerateWidgetValues } from './generation/settings';+import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues } from './upscale/settings';import { getProjectWidgetValues } from './widgetState';import { areArraysEqual, createStableSelector } from './workbenchSelectors';import { getProjectGraphReadiness } from './workflows/buildGraph';@@ -44,7 +45,7 @@ export interface ResultDestinationMeta {export const invocationSources: InvocationSourceMeta[] = [{ id: 'generate', label: 'Generate', available: true },{ id: 'workflow', label: 'Workflow', available: true },- { id: 'upscale', label: 'Upscale', available: false },+ { id: 'upscale', label: 'Upscale', available: true },{ id: 'canvas', label: 'Canvas', available: true },];@@ -78,11 +79,13 @@ const validDestinationIds = new Set(resultDestinations.map((destination) => destconst sourceWidgetIds: Partial<Record<InvocationSourceId, WidgetId>> = {canvas: 'canvas',generate: 'generate',+ upscale: 'upscale',workflow: 'workflow',};export interface InvocationRouteInput {generateValues: Record<string, unknown>;+ upscaleValues: Record<string, unknown>;invocation: InvocationRoute;mountedWidgetIds: readonly WidgetId[];projectGraph: ProjectGraphState;@@ -113,6 +116,7 @@ export const getInvocationRouteInput = (project: Project): InvocationRouteInputwidth: project.canvas.document.bbox.width,},generateValues: getProjectWidgetValues(project, 'generate'),+ upscaleValues: getProjectWidgetValues(project, 'upscale'),invocation: project.invocation,mountedWidgetIds: getMountedWidgetIds(project),projectGraph: project.projectGraph,@@ -124,6 +128,7 @@ export const areInvocationRouteInputsEqual = (left: InvocationRouteInput, right:left.invocation === right.invocation &&left.projectGraph === right.projectGraph &&left.generateValues === right.generateValues &&+ left.upscaleValues === right.upscaleValues &&left.canvasBbox.width === right.canvasBbox.width &&left.canvasBbox.height === right.canvasBbox.height &&areArraysEqual(left.mountedWidgetIds, right.mountedWidgetIds);@@ -186,6 +191,14 @@ export const resolveInvocationRouteInput = (validationReasons.push(...getGenerateSnapshotValidationReasons(input.generateValues, models));}+ if (sourceId === 'upscale') {+ const values = normalizeUpscaleWidgetValues(input.upscaleValues);++ validationReasons.push(+ ...(values ? getUpscaleValidationReasons(values, models) : ['Upscale settings are incomplete.'])+ );+ }+if (sourceId === 'canvas') {// Canvas shares the generate model/prompt/steps, so reuse those reasons, then// require a non-degenerate generation frame (a zero-area bbox has nothing todiff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 64ed692e44..8e621c7062 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -30,6 +30,7 @@ const defaultInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {'gallery:bottom': 'gallery','gallery:center': 'gallery',generate: 'generate',+ upscale: 'upscale',layers: 'layers',notifications: 'notifications',preview: 'preview',@@ -127,7 +128,11 @@ export const layoutPresets: LayoutPreset[] = [instanceIds: ['preview', 'canvas', 'gallery:center', 'workflow:center'],sizePx: 0,}),- left: createRegion({ activeInstanceId: 'generate', instanceIds: ['generate', 'workflow'], sizePx: 450 }),+ left: createRegion({+ activeInstanceId: 'generate',+ instanceIds: ['generate', 'workflow', 'upscale'],+ sizePx: 450,+ }),right: createRegion({activeInstanceId: 'gallery',instanceIds: ['gallery', 'preview', 'queue', 'layers', 'diagnostics', 'project'],@@ -152,7 +157,11 @@ export const layoutPresets: LayoutPreset[] = [instanceIds: ['workflow:center', 'canvas', 'preview', 'gallery:center'],sizePx: 0,}),- left: createRegion({ activeInstanceId: 'workflow', instanceIds: ['workflow', 'generate'], sizePx: 450 }),+ left: createRegion({+ activeInstanceId: 'workflow',+ instanceIds: ['workflow', 'generate', 'upscale'],+ sizePx: 450,+ }),right: createRegion({activeInstanceId: 'queue',instanceIds: ['queue', 'gallery', 'layers', 'preview', 'diagnostics', 'project'],@@ -177,7 +186,11 @@ export const layoutPresets: LayoutPreset[] = [instanceIds: ['canvas', 'preview', 'gallery:center', 'workflow:center'],sizePx: 0,}),- left: createRegion({ activeInstanceId: 'generate', instanceIds: ['generate', 'workflow'], sizePx: 450 }),+ left: createRegion({+ activeInstanceId: 'generate',+ instanceIds: ['generate', 'workflow', 'upscale'],+ sizePx: 450,+ }),right: createRegion({activeInstanceId: 'layers',instanceIds: ['layers', 'gallery', 'queue', 'preview', 'diagnostics', 'project'],@@ -204,7 +217,7 @@ export const layoutPresets: LayoutPreset[] = [}),left: createRegion({activeInstanceId: 'generate',- instanceIds: ['generate', 'workflow', 'gallery'],+ instanceIds: ['generate', 'workflow', 'upscale', 'gallery'],isCollapsed: true,sizePx: 450,}),diff --git a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsxindex 32d9669c4e..47f2eb87c2 100644--- a/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/workbench/models/components/ModelSelect.tsx@@ -258,7 +258,7 @@ export const ModelSelect = ({<Inputref={searchInputRef}aria-label={`Search ${scopeLabel}`}- placeholder={`Search ${scopeLabel}...`}+ placeholder={`Search ${scopeLabel}…`}size="xs"value={searchTerm}onChange={(event) => setSearchTerm(event.currentTarget.value)}@@ -451,7 +451,7 @@ const BaseChip = ({const ModelButtonContent = ({ model }: { model: ModelConfig }) => (<HStack as="span" flex="1" gap="2" minW="0">- <Text as="span" fontSize="xs" minW="0" truncate>+ <Text as="span" fontSize="xs" minW="0" title={model.name} truncate>{model.name}</Text><Badgediff --git a/invokeai/frontend/webv2/src/workbench/queueSnapshot.ts b/invokeai/frontend/webv2/src/workbench/queueSnapshot.tsnew file mode 100644index 0000000000..16b641b6dc--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queueSnapshot.ts@@ -0,0 +1,37 @@+import type { QueueItem } from './types';++import { sanitizeBatchCount } from './generation/batch';+import { getUpscaleOutputDimensions, normalizeUpscaleWidgetValues } from './upscale/settings';++/** Values owned by the source that created this immutable queue snapshot. */+export const getQueueItemSourceWidgetValues = (item: QueueItem): Record<string, unknown> => {+ if (item.snapshot.sourceId === 'upscale') {+ return item.snapshot.widgetStates.upscale?.values ?? {};+ }++ // Canvas intentionally shares Generate settings. Workflow has no first-party+ // batch form yet and keeps the historical Generate batch-count fallback.+ return item.snapshot.widgetStates.generate?.values ?? {};+};++export const getQueueItemSnapshotBatchCount = (item: QueueItem): number =>+ sanitizeBatchCount(getQueueItemSourceWidgetValues(item).batchCount);++export const getQueueItemSnapshotDimensions = (+ item: QueueItem,+ fallback: { width: number; height: number }+): { width: number; height: number } => {+ if (item.snapshot.sourceId === 'upscale') {+ const values = normalizeUpscaleWidgetValues(item.snapshot.widgetStates.upscale?.values);++ if (values?.inputImage) {+ return getUpscaleOutputDimensions(values.inputImage, values.scale);+ }+ }++ const values = getQueueItemSourceWidgetValues(item);+ const width = typeof values.width === 'number' && Number.isFinite(values.width) ? values.width : fallback.width;+ const height = typeof values.height === 'number' && Number.isFinite(values.height) ? values.height : fallback.height;++ return { height: Math.max(1, Math.round(height)), width: Math.max(1, Math.round(width)) };+};diff --git a/invokeai/frontend/webv2/src/workbench/queueSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/queueSubmission.test.tsindex 454a5b79b7..9c137d736d 100644--- a/invokeai/frontend/webv2/src/workbench/queueSubmission.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queueSubmission.test.ts@@ -30,8 +30,8 @@ describe('isBackendSubmittableSourceId', () => {expect(isBackendSubmittableSourceId('workflow')).toBe(true);});- it('excludes upscale (not yet an available source)', () => {- expect(isBackendSubmittableSourceId('upscale')).toBe(false);+ it('includes upscale', () => {+ expect(isBackendSubmittableSourceId('upscale')).toBe(true);});it('exposes canvas in the exported allow-list', () => {@@ -54,7 +54,7 @@ describe('shouldSubmitPendingQueueItem', () => {expect(shouldSubmitPendingQueueItem(makeQueueItem('canvas', 'cancelled'))).toBe(false);});- it('does not submit a pending item whose source is not submittable', () => {- expect(shouldSubmitPendingQueueItem(makeQueueItem('upscale', 'pending'))).toBe(false);+ it('submits a pending upscale item', () => {+ expect(shouldSubmitPendingQueueItem(makeQueueItem('upscale', 'pending'))).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/queueSubmission.ts b/invokeai/frontend/webv2/src/workbench/queueSubmission.tsindex c3d1a2f13f..8aba851aef 100644--- a/invokeai/frontend/webv2/src/workbench/queueSubmission.ts+++ b/invokeai/frontend/webv2/src/workbench/queueSubmission.ts@@ -19,8 +19,8 @@* graph is compiled ahead of time, but prompt/seed batch data still has to ride* along so repeated invokes are not silently run with backend primitive defaults.*- * `upscale` is intentionally excluded: it is not yet an available source- * (`invocation.ts` marks it `available: false`), so it never produces a snapshot.+ * Upscale uses the same prompt/seed batch path as Generate after compiling its+ * own immutable widget snapshot.*/import type { InvocationSourceId, QueueItem } from './types';@@ -29,6 +29,7 @@ import type { InvocationSourceId, QueueItem } from './types';export const BACKEND_SUBMITTABLE_SOURCE_IDS = ['generate','workflow',+ 'upscale','canvas',] as const satisfies readonly InvocationSourceId[];diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.ts b/invokeai/frontend/webv2/src/workbench/queueSummary.tsindex ca0c642f8e..a060939c02 100644--- a/invokeai/frontend/webv2/src/workbench/queueSummary.ts+++ b/invokeai/frontend/webv2/src/workbench/queueSummary.ts@@ -1,7 +1,7 @@import type { QueueItemProgress } from './backend/progressStore';import type { QueueItem } from './types';-import { sanitizeBatchCount } from './generation/batch';+import { getQueueItemSnapshotBatchCount } from './queueSnapshot';export interface QueueSummary {current: number;@@ -60,9 +60,7 @@ export const getQueueItemExpectedImageCount = (item: QueueItem): number => {return item.backendItemIds.length;}- const batchCount = item.snapshot.widgetStates.generate?.values.batchCount;-- return sanitizeBatchCount(batchCount);+ return getQueueItemSnapshotBatchCount(item);};const compareQueuePosition = (a: QueueItem, b: QueueItem): number => {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsxindex 30048849f5..7aa34fcad5 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/BatchCountField.tsx@@ -1,6 +1,6 @@import { NumberInput } from '@chakra-ui/react';import { MIN_BATCH_COUNT, sanitizeBatchCount } from '@workbench/generation/batch';-import { useWidgetValuesSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { useCallback } from 'react';const getBatchCount = (values: Record<string, unknown>): number => {@@ -10,15 +10,28 @@ const getBatchCount = (values: Record<string, unknown>): number => {};export const BatchCountField = () => {- const batchCount = useWidgetValuesSelector('generate', getBatchCount);+ const { batchCount, sourceId } = useActiveProjectSelector(+ (project) => {+ const sourceId = project.invocation.sourceId;+ const typeId = sourceId === 'upscale' ? 'upscale' : 'generate';+ const instance = Object.values(project.widgetInstances).find((candidate) => candidate.typeId === typeId);++ return { batchCount: getBatchCount(instance?.state.values ?? {}), sourceId };+ },+ (left, right) => left.batchCount === right.batchCount && left.sourceId === right.sourceId+ );const dispatch = useWorkbenchDispatch();const handleValueChange = useCallback(({ valueAsNumber }: { valueAsNumber: number }) => {if (Number.isFinite(valueAsNumber)) {- dispatch({ batchCount: valueAsNumber, type: 'setGenerateBatchCount' });+ if (sourceId === 'upscale') {+ dispatch({ type: 'patchWidgetValues', values: { batchCount: valueAsNumber }, widgetId: 'upscale' });+ } else {+ dispatch({ batchCount: valueAsNumber, type: 'setGenerateBatchCount' });+ }}},- [dispatch]+ [dispatch, sourceId]);return (diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 2d5ec9d74a..823d1b3faa 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -4,6 +4,7 @@ import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@woimport { Flex, Group, HStack, Icon, Menu, Portal, Separator, Stack, Text, VStack } from '@chakra-ui/react';import { Button, IconButton, Tooltip } from '@workbench/components/ui';import { sanitizeBatchCount } from '@workbench/generation/batch';+import { useMountEffect } from '@workbench/hooks/useMountEffect';import {formatRoute,createInvocationRouteInputSelector,@@ -26,7 +27,7 @@ import {} from '@workbench/WorkbenchContext';import { useInvocationTemplatesSelector } from '@workbench/workflows/templates';import { CheckIcon, ChevronDownIcon, LockKeyholeIcon, SparklesIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef } from 'react';+import { useCallback, useMemo, useRef } from 'react';const CONTROL_WIDTH = '10rem';const selectInvocationRouteInput = createInvocationRouteInputSelector();@@ -50,19 +51,19 @@ const compactBlockingReason = (reason: string): string => {const InvokeTooltipContent = ({blockingReasons,- generateValues,+ sourceValues,invocation,isValid,}: {blockingReasons: string[];- generateValues: Record<string, unknown>;+ sourceValues: Record<string, unknown>;invocation: InvocationRoute;isValid: boolean;}) => {- const batchCount = getBatchCount(generateValues);+ const batchCount = getBatchCount(sourceValues);const destination = getDestinationLabel(invocation.destination);const summary =- invocation.sourceId === 'generate'+ invocation.sourceId === 'generate' || invocation.sourceId === 'upscale'? `1 prompt × ${batchCount} iteration${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`: `Workflow × ${batchCount} run${batchCount === 1 ? '' : 's'} → ${batchCount} generation${batchCount === 1 ? '' : 's'}`;@@ -130,9 +131,9 @@ export const InvokeControl = () => {modelsRef.current = availabilityModels;- useEffect(() => {+ useMountEffect(() => {ensureModelsLoaded();- }, []);+ });const onInvoke = useCallback(() => {flushGenerateDrafts();@@ -160,12 +161,21 @@ export const InvokeControl = () => {() => (<InvokeTooltipContentblockingReasons={blockingReasons}- generateValues={routeInput.generateValues}+ sourceValues={+ routeInput.invocation.sourceId === 'upscale' ? routeInput.upscaleValues : routeInput.generateValues+ }invocation={invocation}isValid={isValid}/>),- [blockingReasons, invocation, isValid, routeInput.generateValues]+ [+ blockingReasons,+ invocation,+ isValid,+ routeInput.generateValues,+ routeInput.invocation.sourceId,+ routeInput.upscaleValues,+ ]);const handleSourceChange = useCallback((event: { value: string }) =>@@ -212,7 +222,13 @@ export const InvokeControl = () => {</Button></Tooltip><Menu.Trigger asChild>- <IconButton colorPalette="brand" size="sm" minW="0" w="7">+ <IconButton+ aria-label="Choose invocation source and destination"+ colorPalette="brand"+ minW="0"+ size="sm"+ w="7"+ ><ChevronDownIcon /></IconButton></Menu.Trigger>diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsxindex bc6120d145..7569517b83 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueInfo.tsx@@ -6,6 +6,7 @@ import { useModelLoads, type ModelLoadInfo } from '@workbench/backend/modelLoadSimport { useQueueItemProgress, type QueueItemProgress } from '@workbench/backend/progressStore';import { Button, Tooltip } from '@workbench/components/ui';import { getDestinationLabel, getSourceLabel } from '@workbench/invocation';+import { getQueueItemSourceWidgetValues } from '@workbench/queueSnapshot';import { getQueueItemExpectedImageCount, getQueueProgressBarState, getQueueSummary } from '@workbench/queueSummary';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { useActiveProjectSelector, useWorkbenchSelector } from '@workbench/WorkbenchContext';@@ -138,8 +139,8 @@ const QueueInfoTooltip = ({);}- const generateValues = item.snapshot.widgetStates.generate.values;- const prompt = typeof generateValues.positivePrompt === 'string' ? generateValues.positivePrompt.trim() : '';+ const sourceValues = getQueueItemSourceWidgetValues(item);+ const prompt = typeof sourceValues.positivePrompt === 'string' ? sourceValues.positivePrompt.trim() : '';const expectedCount = getQueueItemExpectedImageCount(item);const activeItemIndex = Math.min(expectedCount, Math.max(1, progress?.activeItemIndex ?? 1));const activeBackendItemId = item.backendItemIds?.[activeItemIndex - 1];diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex 6a7cbca6af..6236fe4ac7 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -29,6 +29,7 @@ export type FirstPartyWidgetTypeId =| 'project'| 'queue'| 'server-status'+ | 'upscale'| 'users'| 'version-status'| 'workflow';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/graph.test.ts b/invokeai/frontend/webv2/src/workbench/upscale/graph.test.tsnew file mode 100644index 0000000000..24ca7c35d1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/graph.test.ts@@ -0,0 +1,117 @@+import type { GenerateLora, VaeModelConfig } from '@workbench/generation/types';+import type { ModelConfig } from '@workbench/models/types';++import { describe, expect, it } from 'vitest';++import { compileUpscaleGraph, getUpscaleControlNetValues, getUpscaleDenoisingStart } from './graph';+import { createDefaultUpscaleWidgetValues } from './settings';++const model = (key: string, type: string, base: string, name = key): ModelConfig => ({+ base,+ file_size: 1,+ format: 'checkpoint',+ hash: `${key}-hash`,+ key,+ name,+ path: key,+ source: key,+ source_type: 'path',+ type,+});++const createValues = (base: 'sd-1' | 'sdxl') => {+ const models = [+ model('main', 'main', base),+ model('spandrel', 'spandrel_image_to_image', 'any'),+ model('tile', 'controlnet', base, 'Tile ControlNet'),+ model('lora', 'lora', base),+ model('vae', 'vae', base),+ ];+ const values = createDefaultUpscaleWidgetValues(models);++ return {+ ...values,+ inputImage: { height: 101, image_name: 'input.png', width: 203 },+ loras: [{ isEnabled: true, model: models[3] as GenerateLora['model'], weight: 0.7 }],+ negativePrompt: 'blur',+ positivePrompt: 'detail',+ vae: models[4] as VaeModelConfig,+ };+};++const hasEdge = (+ edges: ReturnType<typeof compileUpscaleGraph>['backendGraph']['edges'],+ source: string,+ sourceField: string,+ destination: string,+ destinationField: string+) =>+ edges.some(+ (edge) =>+ edge.source.node_id === source &&+ edge.source.field === sourceField &&+ edge.destination.node_id === destination &&+ edge.destination.field === destinationField+ );++describe('compileUpscaleGraph', () => {+ it('preserves the exact legacy creativity and structure formulas', () => {+ expect(getUpscaleDenoisingStart(0)).toBeCloseTo(0.499);+ expect(getUpscaleDenoisingStart(10)).toBe(0);+ expect(getUpscaleControlNetValues(0)).toEqual({+ first: { beginStepPercent: 0, controlWeight: 0.625, endStepPercent: 0.55 },+ second: { beginStepPercent: 0.55, controlWeight: 0.21375, endStepPercent: 0.85 },+ });+ });++ it.each(['sd-1', 'sdxl'] as const)('compiles the legacy %s topology with fixed batch ids', (base) => {+ const compiled = compileUpscaleGraph(createValues(base), 'gallery', { useCpuNoise: true });+ const { edges, nodes } = compiled.backendGraph;++ expect(compiled.positivePromptNodeId).toBe('positive_prompt');+ expect(compiled.negativePromptNodeId).toBe('negative_prompt');+ expect(compiled.seedNodeId).toBe('seed');+ expect(compiled.outputNodeId).toBe('upscale_output');+ expect(nodes.spandrel_autoscale).toMatchObject({+ fit_to_multiple_of_8: true,+ image: { image_name: 'input.png' },+ scale: 4,+ type: 'spandrel_image_to_image_autoscale',+ });+ expect(nodes.tiled_multidiffusion_denoise_latents).toMatchObject({+ cfg_scale: 2,+ scheduler: 'kdpm_2',+ steps: 30,+ tile_height: 1024,+ tile_overlap: 128,+ tile_width: 1024,+ });+ expect(nodes.tiled_multidiffusion_denoise_latents?.denoising_start).toBeCloseTo(0.499);+ expect(nodes.upscale_output).toMatchObject({ is_intermediate: false, tiled: true, type: 'l2i' });+ expect(nodes.noise?.use_cpu).toBe(true);+ expect(nodes.controlnet_1).toMatchObject({ control_weight: 0.625, end_step_percent: 0.55 });+ expect(nodes.controlnet_2).toMatchObject({ begin_step_percent: 0.55, control_weight: 0.21375 });+ expect(nodes.core_metadata).toMatchObject({+ creativity: 0,+ structure: 0,+ tile_overlap: 128,+ tile_size: 1024,+ upscale_scale: 4,+ });+ expect(hasEdge(edges, 'spandrel_autoscale', 'width', 'core_metadata', 'width')).toBe(true);+ expect(hasEdge(edges, 'spandrel_autoscale', 'height', 'core_metadata', 'height')).toBe(true);+ expect(+ hasEdge(edges, 'controlnet_collector', 'collection', 'tiled_multidiffusion_denoise_latents', 'control')+ ).toBe(true);+ expect(hasEdge(edges, 'positive_prompt', 'value', 'pos_cond', 'prompt')).toBe(true);+ expect(hasEdge(edges, 'vae_loader', 'vae', 'upscale_output', 'vae')).toBe(true);+ expect(Object.values(nodes).some((node) => node.type.includes('lora_collection_loader'))).toBe(true);+ expect(base === 'sdxl' ? nodes.clip_skip : nodes.clip_skip?.type).toBe(base === 'sdxl' ? undefined : 'clip_skip');+ });++ it('marks only Canvas-destination output intermediate', () => {+ expect(+ compileUpscaleGraph(createValues('sd-1'), 'canvas', { useCpuNoise: false }).backendGraph.nodes.upscale_output+ ).toMatchObject({ is_intermediate: true, use_cache: false });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/upscale/graph.ts b/invokeai/frontend/webv2/src/workbench/upscale/graph.tsnew file mode 100644index 0000000000..bbbaf1194e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/graph.ts@@ -0,0 +1,276 @@+import type {+ BackendGraphContract,+ BackendInvocationContract,+ ProjectSettings,+ ResultDestination,+} from '@workbench/types';++import { coerceSchedulerForGraph } from '@workbench/generation/baseGenerationPolicies';+import { addLoraCollectionLoader } from '@workbench/generation/graph';+import {+ addEdge,+ addNode,+ getActiveCompatibleLoras,+ toGraphContract,+ toModelIdentifier,+} from '@workbench/generation/graphBuilder';++import type { CompiledUpscaleGraph, UpscaleWidgetValues } from './types';++import { getUpscaleOutputDimensions, getUpscaleValidationReasons } from './settings';++export const getUpscaleDenoisingStart = (creativity: number): number => ((creativity * -1 + 10) * 4.99) / 100;++export const getUpscaleControlNetValues = (structure: number) => {+ const splitPoint = (structure + 10) * 0.025 + 0.3;++ return {+ first: {+ beginStepPercent: 0,+ controlWeight: (structure + 10) * 0.0325 + 0.3,+ endStepPercent: splitPoint,+ },+ second: {+ beginStepPercent: splitPoint,+ controlWeight: ((structure + 10) * 0.0325 + 0.15) * 0.45,+ endStepPercent: 0.85,+ },+ };+};++const addUpscaleMetadata = (+ graph: BackendGraphContract,+ output: BackendInvocationContract,+ settings: UpscaleWidgetValues,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): void => {+ if (!settings.model || !settings.upscaleModel || !settings.inputImage) {+ return;+ }++ const dimensions = getUpscaleOutputDimensions(settings.inputImage, settings.scale);+ const activeLoras = getActiveCompatibleLoras(+ {+ ...settings,+ aspectRatioId: 'Free',+ aspectRatioIsLocked: false,+ aspectRatioValue: dimensions.width / dimensions.height,+ cfgRescaleMultiplier: 0,+ colorCompensation: false,+ componentSourceModel: null,+ height: dimensions.height,+ modelKey: settings.model.key,+ negativePromptHeightPx: 56,+ positivePromptHeightPx: 96,+ referenceImages: [],+ seamlessXAxis: false,+ seamlessYAxis: false,+ t5EncoderModel: null,+ clipEmbedModel: null,+ clipLEmbedModel: null,+ clipGEmbedModel: null,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ width: dimensions.width,+ },+ settings.model+ );+ const metadata = addNode(graph, {+ cfg_scale: settings.cfgScale,+ creativity: settings.creativity,+ id: 'core_metadata',+ loras: activeLoras.map((lora) => ({ model: toModelIdentifier(lora.model), weight: lora.weight })),+ model: toModelIdentifier(settings.model),+ rand_device: projectSettings.useCpuNoise ? 'cpu' : 'cuda',+ scheduler: coerceSchedulerForGraph(settings.model, settings.scheduler),+ steps: settings.steps,+ structure: settings.structure,+ tile_overlap: settings.tileOverlap,+ tile_size: settings.tileSize,+ type: 'core_metadata',+ upscale_initial_image: {+ height: settings.inputImage.height,+ image_name: settings.inputImage.image_name,+ width: settings.inputImage.width,+ },+ upscale_model: toModelIdentifier(settings.upscaleModel),+ upscale_scale: settings.scale,+ vae: settings.vae ? toModelIdentifier(settings.vae) : undefined,+ });++ addEdge(graph, graph.nodes.positive_prompt, 'value', metadata, 'positive_prompt');+ addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');+ addEdge(graph, graph.nodes.seed, 'value', metadata, 'seed');+ addEdge(graph, graph.nodes.spandrel_autoscale, 'width', metadata, 'width');+ addEdge(graph, graph.nodes.spandrel_autoscale, 'height', metadata, 'height');+ addEdge(graph, metadata, 'metadata', output, 'metadata');+};++export const compileUpscaleGraph = (+ settings: UpscaleWidgetValues,+ destination: ResultDestination,+ projectSettings: Pick<ProjectSettings, 'useCpuNoise'>+): CompiledUpscaleGraph => {+ const reasons = getUpscaleValidationReasons(settings);++ if (reasons.length > 0) {+ throw new Error(reasons[0]);+ }++ const { inputImage, model, tileControlnetModel, upscaleModel } = settings;++ if (!inputImage || !model || !tileControlnetModel || !upscaleModel) {+ throw new Error('Upscale settings are incomplete.');+ }++ const graph: BackendGraphContract = { edges: [], id: 'upscale-graph', nodes: {} };+ const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });+ const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });+ const seed = addNode(graph, { id: 'seed', type: 'integer' });+ const spandrelAutoscale = addNode(graph, {+ fit_to_multiple_of_8: true,+ id: 'spandrel_autoscale',+ image: { image_name: inputImage.image_name },+ image_to_image_model: toModelIdentifier(upscaleModel),+ scale: settings.scale,+ type: 'spandrel_image_to_image_autoscale',+ });+ const unsharpMask = addNode(graph, { id: 'unsharp_2', radius: 2, strength: 60, type: 'unsharp_mask' });+ const noise = addNode(graph, { id: 'noise', type: 'noise', use_cpu: projectSettings.useCpuNoise });+ const imageToLatents = addNode(graph, {+ fp32: settings.vaePrecision === 'fp32',+ id: 'i2l',+ tile_size: settings.tileSize,+ tiled: true,+ type: 'i2l',+ });+ const output = addNode(graph, {+ fp32: settings.vaePrecision === 'fp32',+ id: 'upscale_output',+ is_intermediate: destination === 'canvas',+ tile_size: settings.tileSize,+ tiled: true,+ type: 'l2i',+ use_cache: false,+ });+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ denoising_end: 1,+ denoising_start: getUpscaleDenoisingStart(settings.creativity),+ id: 'tiled_multidiffusion_denoise_latents',+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),+ steps: settings.steps,+ tile_height: settings.tileSize,+ tile_overlap: settings.tileOverlap,+ tile_width: settings.tileSize,+ type: 'tiled_multi_diffusion_denoise_latents',+ });+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model: toModelIdentifier(model),+ type: model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader',+ });+ const compelType = model.base === 'sdxl' ? 'sdxl_compel_prompt' : 'compel';+ const posCond = addNode(graph, { id: 'pos_cond', type: compelType });+ const negCond = addNode(graph, { id: 'neg_cond', type: compelType });+ const activeLoras = settings.loras.filter(+ (lora) =>+ lora.isEnabled && (lora.model.base === model.base || (model.base === 'sdxl' && lora.model.base === 'sdxl'))+ );+ let unetSource: BackendInvocationContract = modelLoader;+ let clipSource: BackendInvocationContract = modelLoader;+ let clip2Source: BackendInvocationContract | undefined = model.base === 'sdxl' ? modelLoader : undefined;++ addEdge(graph, spandrelAutoscale, 'image', unsharpMask, 'image');+ addEdge(graph, seed, 'value', noise, 'seed');+ addEdge(graph, unsharpMask, 'width', noise, 'width');+ addEdge(graph, unsharpMask, 'height', noise, 'height');+ addEdge(graph, unsharpMask, 'image', imageToLatents, 'image');++ if (model.base === 'sdxl') {+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, positivePrompt, 'value', posCond, 'style');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'style');+ } else {+ const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: settings.clipSkip, type: 'clip_skip' });++ addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');+ clipSource = clipSkip;+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ }++ if (activeLoras.length > 0) {+ const loraLoader = addLoraCollectionLoader(graph, activeLoras, model, {+ clip: clipSource,+ clip2: clip2Source,+ unet: unetSource,+ });++ unetSource = loraLoader;+ clipSource = loraLoader;+ clip2Source = model.base === 'sdxl' ? loraLoader : undefined;+ }++ addEdge(graph, unetSource, 'unet', denoise, 'unet');+ addEdge(graph, clipSource, 'clip', posCond, 'clip');+ addEdge(graph, clipSource, 'clip', negCond, 'clip');+ if (model.base === 'sdxl') {+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', posCond, 'clip2');+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', negCond, 'clip2');+ }++ const vaeLoader =+ settings.vae && settings.vae.base === model.base+ ? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: toModelIdentifier(settings.vae) })+ : null;+ const vaeSource = vaeLoader ?? modelLoader;++ addEdge(graph, vaeSource, 'vae', imageToLatents, 'vae');+ addEdge(graph, vaeSource, 'vae', output, 'vae');+ addEdge(graph, noise, 'noise', denoise, 'noise');+ addEdge(graph, imageToLatents, 'latents', denoise, 'latents');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, denoise, 'latents', output, 'latents');++ const control = getUpscaleControlNetValues(settings.structure);+ const controlNet1 = addNode(graph, {+ begin_step_percent: control.first.beginStepPercent,+ control_mode: 'balanced',+ control_model: toModelIdentifier(tileControlnetModel),+ control_weight: control.first.controlWeight,+ end_step_percent: control.first.endStepPercent,+ id: 'controlnet_1',+ resize_mode: 'just_resize',+ type: 'controlnet',+ });+ const controlNet2 = addNode(graph, {+ begin_step_percent: control.second.beginStepPercent,+ control_mode: 'balanced',+ control_model: toModelIdentifier(tileControlnetModel),+ control_weight: control.second.controlWeight,+ end_step_percent: control.second.endStepPercent,+ id: 'controlnet_2',+ resize_mode: 'just_resize',+ type: 'controlnet',+ });+ const controlNetCollector = addNode(graph, { id: 'controlnet_collector', type: 'collect' });++ addEdge(graph, unsharpMask, 'image', controlNet1, 'image');+ addEdge(graph, unsharpMask, 'image', controlNet2, 'image');+ addEdge(graph, controlNet1, 'control', controlNetCollector, 'item');+ addEdge(graph, controlNet2, 'control', controlNetCollector, 'item');+ addEdge(graph, controlNetCollector, 'collection', denoise, 'control');+ addUpscaleMetadata(graph, output, settings, projectSettings);++ return {+ backendGraph: graph,+ graph: toGraphContract(graph, `${model.name} multi-diffusion upscale`),+ negativePromptNodeId: 'negative_prompt',+ outputNodeId: 'upscale_output',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/upscale/index.ts b/invokeai/frontend/webv2/src/workbench/upscale/index.tsnew file mode 100644index 0000000000..3f02e7e171--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/index.ts@@ -0,0 +1,3 @@+export { compileUpscaleGraph } from './graph';+export * from './settings';+export type * from './types';diff --git a/invokeai/frontend/webv2/src/workbench/upscale/integration.test.ts b/invokeai/frontend/webv2/src/workbench/upscale/integration.test.tsnew file mode 100644index 0000000000..88792e9900--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/integration.test.ts@@ -0,0 +1,100 @@+import type { ModelConfig } from '@workbench/models/types';++import { createQueueItemBackendSubmission, getQueueItemResultImageOptions } from '@workbench/WorkbenchRuntime';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState';+import { describe, expect, it, vi } from 'vitest';++import { createDefaultUpscaleWidgetValues } from './settings';++const model = (key: string, type: string, base: string, name = key): ModelConfig => ({+ base,+ file_size: 1,+ format: 'checkpoint',+ hash: `${key}-hash`,+ key,+ name,+ path: key,+ source: key,+ source_type: 'path',+ type,+});++const MODELS = [+ model('sdxl', 'main', 'sdxl'),+ model('spandrel', 'spandrel_image_to_image', 'any'),+ model('tile', 'controlnet', 'sdxl', 'SDXL Tile ControlNet'),+];++describe('Upscale snapshot submission', () => {+ it('captures a resolved immutable snapshot, prompt history, graph preview, and generate-style backend request', () => {+ vi.spyOn(Math, 'random').mockReturnValue(0.25);+ let state = createInitialWorkbenchState();+ const projectId = state.activeProjectId;+ const values = {+ ...createDefaultUpscaleWidgetValues(MODELS),+ batchCount: 3,+ inputImage: { height: 100, image_name: 'input.png', width: 200 },+ negativePrompt: 'stale Upscale prompt',+ positivePrompt: 'stale Upscale prompt',+ };++ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { ...values },+ widgetId: 'upscale',+ });+ state = workbenchReducer(state, {+ projectId,+ type: 'patchProjectPromptDraft',+ values: { negativePrompt: 'blur', positivePrompt: 'fine detail' },+ });+ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });+ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ models: MODELS,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ });+ state = workbenchReducer(state, {+ projectId,+ type: 'patchProjectPromptDraft',+ values: { negativePrompt: 'changed later', positivePrompt: 'changed later' },+ });++ const project = state.projects.find((candidate) => candidate.id === projectId)!;+ const queueItem = project.queue.items[0]!;+ const snapshotValues = queueItem.snapshot.widgetStates.upscale?.values;++ expect(queueItem.snapshot.sourceId).toBe('upscale');+ expect(snapshotValues).toMatchObject({+ batchCount: 3,+ inputImage: { image_name: 'input.png' },+ negativePrompt: 'blur',+ positivePrompt: 'fine detail',+ seed: Math.floor(0.25 * 4_294_967_295),+ });+ expect(project.promptHistory[0]).toEqual({ negativePrompt: 'blur', positivePrompt: 'fine detail' });+ expect(project.widgetGraphs.upscale?.backendGraph?.nodes.upscale_output).toMatchObject({+ is_intermediate: false,+ type: 'l2i',+ });+ expect(getQueueItemResultImageOptions(queueItem)).toEqual({ resultNodeIds: ['upscale_output'] });+ expect(createQueueItemBackendSubmission(project, queueItem)).toMatchObject({+ kind: 'generate',+ request: {+ batchCount: 3,+ negativePrompt: 'blur',+ positivePrompt: 'fine detail',+ seedNodeId: 'seed',+ },+ });+ expect(getProjectPromptValues(project)).toMatchObject({+ negativePrompt: 'changed later',+ positivePrompt: 'changed later',+ });+ });+});++const getProjectPromptValues = (project: ReturnType<typeof createInitialWorkbenchState>['projects'][number]) =>+ project.widgetInstances.generate?.state.values;diff --git a/invokeai/frontend/webv2/src/workbench/upscale/settings.test.ts b/invokeai/frontend/webv2/src/workbench/upscale/settings.test.tsnew file mode 100644index 0000000000..3d175df83e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/settings.test.ts@@ -0,0 +1,108 @@+import type { GenerateLora, VaeModelConfig } from '@workbench/generation/types';+import type { ModelConfig } from '@workbench/models/types';++import { describe, expect, it } from 'vitest';++import {+ clearDeletedUpscaleInput,+ createDefaultUpscaleWidgetValues,+ getUpscaleOutputDimensions,+ getUpscaleValidationReasons,+ normalizeUpscaleWidgetValues,+ syncUpscaleWidgetValuesWithModels,+ UPSCALE_PRESETS,+} from './settings';++const model = (key: string, type: string, base: string, name = key): ModelConfig => ({+ base,+ file_size: 1,+ format: 'checkpoint',+ hash: `${key}-hash`,+ key,+ name,+ path: key,+ source: key,+ source_type: 'path',+ type,+});++const MODELS = [+ model('sd15', 'main', 'sd-1'),+ model('spandrel', 'spandrel_image_to_image', 'any'),+ model('tile', 'controlnet', 'sd-1', 'ControlNet Tile'),+ model('lora', 'lora', 'sd-1'),+ model('vae', 'vae', 'sd-1'),+];++describe('upscale settings', () => {+ it('preserves the legacy defaults and named presets', () => {+ expect(createDefaultUpscaleWidgetValues()).toMatchObject({+ batchCount: 1,+ cfgScale: 2,+ creativity: 0,+ negativePromptHeightPx: 56,+ positivePromptHeightPx: 96,+ scale: 4,+ scheduler: 'kdpm_2',+ shouldRandomizeSeed: true,+ steps: 30,+ structure: 0,+ tileOverlap: 128,+ tileSize: 1024,+ });+ expect(UPSCALE_PRESETS).toEqual({+ artistic: { creativity: 8, structure: -5 },+ balanced: { creativity: 0, structure: 0 },+ conservative: { creativity: -5, structure: 5 },+ creative: { creativity: 5, structure: -2 },+ });+ });++ it('normalizes partial persisted values and calculates multiple-of-eight output dimensions', () => {+ expect(+ normalizeUpscaleWidgetValues({ negativePromptHeightPx: 4, positivePrompt: 'detail', positivePromptHeightPx: 999 })+ ).toMatchObject({+ negativePromptHeightPx: 56,+ positivePrompt: 'detail',+ positivePromptHeightPx: 360,+ scale: 4,+ tileSize: 1024,+ });+ expect(getUpscaleOutputDimensions({ height: 101, width: 203 }, 2.5)).toEqual({ height: 248, width: 504 });+ });++ it('reconciles required models, refreshes configs, and removes incompatible selections', () => {+ const defaults = createDefaultUpscaleWidgetValues(MODELS);+ const stale = {+ ...defaults,+ loras: [+ { isEnabled: true, model: model('missing', 'lora', 'sd-1') as GenerateLora['model'], weight: 1 },+ { isEnabled: true, model: model('lora', 'lora', 'sd-1', 'Old name') as GenerateLora['model'], weight: 0.5 },+ ],+ vae: model('vae', 'vae', 'sd-1', 'Old VAE') as VaeModelConfig,+ };+ const synced = syncUpscaleWidgetValuesWithModels(stale, MODELS);++ expect(synced.model?.key).toBe('sd15');+ expect(synced.upscaleModel?.key).toBe('spandrel');+ expect(synced.tileControlnetModel?.key).toBe('tile');+ expect(synced.loras).toHaveLength(1);+ expect(synced.loras[0]?.model.name).toBe('lora');+ expect(synced.vae?.name).toBe('vae');+ });++ it('validates required fields and ranges and clears a deleted input image', () => {+ const defaults = createDefaultUpscaleWidgetValues();++ expect(getUpscaleValidationReasons({ ...defaults, scale: 17 })).toEqual(+ expect.arrayContaining([+ 'Upscale needs an input image. Upload one or send one from Gallery.',+ 'Scale must be between 1 and 16.',+ ])+ );++ const values = { ...defaults, inputImage: { height: 10, image_name: 'delete.png', width: 10 } };++ expect(clearDeletedUpscaleInput(values, new Set(['delete.png'])).inputImage).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/upscale/settings.ts b/invokeai/frontend/webv2/src/workbench/upscale/settings.tsnew file mode 100644index 0000000000..afc5ca2e94--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/settings.ts@@ -0,0 +1,352 @@+import type {+ GenerateLora,+ ImageWithDims,+ MainModelConfig,+ ModelIdentifierConfig,+ VaePrecision,+} from '@workbench/generation/types';+import type { ModelConfig } from '@workbench/models/types';++import { sanitizeBatchCount } from '@workbench/generation/batch';+import { isVaeCompatibleWithGenerateModel } from '@workbench/generation/componentCompatibility';+import {+ DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,+ DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,+ isLoraCompatibleWithModel,+ isLoraModelConfig,+ isMainModelConfig,+ isModelIdentifierConfig,+ isVaeModelConfig,+ MAX_NEGATIVE_PROMPT_HEIGHT_PX,+ MAX_POSITIVE_PROMPT_HEIGHT_PX,+ MIN_NEGATIVE_PROMPT_HEIGHT_PX,+ MIN_POSITIVE_PROMPT_HEIGHT_PX,+ SEED_MAX,+} from '@workbench/generation/settings';++import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleWidgetValues } from './types';++export const UPSCALE_SCALE_SLIDER_MIN = 2;+export const UPSCALE_SCALE_SLIDER_MAX = 8;+export const UPSCALE_SCALE_MIN = 1;+export const UPSCALE_SCALE_MAX = 16;+export const UPSCALE_CREATIVITY_MIN = -10;+export const UPSCALE_CREATIVITY_MAX = 10;+export const UPSCALE_STRUCTURE_MIN = -10;+export const UPSCALE_STRUCTURE_MAX = 10;+export const UPSCALE_TILE_SIZE_MIN = 512;+export const UPSCALE_TILE_SIZE_MAX = 1536;+export const UPSCALE_TILE_OVERLAP_MIN = 16;+export const UPSCALE_TILE_OVERLAP_MAX = 512;++export const UPSCALE_PRESETS = {+ conservative: { creativity: -5, structure: 5 },+ balanced: { creativity: 0, structure: 0 },+ creative: { creativity: 5, structure: -2 },+ artistic: { creativity: 8, structure: -5 },+} as const;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);++const normalizePromptHeight = (value: unknown, min: number, max: number, fallback: number): number =>+ isFiniteNumber(value) ? Math.min(max, Math.max(min, value)) : fallback;++export const isSupportedUpscaleMainModel = (value: unknown): value is MainModelConfig =>+ isMainModelConfig(value) && (value.base === 'sd-1' || value.base === 'sdxl');++export const isSpandrelModelConfig = (value: unknown): value is SpandrelModelConfig =>+ isModelIdentifierConfig(value) && value.type === 'spandrel_image_to_image';++export const isTileControlNetModelConfig = (value: unknown): value is TileControlNetModelConfig =>+ isModelIdentifierConfig(value) && value.type === 'controlnet';++export const isTileControlNetCandidate = (+ value: unknown,+ model: Pick<MainModelConfig, 'base'> | null+): value is TileControlNetModelConfig => {+ if (!model || !isTileControlNetModelConfig(value) || value.base !== model.base) {+ return false;+ }++ const name = value.name.toLowerCase();++ return name.includes('tile') || name.includes('union');+};++export const isUpscaleImage = (value: unknown): value is ImageWithDims =>+ isRecord(value) &&+ typeof value.image_name === 'string' &&+ value.image_name.length > 0 &&+ isFiniteNumber(value.width) &&+ value.width > 0 &&+ isFiniteNumber(value.height) &&+ value.height > 0;++const isVaePrecision = (value: unknown): value is VaePrecision => value === 'fp16' || value === 'fp32';++const normalizeLoras = (value: unknown): GenerateLora[] =>+ Array.isArray(value)+ ? value.filter(+ (item): item is GenerateLora =>+ isRecord(item) &&+ isLoraModelConfig(item.model) &&+ typeof item.isEnabled === 'boolean' &&+ isFiniteNumber(item.weight)+ )+ : [];++export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[] = []): UpscaleWidgetValues => {+ const model = (models.find(isSupportedUpscaleMainModel) as MainModelConfig | undefined) ?? null;++ return {+ batchCount: 1,+ cfgScale: 2,+ clipSkip: 0,+ creativity: 0,+ inputImage: null,+ loras: [],+ model,+ negativePrompt: '',+ negativePromptEnabled: true,+ negativePromptHeightPx: DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,+ positivePrompt: '',+ positivePromptHeightPx: DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,+ scale: 4,+ scheduler: 'kdpm_2',+ seed: 0,+ shouldRandomizeSeed: true,+ steps: 30,+ structure: 0,+ tileControlnetModel: models.find((candidate) => isTileControlNetCandidate(candidate, model)) ?? null,+ tileOverlap: 128,+ tileSize: 1024,+ upscaleModel: (models.find(isSpandrelModelConfig) as SpandrelModelConfig | undefined) ?? null,+ vae: null,+ vaePrecision: 'fp32',+ };+};++/**+ * Heals older/partial persisted values without silently clamping invalid user+ * input. Range checks remain invocation validation so actionable errors can be+ * shown instead of changing a saved project behind the user's back.+ */+export const normalizeUpscaleWidgetValues = (value: unknown): UpscaleWidgetValues | null => {+ if (!isRecord(value)) {+ return null;+ }++ const defaults = createDefaultUpscaleWidgetValues();++ return {+ batchCount: sanitizeBatchCount(value.batchCount),+ cfgScale: isFiniteNumber(value.cfgScale) ? value.cfgScale : defaults.cfgScale,+ clipSkip: isFiniteNumber(value.clipSkip) ? value.clipSkip : defaults.clipSkip,+ creativity: isFiniteNumber(value.creativity) ? value.creativity : defaults.creativity,+ inputImage:+ value.inputImage === null || value.inputImage === undefined+ ? null+ : isUpscaleImage(value.inputImage)+ ? value.inputImage+ : null,+ loras: normalizeLoras(value.loras),+ model: isMainModelConfig(value.model) ? value.model : null,+ negativePrompt: typeof value.negativePrompt === 'string' ? value.negativePrompt : defaults.negativePrompt,+ negativePromptEnabled:+ typeof value.negativePromptEnabled === 'boolean' ? value.negativePromptEnabled : defaults.negativePromptEnabled,+ negativePromptHeightPx: normalizePromptHeight(+ value.negativePromptHeightPx,+ MIN_NEGATIVE_PROMPT_HEIGHT_PX,+ MAX_NEGATIVE_PROMPT_HEIGHT_PX,+ defaults.negativePromptHeightPx+ ),+ positivePrompt: typeof value.positivePrompt === 'string' ? value.positivePrompt : defaults.positivePrompt,+ positivePromptHeightPx: normalizePromptHeight(+ value.positivePromptHeightPx,+ MIN_POSITIVE_PROMPT_HEIGHT_PX,+ MAX_POSITIVE_PROMPT_HEIGHT_PX,+ defaults.positivePromptHeightPx+ ),+ scale: isFiniteNumber(value.scale) ? value.scale : defaults.scale,+ scheduler: typeof value.scheduler === 'string' ? value.scheduler : defaults.scheduler,+ seed: isFiniteNumber(value.seed) ? value.seed : defaults.seed,+ shouldRandomizeSeed:+ typeof value.shouldRandomizeSeed === 'boolean' ? value.shouldRandomizeSeed : defaults.shouldRandomizeSeed,+ steps: isFiniteNumber(value.steps) ? value.steps : defaults.steps,+ structure: isFiniteNumber(value.structure) ? value.structure : defaults.structure,+ tileControlnetModel: isTileControlNetModelConfig(value.tileControlnetModel) ? value.tileControlnetModel : null,+ tileOverlap: isFiniteNumber(value.tileOverlap) ? value.tileOverlap : defaults.tileOverlap,+ tileSize: isFiniteNumber(value.tileSize) ? value.tileSize : defaults.tileSize,+ upscaleModel: isSpandrelModelConfig(value.upscaleModel) ? value.upscaleModel : null,+ vae: isVaeModelConfig(value.vae) ? value.vae : null,+ vaePrecision: isVaePrecision(value.vaePrecision) ? value.vaePrecision : defaults.vaePrecision,+ };+};++export const syncUpscaleWidgetValuesWithModels = (+ values: UpscaleWidgetValues,+ models: readonly ModelConfig[]+): UpscaleWidgetValues => {+ const modelsByKey = new Map(models.map((model) => [model.key, model]));+ const storedMain = values.model ? modelsByKey.get(values.model.key) : undefined;+ const model: MainModelConfig | null = isSupportedUpscaleMainModel(storedMain)+ ? storedMain+ : ((models.find(isSupportedUpscaleMainModel) as MainModelConfig | undefined) ?? null);+ const storedSpandrel = values.upscaleModel ? modelsByKey.get(values.upscaleModel.key) : undefined;+ const upscaleModel: SpandrelModelConfig | null = isSpandrelModelConfig(storedSpandrel)+ ? storedSpandrel+ : ((models.find(isSpandrelModelConfig) as SpandrelModelConfig | undefined) ?? null);+ const storedControlNet = values.tileControlnetModel ? modelsByKey.get(values.tileControlnetModel.key) : undefined;+ const tileControlnetModel = isTileControlNetCandidate(storedControlNet, model)+ ? storedControlNet+ : (models.find((candidate) => isTileControlNetCandidate(candidate, model)) ?? null);+ const storedVae = values.vae ? modelsByKey.get(values.vae.key) : undefined;+ const vae =+ storedVae && isVaeModelConfig(storedVae) && model && isVaeCompatibleWithGenerateModel(model, storedVae)+ ? storedVae+ : null;+ const loras = model+ ? values.loras.flatMap((lora) => {+ const installed = modelsByKey.get(lora.model.key);++ return installed && isLoraModelConfig(installed) && isLoraCompatibleWithModel(installed, model)+ ? [{ ...lora, model: installed }]+ : [];+ })+ : [];++ if (+ values.model === model &&+ values.upscaleModel === upscaleModel &&+ values.tileControlnetModel === tileControlnetModel &&+ values.vae === vae &&+ loras.length === values.loras.length &&+ loras.every((lora, index) => lora.model === values.loras[index]?.model)+ ) {+ return values;+ }++ return { ...values, loras, model, tileControlnetModel, upscaleModel, vae };+};++const addRangeReason = (reasons: string[], label: string, value: number, min: number, max: number): void => {+ if (!Number.isFinite(value) || value < min || value > max) {+ reasons.push(`${label} must be between ${min} and ${max}.`);+ }+};++export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?: readonly ModelConfig[]): string[] => {+ const reasons: string[] = [];++ if (!values.inputImage) {+ reasons.push('Upscale needs an input image. Upload one or send one from Gallery.');+ }+ if (!values.upscaleModel) {+ reasons.push('Upscale needs a Spandrel image-to-image model.');+ }+ if (!values.model) {+ reasons.push('Upscale needs an SD1.5 or SDXL main model.');+ } else if (!isSupportedUpscaleMainModel(values.model)) {+ reasons.push('Upscale supports only SD1.5 and SDXL main models.');+ }+ if (!values.tileControlnetModel) {+ reasons.push('Upscale needs a Tile or Union ControlNet compatible with the main model.');+ } else if (!isTileControlNetCandidate(values.tileControlnetModel, values.model)) {+ reasons.push('The Tile ControlNet must match the main model base and be a Tile or Union model.');+ }++ addRangeReason(reasons, 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);+ addRangeReason(reasons, 'Creativity', values.creativity, UPSCALE_CREATIVITY_MIN, UPSCALE_CREATIVITY_MAX);+ addRangeReason(reasons, 'Structure', values.structure, UPSCALE_STRUCTURE_MIN, UPSCALE_STRUCTURE_MAX);+ addRangeReason(reasons, 'Tile size', values.tileSize, UPSCALE_TILE_SIZE_MIN, UPSCALE_TILE_SIZE_MAX);+ addRangeReason(reasons, 'Tile overlap', values.tileOverlap, UPSCALE_TILE_OVERLAP_MIN, UPSCALE_TILE_OVERLAP_MAX);+ addRangeReason(reasons, 'Steps', values.steps, 1, 1000);+ addRangeReason(reasons, 'CFG scale', values.cfgScale, 0, 100);+ addRangeReason(reasons, 'Seed', values.seed, 0, SEED_MAX);++ if (models) {+ const installedByKey = new Map(models.map((model) => [model.key, model]));+ const required: ModelIdentifierConfig[] = [+ ...(values.model ? [values.model] : []),+ ...(values.upscaleModel ? [values.upscaleModel] : []),+ ...(values.tileControlnetModel ? [values.tileControlnetModel] : []),+ ];++ for (const selected of required) {+ const installed = installedByKey.get(selected.key);++ if (!installed) {+ reasons.push(`${selected.name} is no longer installed.`);+ }+ }++ const installedMain = values.model ? installedByKey.get(values.model.key) : undefined;+ const installedSpandrel = values.upscaleModel ? installedByKey.get(values.upscaleModel.key) : undefined;+ const installedControlNet = values.tileControlnetModel+ ? installedByKey.get(values.tileControlnetModel.key)+ : undefined;++ if (values.model && installedMain && !isSupportedUpscaleMainModel(installedMain)) {+ reasons.push(`${values.model.name} is not an installed SD1.5 or SDXL main model.`);+ }+ if (values.upscaleModel && installedSpandrel && !isSpandrelModelConfig(installedSpandrel)) {+ reasons.push(`${values.upscaleModel.name} is not an installed Spandrel model.`);+ }+ if (+ values.tileControlnetModel &&+ installedControlNet &&+ !isTileControlNetCandidate(installedControlNet, values.model)+ ) {+ reasons.push(`${values.tileControlnetModel.name} is not an installed compatible Tile or Union ControlNet.`);+ }+ if (values.vae) {+ const installedVae = installedByKey.get(values.vae.key);++ if (!installedVae) {+ reasons.push(`${values.vae.name} is no longer installed.`);+ } else if (+ !values.model ||+ !isVaeModelConfig(installedVae) ||+ !isVaeCompatibleWithGenerateModel(values.model, installedVae)+ ) {+ reasons.push(`${values.vae.name} is not compatible with ${values.model?.name ?? 'the main model'}.`);+ }+ }+ for (const lora of values.loras) {+ const installedLora = installedByKey.get(lora.model.key);++ if (!installedLora) {+ reasons.push(`${lora.model.name} is no longer installed.`);+ } else if (+ !isLoraModelConfig(installedLora) ||+ (values.model && !isLoraCompatibleWithModel(installedLora, values.model))+ ) {+ reasons.push(`${lora.model.name} is not compatible with ${values.model?.name ?? 'the main model'}.`);+ }+ }+ }++ return reasons;+};++export const getUpscaleOutputDimensions = (+ image: Pick<ImageWithDims, 'width' | 'height'>,+ scale: number+): { width: number; height: number } => ({+ height: Math.floor((image.height * scale) / 8) * 8,+ width: Math.floor((image.width * scale) / 8) * 8,+});++export const clearDeletedUpscaleInput = (+ values: UpscaleWidgetValues,+ deletedImageNames: ReadonlySet<string>+): UpscaleWidgetValues =>+ values.inputImage && deletedImageNames.has(values.inputImage.image_name) ? { ...values, inputImage: null } : values;++export const resolveUpscaleSeed = (values: UpscaleWidgetValues): number =>+ values.shouldRandomizeSeed ? Math.floor(Math.random() * SEED_MAX) : values.seed;++export const cloneUpscaleWidgetValues = (values: UpscaleWidgetValues): UpscaleWidgetValues => structuredClone(values);diff --git a/invokeai/frontend/webv2/src/workbench/upscale/types.ts b/invokeai/frontend/webv2/src/workbench/upscale/types.tsnew file mode 100644index 0000000000..f996fac7f3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/upscale/types.ts@@ -0,0 +1,46 @@+import type {+ CompiledGenerateGraph,+ GenerateLora,+ ImageWithDims,+ MainModelConfig,+ ModelIdentifierConfig,+ VaeModelConfig,+ VaePrecision,+} from '@workbench/generation/types';++export type SpandrelModelConfig = ModelIdentifierConfig & { type: 'spandrel_image_to_image' };+export type TileControlNetModelConfig = ModelIdentifierConfig & { type: 'controlnet' };++/** Project-persisted settings owned by the Upscale widget. */+export interface UpscaleWidgetValues {+ inputImage: ImageWithDims | null;+ upscaleModel: SpandrelModelConfig | null;+ scale: number;+ creativity: number;+ structure: number;++ model: MainModelConfig | null;+ positivePrompt: string;+ positivePromptHeightPx: number;+ negativePrompt: string;+ negativePromptEnabled: boolean;+ negativePromptHeightPx: number;+ loras: GenerateLora[];+ steps: number;+ cfgScale: number;+ scheduler: string;+ batchCount: number;+ seed: number;+ shouldRandomizeSeed: boolean;+ clipSkip: number;+ vae: VaeModelConfig | null;+ vaePrecision: VaePrecision;++ tileControlnetModel: TileControlNetModelConfig | null;+ tileSize: number;+ tileOverlap: number;+}++export interface CompiledUpscaleGraph extends CompiledGenerateGraph {+ outputNodeId: 'upscale_output';+}diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.tsindex f84cce1af4..d925b8c4e9 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts@@ -1,8 +1,10 @@+import { ImageUpscaleIcon } from 'lucide-react';import { describe, expect, it } from 'vitest';import type { WidgetManifest } from './types';import { getWidgetHosts, registerFirstPartyWidgets, registerWidgets } from './widgetRegistry';+import { upscaleWidgetManifest } from './widgets/upscale';const TestIcon = () => null;const TestView = () => null;@@ -23,11 +25,15 @@ describe('widget registry', () => {it('registers first-party widget manifests without icon validation failures', () => {const widgets = registerFirstPartyWidgets();- expect(widgets).toHaveLength(13);+ expect(widgets).toHaveLength(14);expect(widgets.flatMap((widget) => widget.failure ?? [])).toEqual([]);expect(widgets.every((widget) => widget.status === 'enabled')).toBe(true);});+ it('uses the image-upscale icon for Upscale', () => {+ expect(upscaleWidgetManifest.icon).toBe(ImageUpscaleIcon);+ });+it('normalizes default state and api version', () => {const [widget] = registerWidgets([createManifest({ state: undefined })]);diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.tsindex 2bc727239d..e1a6601b9c 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts@@ -19,12 +19,14 @@ import { previewWidgetManifest } from './widgets/preview';import { projectWidgetManifest } from './widgets/project';import { queueWidgetManifest } from './widgets/queue';import { serverStatusWidgetManifest } from './widgets/server-status';+import { upscaleWidgetManifest } from './widgets/upscale';import { versionStatusWidgetManifest } from './widgets/version-status';import { workflowWidgetManifest } from './widgets/workflow';export const firstPartyWidgetManifests: WidgetManifest[] = [generateWidgetManifest,workflowWidgetManifest,+ upscaleWidgetManifest,canvasWidgetManifest,diagnosticsWidgetManifest,galleryWidgetManifest,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.tsindex c175cd90e8..ffa8fb19e1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/galleryStateView.ts@@ -2,7 +2,7 @@ import type { GalleryBoard, GalleryImage, GalleryView } from '@workbench/galleryimport type { GeneratedImageContract, QueueItem } from '@workbench/types';import { getGallerySettings, type GallerySettings } from '@workbench/gallery/settings';-import { sanitizeBatchCount } from '@workbench/generation/batch';+import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@workbench/queueSnapshot';const UNCATEGORIZED_BOARD: GalleryBoard = {archived: false,@@ -107,9 +107,6 @@ export const getGalleryRecentImagesKey = (values: Record<string, unknown>): strireturn (values.recentImages as GeneratedImageContract[]).map((image) => image.imageName).join('\0');};-const getFiniteNumber = (value: unknown, fallback: number): number =>- typeof value === 'number' && Number.isFinite(value) ? value : fallback;-export const getGalleryQueuePlaceholders = (queueItems: QueueItem[],{@@ -140,12 +137,10 @@ export const getGalleryQueuePlaceholders = (continue;}- const generateValues = item.snapshot.widgetStates.generate?.values ?? {};const expectedImageCount = item.backendItemIds?.length? item.backendItemIds.length- : sanitizeBatchCount(generateValues.batchCount);- const width = getFiniteNumber(generateValues.width, 1024);- const height = getFiniteNumber(generateValues.height, 1024);+ : getQueueItemSnapshotBatchCount(item);+ const { width, height } = getQueueItemSnapshotDimensions(item, { height: 1024, width: 1024 });const completedBackendItemIds = new Set(item.completedBackendItemIds ?? []);const cancelledBackendItemIds = new Set(item.cancelledBackendItemIds ?? []);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsxindex 33ab3344f1..17beac4ad2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx@@ -11,9 +11,9 @@ type Props = {const COLLAPSIBLE_INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' };-export const GenerateCollapsibleSection = ({ label, defaultOpen, isOpen, children, badges }: Props) => {+export const GenerateCollapsibleSection = ({ badges, children, defaultOpen, isOpen, label }: Props) => {return (- <Collapsible.Root defaultOpen={defaultOpen} open={isOpen} bg="bg.muted/50" rounded="md" overflow="hidden">+ <Collapsible.Root bg="bg.muted/50" defaultOpen={defaultOpen} open={isOpen} overflow="hidden" rounded="md"><Collapsible.Trigger display="flex" gap={2} w="full" px={2} h="8" alignItems="center"><Collapsible.Indicator_open={COLLAPSIBLE_INDICATOR_OPEN_STYLES}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.tsindex 0965a48ef9..4722dd331d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/useLocalGenerateValues.ts@@ -21,7 +21,7 @@ export const useLocalGenerateValues = (origin?: string | null): GenerateWidgetVafor (const project of snapshot.state.projects) {const localItem = project.queue.items.find((queueItem) => queueItem.id === localId);- if (localItem) {+ if (localItem && (localItem.snapshot.sourceId === 'generate' || localItem.snapshot.sourceId === 'canvas')) {const generate = (localItem.snapshot.widgetStates as Record<string, { values?: unknown }>).generate;return (generate?.values as GenerateWidgetValues | undefined) ?? null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsxnew file mode 100644index 0000000000..e2f23cf389--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/upscale/UpscaleWidgetView.tsx@@ -0,0 +1,999 @@+/* oxlint-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 */+import type { GenerateLora, MainModelConfig, VaePrecision } from '@workbench/generation/types';+import type { ModelConfig } from '@workbench/models/types';+import type { PromptHistoryItem } from '@workbench/types';+import type { UpscaleWidgetValues } from '@workbench/upscale/types';+import type { ChangeEvent } from 'react';++import {+ Badge,+ Box,+ ButtonGroup,+ chakra,+ DataList,+ HStack,+ Image,+ Input,+ NativeSelect,+ NumberInput,+ SimpleGrid,+ Spinner,+ Stack,+ Switch,+ Text,+} from '@chakra-ui/react';+import { useDndMonitor, useDroppable } from '@dnd-kit/core';+import { Button, Combobox, Field, IconButton, Slider, Tooltip } from '@workbench/components/ui';+import { toaster } from '@workbench/components/ui/toaster';+import { getGalleryImagesByNames, getImageThumbnailUrl, uploadGalleryImage } from '@workbench/gallery/api';+import { SCHEDULER_OPTIONS } from '@workbench/generation/baseGenerationPolicies';+import {+ areProjectPromptDraftsEqual,+ getProjectPromptDraft,+ type ProjectPromptDraft,+ type ProjectPromptDraftPatch,+} from '@workbench/generation/projectPromptDraft';+import {+ getDefaultLoraWeight,+ isLoraCompatibleWithModel,+ isLoraModelConfig,+ isMainModelConfig,+ isVaeModelConfig,+ SEED_MAX,+} from '@workbench/generation/settings';+import { useMountEffect } from '@workbench/hooks/useMountEffect';+import { ModelSelect } from '@workbench/models/components';+import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';+import {+ createDefaultUpscaleWidgetValues,+ getUpscaleOutputDimensions,+ isSpandrelModelConfig,+ isSupportedUpscaleMainModel,+ isTileControlNetCandidate,+ normalizeUpscaleWidgetValues,+ syncUpscaleWidgetValuesWithModels,+ UPSCALE_CREATIVITY_MAX,+ UPSCALE_CREATIVITY_MIN,+ UPSCALE_PRESETS,+ UPSCALE_SCALE_MAX,+ UPSCALE_SCALE_MIN,+ UPSCALE_STRUCTURE_MAX,+ UPSCALE_STRUCTURE_MIN,+ UPSCALE_TILE_OVERLAP_MAX,+ UPSCALE_TILE_OVERLAP_MIN,+ UPSCALE_TILE_SIZE_MAX,+ UPSCALE_TILE_SIZE_MIN,+} from '@workbench/upscale/settings';+import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';+import { NegativePromptField } from '@workbench/widgets/generate/promptFields/NegativePromptField';+import { PositivePromptField } from '@workbench/widgets/generate/promptFields/PositivePromptField';+import { GenerateCollapsibleSection } from '@workbench/widgets/generate/shared/GenerateCollapsibleSection';+import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { DicesIcon, ImagePlusIcon, Trash2Icon, UploadIcon, XIcon } from 'lucide-react';+import { useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++const DROP_ID = 'upscale-input-image';+const LARGE_OUTPUT_MEGAPIXELS = 50;+const DIMENSION_FORMATTER = new Intl.NumberFormat();+const MEGAPIXEL_FORMATTER = new Intl.NumberFormat(undefined, { maximumFractionDigits: 1, minimumFractionDigits: 1 });++const isSelectableMainModel = (model: ModelConfig): boolean => isSupportedUpscaleMainModel(model);++const valuesAreEqual = (left: UpscaleWidgetValues, right: UpscaleWidgetValues): boolean =>+ JSON.stringify(left) === JSON.stringify(right);++const getRangeError = (label: string, value: number, min: number, max: number): string | undefined =>+ Number.isFinite(value) && value >= min && value <= max ? undefined : `${label} must be between ${min} and ${max}.`;++const UpscaleOutputPreflight = ({ values }: { values: UpscaleWidgetValues }) => {+ const { t } = useTranslation();++ if (!values.inputImage) {+ return null;+ }++ const output = getUpscaleOutputDimensions(values.inputImage, values.scale);+ const outputMegapixels = (output.width * output.height) / 1_000_000;+ const isLargeOutput = outputMegapixels >= LARGE_OUTPUT_MEGAPIXELS;++ return (+ <Stack bg="bg.subtle" gap="2" px="2.5" py="2" rounded="md">+ <DataList.Root gap="1.5" orientation="horizontal" size="sm">+ <DataList.Item>+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs">+ {t('widgets.upscale.inputSize')}+ </DataList.ItemLabel>+ <DataList.ItemValue+ fontFamily="mono"+ fontSize="xs"+ fontVariantNumeric="tabular-nums"+ justifyContent="flex-end"+ >+ {DIMENSION_FORMATTER.format(values.inputImage.width)} ×{' '}+ {DIMENSION_FORMATTER.format(values.inputImage.height)}+ </DataList.ItemValue>+ </DataList.Item>+ <DataList.Item>+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs">+ {t('widgets.upscale.scale')}+ </DataList.ItemLabel>+ <DataList.ItemValue+ fontFamily="mono"+ fontSize="xs"+ fontVariantNumeric="tabular-nums"+ justifyContent="flex-end"+ >+ {values.scale}×+ </DataList.ItemValue>+ </DataList.Item>+ <DataList.Item>+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs">+ {t('widgets.upscale.outputSize')}+ </DataList.ItemLabel>+ <DataList.ItemValue+ fontFamily="mono"+ fontSize="xs"+ fontVariantNumeric="tabular-nums"+ fontWeight="semibold"+ justifyContent="flex-end"+ >+ {DIMENSION_FORMATTER.format(output.width)} × {DIMENSION_FORMATTER.format(output.height)}+ </DataList.ItemValue>+ </DataList.Item>+ <DataList.Item>+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs">+ {t('widgets.upscale.outputMegapixels')}+ </DataList.ItemLabel>+ <DataList.ItemValue+ fontFamily="mono"+ fontSize="xs"+ fontVariantNumeric="tabular-nums"+ fontWeight="semibold"+ gap="1.5"+ justifyContent="flex-end"+ >+ {MEGAPIXEL_FORMATTER.format(outputMegapixels)} MP+ {isLargeOutput ? (+ <Badge colorPalette="orange" fontFamily="body" size="xs" variant="surface">+ {t('widgets.upscale.largeOutput')}+ </Badge>+ ) : null}+ </DataList.ItemValue>+ </DataList.Item>+ </DataList.Root>+ {isLargeOutput ? (+ <Text+ borderTopWidth="1px"+ borderColor="border.subtle"+ color="fg.warning"+ fontSize="2xs"+ pt="2"+ textWrap="pretty"+ >+ {t('widgets.upscale.largeOutputDescription')}+ </Text>+ ) : null}+ </Stack>+ );+};++const UpscaleModelReconciler = ({+ projectId,+ rawValues,+ values,+}: {+ projectId: string;+ rawValues: Record<string, unknown>;+ values: UpscaleWidgetValues;+}) => {+ const dispatch = useWorkbenchDispatch();++ useMountEffect(() => {+ const normalized = normalizeUpscaleWidgetValues(rawValues);++ if (normalized && valuesAreEqual(normalized, values)) {+ return;+ }++ dispatch({ projectId, type: 'patchWidgetValues', values: { ...values }, widgetId: 'upscale' });+ });++ return null;+};++const UpscalePromptFields = ({+ onPatchPromptDraft,+ onPatchValues,+ promptDraft,+ projectId,+ showSyntaxHighlighting,+ values,+}: {+ onPatchPromptDraft: (patch: ProjectPromptDraftPatch) => void;+ onPatchValues: (patch: Partial<UpscaleWidgetValues>) => void;+ promptDraft: ProjectPromptDraft;+ projectId: string;+ showSyntaxHighlighting: boolean;+ values: UpscaleWidgetValues;+}) => {+ const { t } = useTranslation();+ const handleUsePrompt = useCallback(+ (prompt: PromptHistoryItem) =>+ onPatchPromptDraft({+ negativePrompt: prompt.negativePrompt ?? '',+ negativePromptEnabled: prompt.negativePrompt ? true : promptDraft.negativePromptEnabled,+ positivePrompt: prompt.positivePrompt,+ }),+ [onPatchPromptDraft, promptDraft.negativePromptEnabled]+ );++ return (+ <Stack gap="2" p="2">+ <Text color="fg.muted" fontSize="2xs" textWrap="pretty">+ {t('widgets.upscale.sharedPromptDescription')}+ </Text>+ <PositivePromptField+ heightPx={values.positivePromptHeightPx}+ loras={values.loras}+ projectId={projectId}+ selectedModel={values.model ?? undefined}+ showSyntaxHighlighting={showSyntaxHighlighting}+ value={promptDraft.positivePrompt}+ onChange={(positivePrompt) => onPatchPromptDraft({ positivePrompt })}+ onResizeEnd={(positivePromptHeightPx) => onPatchValues({ positivePromptHeightPx })}+ onUsePrompt={handleUsePrompt}+ />+ <NegativePromptField+ heightPx={values.negativePromptHeightPx}+ isEnabled={promptDraft.negativePromptEnabled}+ loras={values.loras}+ projectId={projectId}+ selectedModel={values.model ?? undefined}+ showSyntaxHighlighting={showSyntaxHighlighting}+ value={promptDraft.negativePrompt}+ onChange={(negativePrompt) => onPatchPromptDraft({ negativePrompt })}+ onEnabledChange={(negativePromptEnabled) => onPatchPromptDraft({ negativePromptEnabled })}+ onResizeEnd={(negativePromptHeightPx) => onPatchValues({ negativePromptHeightPx })}+ />+ </Stack>+ );+};++const NumericSliderField = ({+ error,+ formatValue,+ helpText,+ label,+ marks,+ numberMax,+ numberMin,+ onChange,+ sliderMax = numberMax,+ sliderMin = numberMin,+ step,+ value,+}: {+ error?: string;+ formatValue?: (value: number) => string;+ helpText?: string;+ label: string;+ marks?: number[];+ numberMax: number;+ numberMin: number;+ onChange: (value: number) => void;+ sliderMax?: number;+ sliderMin?: number;+ step: number;+ value: number;+}) => (+ <Field error={error} helpText={helpText} label={label}>+ <HStack align="center" gap="3">+ <Slider+ aria-label={[label]}+ flex="1"+ formatValue={(nextValue) => (formatValue ? formatValue(nextValue) : String(nextValue))}+ marks={marks}+ max={sliderMax}+ min={sliderMin}+ step={step}+ value={[Math.min(sliderMax, Math.max(sliderMin, value))]}+ onValueChange={(details) => {+ const nextValue = details.value[0];++ if (nextValue !== undefined) {+ onChange(nextValue);+ }+ }}+ />+ <NumberInput.Root+ max={numberMax}+ min={numberMin}+ size="xs"+ step={step}+ value={String(value)}+ w="20"+ onValueChange={({ valueAsNumber }) => {+ if (Number.isFinite(valueAsNumber)) {+ onChange(valueAsNumber);+ }+ }}+ >+ <NumberInput.Control />+ <NumberInput.Input aria-label={`${label} value`} fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ </HStack>+ </Field>+);++const UpscaleImageField = ({+ inputImage,+ onChange,+}: {+ inputImage: UpscaleWidgetValues['inputImage'];+ onChange: (image: UpscaleWidgetValues['inputImage']) => void;+}) => {+ const { t } = useTranslation();+ const dispatch = useWorkbenchDispatch();+ const fileInputRef = useRef<HTMLInputElement | null>(null);+ const { isOver, setNodeRef } = useDroppable({ data: { kind: DROP_ID }, id: DROP_ID });+ const [isLoading, setIsLoading] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);++ const setGalleryImage = useCallback(+ async (imageName: string) => {+ setErrorMessage(null);+ setIsLoading(true);++ try {+ const [image] = await getGalleryImagesByNames([imageName]);++ if (image) {+ onChange({ height: image.height, image_name: image.imageName, width: image.width });+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ setErrorMessage(message);+ dispatch({ area: 'upscale', message, namespace: 'generation', type: 'recordError' });+ } finally {+ setIsLoading(false);+ }+ },+ [dispatch, onChange]+ );++ useDndMonitor({+ onDragEnd: (event) => {+ const data = event.active.data.current;++ if (!isLoading && event.over?.id === DROP_ID && isGalleryImageDragData(data) && data.images.length === 1) {+ const imageName = data.images[0]?.imageName;++ if (imageName) {+ void setGalleryImage(imageName);+ }+ }+ },+ });++ const uploadFile = useCallback(+ async (file: File) => {+ setErrorMessage(null);++ if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type)) {+ setErrorMessage(t('widgets.upscale.unsupportedFile'));+ dispatch({+ area: 'upscale',+ message: t('widgets.upscale.unsupportedFile'),+ namespace: 'generation',+ type: 'recordError',+ });+ return;+ }++ setIsLoading(true);++ try {+ const image = await uploadGalleryImage(file, 'none');++ onChange({ height: image.height, image_name: image.imageName, width: image.width });+ dispatch({ type: 'touchGalleryImagesRefresh' });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ setErrorMessage(message);+ dispatch({+ area: 'upscale',+ message,+ namespace: 'generation',+ type: 'recordError',+ });+ } finally {+ setIsLoading(false);+ }+ },+ [dispatch, onChange, t]+ );++ const handleFileChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.currentTarget.files?.[0];++ if (file) {+ void uploadFile(file);+ }+ event.currentTarget.value = '';+ },+ [uploadFile]+ );++ return (+ <Stack gap="2">+ <chakra.button+ ref={setNodeRef}+ aria-busy={isLoading}+ aria-label={inputImage ? t('widgets.upscale.replaceImage') : t('widgets.upscale.uploadImage')}+ borderColor={isOver ? 'accent.solid' : 'border.emphasized'}+ borderStyle="dashed"+ borderWidth="1px"+ cursor="pointer"+ disabled={isLoading}+ minH="24"+ overflow="hidden"+ position="relative"+ rounded="md"+ _focusVisible={{+ outlineColor: 'accent.focusRing',+ outlineOffset: '2px',+ outlineStyle: 'solid',+ outlineWidth: '2px',+ }}+ _disabled={{ cursor: 'wait', opacity: 0.7 }}+ _hover={{ bg: isLoading ? undefined : 'bg.subtle' }}+ onClick={() => fileInputRef.current?.click()}+ >+ {inputImage ? (+ <HStack align="stretch" gap="3" h="24" p="2">+ <Box bg="blackAlpha.300" boxSize="20" flexShrink="0" overflow="hidden" rounded="sm">+ <Image+ alt={t('widgets.upscale.inputImageAlt')}+ boxSize="full"+ objectFit="contain"+ outline="1px solid rgba(0, 0, 0, 0.1)"+ outlineOffset="-1px"+ rounded="sm"+ src={getImageThumbnailUrl(inputImage.image_name)}+ _dark={{ outlineColor: 'rgba(255, 255, 255, 0.1)' }}+ />+ </Box>+ <Stack align="start" flex="1" gap="1" justify="center" minW="0">+ <Text fontSize="xs" fontWeight="semibold" truncate>+ {inputImage.image_name}+ </Text>+ <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums">+ {inputImage.width} × {inputImage.height}+ </Text>+ <HStack color="fg.muted" gap="1">+ {isLoading ? <Spinner size="xs" /> : <UploadIcon aria-hidden="true" size="12" />}+ <Text fontSize="2xs">+ {isLoading ? t('widgets.upscale.uploadingImage') : t('widgets.upscale.replaceOrDrop')}+ </Text>+ </HStack>+ </Stack>+ </HStack>+ ) : (+ <Stack align="center" color="fg.muted" gap="2" justify="center" minH="24" px="4">+ {isLoading ? <Spinner size="sm" /> : <ImagePlusIcon aria-hidden="true" size="20" />}+ <Text fontSize="xs" textAlign="center">+ {isLoading ? t('widgets.upscale.uploadingImage') : t('widgets.upscale.uploadOrDrop')}+ </Text>+ </Stack>+ )}+ </chakra.button>+ <HStack justify="end">+ {inputImage ? (+ <Button disabled={isLoading} size="xs" variant="ghost" onClick={() => onChange(null)}>+ <XIcon aria-hidden="true" size="12" />+ {t('widgets.upscale.removeImage')}+ </Button>+ ) : null}+ </HStack>+ {errorMessage ? (+ <Text aria-live="polite" color="fg.error" fontSize="2xs" role="alert" textWrap="pretty">+ {errorMessage}+ </Text>+ ) : null}+ <Input+ ref={fileInputRef}+ accept="image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp"+ aria-hidden="true"+ display="none"+ tabIndex={-1}+ type="file"+ onChange={handleFileChange}+ />+ </Stack>+ );+};++export const UpscaleWidgetView = () => {+ const { t } = useTranslation();+ const dispatch = useWorkbenchDispatch();+ const selection = useActiveProjectSelector(+ (project) => {+ const instance = Object.values(project.widgetInstances).find((candidate) => candidate.typeId === 'upscale');++ return {+ promptDraft: getProjectPromptDraft(project),+ projectId: project.id,+ rawValues: instance?.state.values ?? {},+ showPromptSyntaxHighlighting: project.settings.showPromptSyntaxHighlighting,+ };+ },+ (left, right) =>+ left.projectId === right.projectId &&+ areProjectPromptDraftsEqual(left.promptDraft, right.promptDraft) &&+ left.rawValues === right.rawValues &&+ left.showPromptSyntaxHighlighting === right.showPromptSyntaxHighlighting+ );+ const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsStatus = useModelsSelector((snapshot) => snapshot.status);+ const normalized = normalizeUpscaleWidgetValues(selection.rawValues) ?? createDefaultUpscaleWidgetValues();+ const values = modelsStatus === 'loaded' ? syncUpscaleWidgetValuesWithModels(normalized, models) : normalized;+ const modelsFingerprint = useMemo(+ () =>+ models+ .map(+ (model) =>+ `${model.key}:${model.hash}:${model.name}:${model.base}:${model.type}:${model.format}:${model.variant ?? ''}:${JSON.stringify(model.default_settings ?? null)}`+ )+ .join('|'),+ [models]+ );+ const errors = {+ cfgScale: getRangeError(t('widgets.upscale.cfgScale'), values.cfgScale, 0, 100),+ creativity: getRangeError(+ t('widgets.upscale.creativity'),+ values.creativity,+ UPSCALE_CREATIVITY_MIN,+ UPSCALE_CREATIVITY_MAX+ ),+ scale: getRangeError(t('widgets.upscale.scale'), values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX),+ seed: getRangeError(t('widgets.upscale.seed'), values.seed, 0, SEED_MAX),+ steps: getRangeError(t('widgets.upscale.steps'), values.steps, 1, 1000),+ structure: getRangeError(+ t('widgets.upscale.structure'),+ values.structure,+ UPSCALE_STRUCTURE_MIN,+ UPSCALE_STRUCTURE_MAX+ ),+ tileOverlap: getRangeError(+ t('widgets.upscale.tileOverlap'),+ values.tileOverlap,+ UPSCALE_TILE_OVERLAP_MIN,+ UPSCALE_TILE_OVERLAP_MAX+ ),+ tileSize: getRangeError(+ t('widgets.upscale.tileSize'),+ values.tileSize,+ UPSCALE_TILE_SIZE_MIN,+ UPSCALE_TILE_SIZE_MAX+ ),+ };+ const patch = useCallback(+ (next: Partial<UpscaleWidgetValues>) =>+ dispatch({ projectId: selection.projectId, type: 'patchWidgetValues', values: next, widgetId: 'upscale' }),+ [dispatch, selection.projectId]+ );+ const patchPromptDraft = useCallback(+ (next: ProjectPromptDraftPatch) =>+ dispatch({ projectId: selection.projectId, type: 'patchProjectPromptDraft', values: next }),+ [dispatch, selection.projectId]+ );+ const replace = useCallback(+ (next: UpscaleWidgetValues) =>+ dispatch({ projectId: selection.projectId, type: 'patchWidgetValues', values: { ...next }, widgetId: 'upscale' }),+ [dispatch, selection.projectId]+ );++ useMountEffect(() => {+ ensureModelsLoaded();+ });++ const selectMainModel = (model: ModelConfig | null) => {+ if (!isMainModelConfig(model) || !isSelectableMainModel(model)) {+ return;+ }++ const nextValues = syncUpscaleWidgetValuesWithModels({ ...values, model: model as MainModelConfig }, models);+ const notices: string[] = [];++ if (values.tileControlnetModel?.key !== nextValues.tileControlnetModel?.key) {+ notices.push(+ nextValues.tileControlnetModel+ ? t('widgets.upscale.controlNetChanged', { name: nextValues.tileControlnetModel.name })+ : t('widgets.upscale.controlNetCleared')+ );+ }+ if (values.vae && !nextValues.vae) {+ notices.push(t('widgets.upscale.vaeCleared'));+ }+ const removedLoraCount = values.loras.length - nextValues.loras.length;++ if (removedLoraCount > 0) {+ notices.push(t('widgets.upscale.lorasRemoved', { count: removedLoraCount }));+ }++ replace(nextValues);++ if (notices.length > 0) {+ toaster.create({+ description: notices.join(' '),+ title: t('widgets.upscale.settingsAdjusted'),+ type: 'info',+ });+ }+ };++ const addLora = (model: ModelConfig | null) => {+ if (!values.model || !isLoraModelConfig(model) || !isLoraCompatibleWithModel(model, values.model)) {+ return;+ }++ patch({ loras: [...values.loras, { isEnabled: true, model, weight: getDefaultLoraWeight(model) }] });+ };++ const updateLora = (key: string, update: Partial<GenerateLora>) =>+ patch({ loras: values.loras.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora)) });+ const selectedLoraKeys = new Set(values.loras.map((lora) => lora.model.key));++ return (+ <Stack gap="2" minW="0" p="2">+ <UpscaleModelReconciler+ key={`${selection.projectId}:${modelsStatus}:${modelsFingerprint}`}+ projectId={selection.projectId}+ rawValues={selection.rawValues}+ values={values}+ />++ <GenerateCollapsibleSection label={t('widgets.upscale.sourceAndTreatment')} defaultOpen>+ <Stack gap="3" p="2">+ <UpscaleImageField inputImage={values.inputImage} onChange={(inputImage) => patch({ inputImage })} />+ <UpscaleOutputPreflight values={values} />+ <Field+ error={values.upscaleModel ? undefined : t('widgets.upscale.spandrelModelRequired')}+ helpText={values.upscaleModel ? t('widgets.upscale.spandrelModelHelp') : undefined}+ label={t('widgets.upscale.spandrelModel')}+ >+ <ModelSelect+ invalid={!values.upscaleModel}+ modelTypes={['spandrel_image_to_image']}+ placeholder={t('widgets.upscale.selectSpandrelModel')}+ size="xs"+ value={values.upscaleModel?.key ?? null}+ onChange={(model) => patch({ upscaleModel: isSpandrelModelConfig(model) ? model : null })}+ />+ </Field>+ <NumericSliderField+ error={errors.scale}+ formatValue={(scale) => `${scale}×`}+ helpText={t('widgets.upscale.scaleHelp')}+ label={t('widgets.upscale.scale')}+ marks={[1, 2, 4, 8, 16]}+ numberMax={UPSCALE_SCALE_MAX}+ numberMin={UPSCALE_SCALE_MIN}+ step={0.5}+ value={values.scale}+ onChange={(scale) => patch({ scale })}+ />+ <ButtonGroup attached={false} size="xs" variant="outline">+ <SimpleGrid columns={{ base: 2, md: 4 }} gap="1" w="full">+ {Object.entries(UPSCALE_PRESETS).map(([id, preset]) => {+ const active = values.creativity === preset.creativity && values.structure === preset.structure;+ const tooltipContent = `${t(`widgets.upscale.presetDescriptions.${id}`)} ${t(+ 'widgets.upscale.presetValues',+ { creativity: preset.creativity, structure: preset.structure }+ )}`;++ return (+ <Tooltip key={id} content={tooltipContent}>+ <Button+ aria-pressed={active}+ colorPalette={active ? 'accent' : 'bg'}+ size="xs"+ variant={active ? 'solid' : 'outline'}+ onClick={() => patch(preset)}+ >+ {t(`widgets.upscale.presets.${id}`)}+ </Button>+ </Tooltip>+ );+ })}+ </SimpleGrid>+ </ButtonGroup>+ <NumericSliderField+ error={errors.creativity}+ helpText={t('widgets.upscale.creativityHelp')}+ label={t('widgets.upscale.creativity')}+ marks={[UPSCALE_CREATIVITY_MIN, 0, UPSCALE_CREATIVITY_MAX]}+ numberMax={UPSCALE_CREATIVITY_MAX}+ numberMin={UPSCALE_CREATIVITY_MIN}+ step={1}+ value={values.creativity}+ onChange={(creativity) => patch({ creativity })}+ />+ <NumericSliderField+ error={errors.structure}+ helpText={t('widgets.upscale.structureHelp')}+ label={t('widgets.upscale.structure')}+ marks={[UPSCALE_STRUCTURE_MIN, 0, UPSCALE_STRUCTURE_MAX]}+ numberMax={UPSCALE_STRUCTURE_MAX}+ numberMin={UPSCALE_STRUCTURE_MIN}+ step={1}+ value={values.structure}+ onChange={(structure) => patch({ structure })}+ />+ </Stack>+ </GenerateCollapsibleSection>++ <GenerateCollapsibleSection badges={t('widgets.upscale.shared')} label={t('widgets.upscale.detailGuidance')}>+ <UpscalePromptFields+ promptDraft={selection.promptDraft}+ projectId={selection.projectId}+ showSyntaxHighlighting={selection.showPromptSyntaxHighlighting}+ values={values}+ onPatchPromptDraft={patchPromptDraft}+ onPatchValues={patch}+ />+ </GenerateCollapsibleSection>++ <GenerateCollapsibleSection label={t('widgets.upscale.generation')}>+ <Stack gap="3" p="2">+ <Field+ error={values.model ? undefined : t('widgets.upscale.mainModelRequired')}+ label={t('widgets.upscale.mainModel')}+ >+ <ModelSelect+ filter={isSelectableMainModel}+ invalid={!values.model}+ modelTypes={['main']}+ placeholder={t('widgets.upscale.selectMainModel')}+ size="xs"+ value={values.model?.key ?? null}+ onChange={selectMainModel}+ />+ </Field>+ <SimpleGrid columns={{ base: 2, md: 3 }} gap="2">+ <Field error={errors.steps} label={t('widgets.upscale.steps')}>+ <NumberInput.Root+ max={1000}+ min={1}+ size="xs"+ value={String(values.steps)}+ onValueChange={({ valueAsNumber }) => Number.isFinite(valueAsNumber) && patch({ steps: valueAsNumber })}+ >+ <NumberInput.Control />+ <NumberInput.Input fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ </Field>+ <Field error={errors.cfgScale} label={t('widgets.upscale.cfgScale')}>+ <NumberInput.Root+ max={100}+ min={0}+ size="xs"+ step={0.5}+ value={String(values.cfgScale)}+ onValueChange={({ valueAsNumber }) =>+ Number.isFinite(valueAsNumber) && patch({ cfgScale: valueAsNumber })+ }+ >+ <NumberInput.Control />+ <NumberInput.Input fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ </Field>+ <Field label={t('widgets.upscale.batchCount')}>+ <NumberInput.Root+ min={1}+ size="xs"+ value={String(values.batchCount)}+ onValueChange={({ valueAsNumber }) =>+ Number.isFinite(valueAsNumber) && patch({ batchCount: valueAsNumber })+ }+ >+ <NumberInput.Control />+ <NumberInput.Input fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ </Field>+ </SimpleGrid>+ <Field label={t('widgets.upscale.scheduler')}>+ <Combobox+ aria-label={t('widgets.upscale.scheduler')}+ options={SCHEDULER_OPTIONS}+ size="xs"+ value={values.scheduler}+ onValueChange={(scheduler) => patch({ scheduler })}+ />+ </Field>+ <Field error={values.shouldRandomizeSeed ? undefined : errors.seed} label={t('widgets.upscale.seed')}>+ <HStack gap="2">+ <NumberInput.Root+ disabled={values.shouldRandomizeSeed}+ max={SEED_MAX}+ min={0}+ size="xs"+ value={String(values.seed)}+ w="full"+ onValueChange={({ valueAsNumber }) => Number.isFinite(valueAsNumber) && patch({ seed: valueAsNumber })}+ >+ <NumberInput.Input fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ <Tooltip content={t('widgets.upscale.shuffleSeed')}>+ <IconButton+ aria-label={t('widgets.upscale.shuffleSeed')}+ disabled={values.shouldRandomizeSeed}+ size="xs"+ variant="outline"+ onClick={() => patch({ seed: Math.floor(Math.random() * SEED_MAX) })}+ >+ <DicesIcon />+ </IconButton>+ </Tooltip>+ <Switch.Root+ checked={values.shouldRandomizeSeed}+ size="sm"+ onCheckedChange={(event) => patch({ shouldRandomizeSeed: event.checked })}+ >+ <Switch.HiddenInput />+ <Switch.Control _checked={{ bg: 'accent.solid' }}>+ <Switch.Thumb />+ </Switch.Control>+ <Switch.Label fontSize="xs">{t('widgets.upscale.random')}</Switch.Label>+ </Switch.Root>+ </HStack>+ </Field>+ <Field label={t('widgets.upscale.addLora')}>+ <ModelSelect+ excludeKeys={selectedLoraKeys}+ filter={(model) =>+ Boolean(values.model && isLoraModelConfig(model) && isLoraCompatibleWithModel(model, values.model))+ }+ modelTypes={['lora']}+ placeholder={t('widgets.upscale.selectLora')}+ size="xs"+ value={null}+ onChange={addLora}+ />+ </Field>+ {values.loras.map((lora) => (+ <HStack key={lora.model.key} bg="bg.subtle" gap="2" p="2" rounded="md">+ <Switch.Root+ aria-label={lora.model.name}+ checked={lora.isEnabled}+ size="sm"+ onCheckedChange={(event) => updateLora(lora.model.key, { isEnabled: event.checked })}+ >+ <Switch.HiddenInput />+ <Switch.Control _checked={{ bg: 'accent.solid' }}>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Root>+ <Text flex="1" fontSize="xs" minW="0" truncate>+ {lora.model.name}+ </Text>+ <NumberInput.Root+ max={10}+ min={-10}+ size="xs"+ step={0.05}+ value={String(lora.weight)}+ w="20"+ onValueChange={({ valueAsNumber }) =>+ Number.isFinite(valueAsNumber) && updateLora(lora.model.key, { weight: valueAsNumber })+ }+ >+ <NumberInput.Input aria-label={t('widgets.upscale.loraWeight', { name: lora.model.name })} />+ </NumberInput.Root>+ <IconButton+ aria-label={t('widgets.upscale.removeLora', { name: lora.model.name })}+ size="xs"+ variant="ghost"+ onClick={() =>+ patch({ loras: values.loras.filter((candidate) => candidate.model.key !== lora.model.key) })+ }+ >+ <Trash2Icon />+ </IconButton>+ </HStack>+ ))}+ </Stack>+ </GenerateCollapsibleSection>++ <GenerateCollapsibleSection label={t('widgets.upscale.advanced')}>+ <Stack gap="3" p="2">+ <Field+ error={values.tileControlnetModel ? undefined : t('widgets.upscale.tileControlNetRequired')}+ helpText={values.tileControlnetModel ? t('widgets.upscale.tileControlNetHelp') : undefined}+ label={t('widgets.upscale.tileControlNet')}+ >+ <ModelSelect+ filter={(model) => isTileControlNetCandidate(model, values.model)}+ invalid={!values.tileControlnetModel}+ modelTypes={['controlnet']}+ placeholder={t('widgets.upscale.selectTileControlNet')}+ size="xs"+ value={values.tileControlnetModel?.key ?? null}+ onChange={(model) =>+ patch({ tileControlnetModel: isTileControlNetCandidate(model, values.model) ? model : null })+ }+ />+ </Field>+ <NumericSliderField+ error={errors.tileSize}+ helpText={t('widgets.upscale.tileSizeHelp')}+ label={t('widgets.upscale.tileSize')}+ marks={[UPSCALE_TILE_SIZE_MIN, 1024, UPSCALE_TILE_SIZE_MAX]}+ numberMax={UPSCALE_TILE_SIZE_MAX}+ numberMin={UPSCALE_TILE_SIZE_MIN}+ step={64}+ value={values.tileSize}+ onChange={(tileSize) => patch({ tileSize })}+ />+ <NumericSliderField+ error={errors.tileOverlap}+ helpText={t('widgets.upscale.tileOverlapHelp')}+ label={t('widgets.upscale.tileOverlap')}+ marks={[UPSCALE_TILE_OVERLAP_MIN, 128, 256, UPSCALE_TILE_OVERLAP_MAX]}+ numberMax={UPSCALE_TILE_OVERLAP_MAX}+ numberMin={UPSCALE_TILE_OVERLAP_MIN}+ step={8}+ value={values.tileOverlap}+ onChange={(tileOverlap) => patch({ tileOverlap })}+ />+ <SimpleGrid columns={{ base: 1, md: 2 }} gap="2">+ <Field label={t('widgets.upscale.vae')} helpText={values.vae ? undefined : t('widgets.upscale.bundledVae')}>+ <ModelSelect+ filter={(model) => Boolean(values.model && model.base === values.model.base)}+ isClearable+ modelTypes={['vae']}+ placeholder={t('widgets.upscale.bundledVae')}+ size="xs"+ value={values.vae?.key ?? null}+ onChange={(model) => patch({ vae: isVaeModelConfig(model) ? model : null })}+ />+ </Field>+ <Field label={t('widgets.upscale.vaePrecision')}>+ <NativeSelect.Root size="xs">+ <NativeSelect.Field+ aria-label={t('widgets.upscale.vaePrecision')}+ value={values.vaePrecision}+ onChange={(event: ChangeEvent<HTMLSelectElement>) =>+ patch({ vaePrecision: event.currentTarget.value as VaePrecision })+ }+ >+ <option value="fp16">FP16</option>+ <option value="fp32">FP32</option>+ </NativeSelect.Field>+ <NativeSelect.Indicator />+ </NativeSelect.Root>+ </Field>+ </SimpleGrid>+ {values.model?.base === 'sd-1' ? (+ <Field label={t('widgets.upscale.clipSkip')}>+ <NumberInput.Root+ max={12}+ min={0}+ size="xs"+ value={String(values.clipSkip)}+ onValueChange={({ valueAsNumber }) =>+ Number.isFinite(valueAsNumber) && patch({ clipSkip: valueAsNumber })+ }+ >+ <NumberInput.Control />+ <NumberInput.Input fontVariantNumeric="tabular-nums" />+ </NumberInput.Root>+ </Field>+ ) : null}+ </Stack>+ </GenerateCollapsibleSection>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/upscale/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/upscale/index.tsnew file mode 100644index 0000000000..9fa9fd5e3a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/upscale/index.ts@@ -0,0 +1,17 @@+import type { WidgetManifest } from '@workbench/types';++import { ImageUpscaleIcon } from 'lucide-react';++import { UpscaleWidgetView } from './UpscaleWidgetView';++export const upscaleWidgetManifest: WidgetManifest = {+ allowMultiple: false,+ allowedRegions: ['left'],+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ graphBearing: { defaultGraphId: 'upscale-graph', sourceId: 'upscale', surfaces: ['left'] },+ icon: ImageUpscaleIcon,+ id: 'upscale',+ label: (t) => t('widgets.labels.upscale'),+ version: 1,+ view: UpscaleWidgetView,+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 410e708bc3..ce2f64891a 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -320,6 +320,85 @@ describe('workbench widget region defaults', () => {]);expect(getActiveProject(hydratedCustomized).widgetRegions.right.instanceIds).toEqual(['gallery', 'layers']);});++ it('adds Upscale to untouched legacy left rails while preserving customized rails', () => {+ const initial = createInitialWorkbenchState();+ const withoutUpscaleInstance = Object.fromEntries(+ Object.entries(getActiveProject(initial).widgetInstances).filter(([id]) => id !== 'upscale')+ ) as Project['widgetInstances'];+ const withLeftIds = (instanceIds: Project['widgetRegions']['left']['instanceIds']): WorkbenchState => ({+ ...initial,+ projects: initial.projects.map((project) => ({+ ...project,+ widgetInstances: withoutUpscaleInstance,+ widgetRegions: { ...project.widgetRegions, left: { ...project.widgetRegions.left, instanceIds } },+ })),+ });++ const migrated = workbenchReducer(initial, {+ state: withLeftIds(['generate', 'workflow']),+ type: 'hydrateWorkbench',+ });+ const customized = workbenchReducer(initial, {+ state: withLeftIds(['generate', 'gallery']),+ type: 'hydrateWorkbench',+ });++ expect(getActiveProject(migrated).widgetRegions.left.instanceIds).toEqual(['generate', 'workflow', 'upscale']);+ expect(getActiveProject(migrated).widgetInstances.upscale?.typeId).toBe('upscale');+ expect(getActiveProject(customized).widgetRegions.left.instanceIds).toEqual(['generate', 'gallery']);+ });++ it('migrates a legacy Upscale prompt only when Generate has no prompt content', () => {+ const initial = createInitialWorkbenchState();+ const withPrompts = (generatePrompt: string): WorkbenchState => ({+ ...initial,+ projects: initial.projects.map((project) => {+ const generate = project.widgetInstances.generate!;+ const upscale = project.widgetInstances.upscale!;++ return {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ generate: {+ ...generate,+ state: { ...generate.state, values: { ...generate.state.values, positivePrompt: generatePrompt } },+ },+ upscale: {+ ...upscale,+ state: {+ ...upscale.state,+ values: {+ ...upscale.state.values,+ negativePrompt: 'legacy negative',+ negativePromptEnabled: false,+ positivePrompt: 'legacy positive',+ },+ },+ },+ },+ };+ }),+ });++ const migrated = workbenchReducer(initial, { state: withPrompts(''), type: 'hydrateWorkbench' });+ const preserved = workbenchReducer(initial, { state: withPrompts('generate positive'), type: 'hydrateWorkbench' });++ expect(getProjectWidgetValues(getActiveProject(migrated), 'generate')).toMatchObject({+ negativePrompt: 'legacy negative',+ negativePromptEnabled: false,+ positivePrompt: 'legacy positive',+ });+ expect(getProjectWidgetValues(getActiveProject(migrated), 'upscale')).toMatchObject({+ negativePrompt: '',+ negativePromptEnabled: true,+ positivePrompt: '',+ });+ expect(getProjectWidgetValues(getActiveProject(preserved), 'generate')).toMatchObject({+ positivePrompt: 'generate positive',+ });+ });});describe('workbench widget region opening', () => {@@ -463,7 +542,7 @@ describe('workbench layout presets', () => {expect(project.layout.panels).toEqual({ isBottomOpen: false, isLeftOpen: true, isRightOpen: true });expect(project.widgetRegions.left).toMatchObject({activeInstanceId: 'generate',- instanceIds: ['generate', 'workflow'],+ instanceIds: ['generate', 'workflow', 'upscale'],isCollapsed: false,sizePx: 450,});@@ -1421,12 +1500,12 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);});- it('does not queue sources that are still unavailable', () => {+ it('does not queue Upscale while its required settings are incomplete', () => {let state = createInitialWorkbenchState();state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });- expect(getActiveProject(state).invocation.sourceId).toBe('generate');+ expect(getActiveProject(state).invocation.sourceId).toBe('upscale');state = workbenchReducer(state, {backendSupportsCancellation: true,@@ -1494,6 +1573,22 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(afterValues.loras).toBe(beforeValues.loras);});+ it('shares prompt content through Generate without changing Upscale-local textarea sizing', () => {+ const state = createInitialWorkbenchState();+ const beforeUpscale = getProjectWidgetValues(getActiveProject(state), 'upscale');+ const nextState = workbenchReducer(state, {+ type: 'patchProjectPromptDraft',+ values: { negativePrompt: 'blur', negativePromptEnabled: false, positivePrompt: 'fine detail' },+ });++ expect(getProjectWidgetValues(getActiveProject(nextState), 'generate')).toMatchObject({+ negativePrompt: 'blur',+ negativePromptEnabled: false,+ positivePrompt: 'fine detail',+ });+ expect(getProjectWidgetValues(getActiveProject(nextState), 'upscale')).toBe(beforeUpscale);+ });+it('deduplicates prompt history by prompt pair and moves the newest submission to the top', () => {let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });@@ -1823,6 +1918,14 @@ describe('workbench backend connection recovery', () => {values: { recentImages: [image], selectedImage: image, selectedImageName: image.imageName },widgetId: 'gallery',});+ for (const projectId of [firstProjectId, secondProjectId]) {+ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { inputImage: { height: image.height, image_name: image.imageName, width: image.width } },+ widgetId: 'upscale',+ });+ }state = workbenchReducer(state, {imageNames: [image.imageName],@@ -1832,6 +1935,10 @@ describe('workbench backend connection recovery', () => {expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery').recentImages).toEqual([]);expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery').recentImages).toEqual([image]);+ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'upscale').inputImage).toBeNull();+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).toMatchObject({+ image_name: image.imageName,+ });});it('does not hydrate stale persisted backend connection state', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 78f89ff788..9054ff4895 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -37,6 +37,7 @@ import type {WorkbenchNotificationKind,WorkbenchState,} from './types';+import type { UpscaleWidgetValues } from './upscale/types';import type { ProjectGraphState } from './workflows/types';import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';@@ -50,6 +51,12 @@ import {import { getGenerationModelAvailabilityReasons } from './generation/baseGenerationPolicies';import { sanitizeBatchCount } from './generation/batch';import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';+import {+ applyProjectPromptDraft,+ getProjectPromptDraft,+ migrateProjectPromptDraft,+ type ProjectPromptDraftPatch,+} from './generation/projectPromptDraft';import {addPromptHistoryItem,getPromptHistoryItemFromGenerateSettings,@@ -70,6 +77,15 @@ import {import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';import { cloneLayoutPresetWidgetRegions, createLayoutPresetSnapshot } from './layoutPresetSnapshots';import { normalizeProjectSettings } from './settings/store';+import { compileUpscaleGraph } from './upscale/graph';+import {+ clearDeletedUpscaleInput,+ cloneUpscaleWidgetValues,+ getUpscaleValidationReasons,+ normalizeUpscaleWidgetValues,+ resolveUpscaleSeed,+ syncUpscaleWidgetValuesWithModels,+} from './upscale/settings';import { compileProjectGraph } from './workflows/buildGraph';import {cloneProjectGraph,@@ -128,6 +144,7 @@ type WorkbenchReducerAction =| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }| { type: 'setGenerateSettings'; values: GenerateWidgetValues; projectId?: string }| { type: 'patchGenerateSettings'; values: Partial<GenerateWidgetValues>; projectId?: string }+ | { type: 'patchProjectPromptDraft'; values: ProjectPromptDraftPatch; projectId?: string }| { type: 'setGenerateBatchCount'; batchCount: number; projectId?: string }| { type: 'addPromptToHistory'; prompt: PromptHistoryItem; projectId?: string }| { type: 'removePromptFromHistory'; prompt: PromptHistoryItem; projectId?: string }@@ -845,6 +862,7 @@ const createWidgetStates = (): WidgetStateMap => ({users: { id: 'users', label: 'Users', values: {}, version: 1 },'version-status': { id: 'version-status', label: 'Version', values: {}, version: 1 },workflow: { graphId: 'workflow-graph', id: 'workflow', label: 'Workflow', values: {}, version: 1 },+ upscale: { graphId: 'upscale-graph', id: 'upscale', label: 'Upscale', values: {}, version: 1 },});const createWidgetState = (widgetId: WidgetTypeId): WidgetStateContract =>@@ -877,6 +895,7 @@ const defaultWidgetInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {'gallery:bottom': 'gallery','gallery:center': 'gallery',generate: 'generate',+ upscale: 'upscale',layers: 'layers',notifications: 'notifications',preview: 'preview',@@ -901,6 +920,39 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({...cloneLayoutPresetWidgetRegions(defaultLayoutPreset.snapshot.widgetRegions),});+const LEGACY_DEFAULT_LEFT_REGION_WIDGET_IDS: readonly WidgetInstanceId[][] = [+ ['generate', 'workflow'],+ ['workflow', 'generate'],+ ['generate', 'workflow', 'gallery'],+];++const ensureLeftRegion = (leftRegion: WidgetRegionState | undefined): WidgetRegionState => {+ const fallback = createWidgetRegions().left;++ if (!leftRegion) {+ return fallback;+ }+ if (leftRegion.instanceIds.includes('upscale')) {+ return leftRegion;+ }++ const legacyMatch = LEGACY_DEFAULT_LEFT_REGION_WIDGET_IDS.some(+ (ids) =>+ ids.length === leftRegion.instanceIds.length && ids.every((id, index) => leftRegion.instanceIds[index] === id)+ );++ if (!legacyMatch) {+ return leftRegion;+ }++ const galleryIndex = leftRegion.instanceIds.indexOf('gallery');+ const instanceIds = [...leftRegion.instanceIds];++ instanceIds.splice(galleryIndex === -1 ? instanceIds.length : galleryIndex, 0, 'upscale');++ return { ...leftRegion, instanceIds };+};+const LEGACY_RIGHT_REGION_WIDGET_IDS: WidgetId[] = ['queue', 'gallery', 'layers'];const isLegacyDefaultRightRegion = (region: WidgetRegionState): boolean =>@@ -979,7 +1031,38 @@ const ensureProjectWidgetContracts = (project: Project): Project => {const legacyWidgetRegions = project.widgetRegions as| Partial<Record<WidgetRegion | 'left-panel' | 'right-panel' | 'status-bar', WidgetRegionState>>| undefined;- const widgetInstances = project.widgetInstances ?? createWidgetInstances();+ const leftRegion = ensureLeftRegion(legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel']);+ const widgetInstances = cloneWidgetInstances(project.widgetInstances ?? createWidgetInstances());++ const generateInstance = widgetInstances.generate;+ const upscaleInstance = widgetInstances.upscale;++ if (generateInstance && upscaleInstance) {+ const migratedValues = migrateProjectPromptDraft(generateInstance.state.values, upscaleInstance.state.values);+ const clearedLegacyUpscaleValues = applyProjectPromptDraft(upscaleInstance.state.values, {+ negativePrompt: '',+ negativePromptEnabled: true,+ positivePrompt: '',+ });++ if (migratedValues !== generateInstance.state.values) {+ widgetInstances.generate = {+ ...generateInstance,+ state: { ...generateInstance.state, values: migratedValues },+ };+ }++ if (clearedLegacyUpscaleValues !== upscaleInstance.state.values) {+ widgetInstances.upscale = {+ ...upscaleInstance,+ state: { ...upscaleInstance.state, values: clearedLegacyUpscaleValues },+ };+ }+ }++ if (leftRegion.instanceIds.includes('upscale') && !widgetInstances.upscale) {+ widgetInstances.upscale = createWidgetInstance('upscale');+ }return {...project,@@ -990,12 +1073,12 @@ const ensureProjectWidgetContracts = (project: Project): Project => {promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),settings: normalizeProjectSettings(project.settings),widgetRegions: {- left: legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel'] ?? defaultWidgetRegions.left,+ left: leftRegion,right: ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']),bottom: legacyWidgetRegions?.bottom ?? legacyWidgetRegions?.['status-bar'] ?? defaultWidgetRegions.bottom,center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),},- widgetInstances: cloneWidgetInstances(widgetInstances),+ widgetInstances,};};@@ -1316,6 +1399,32 @@ const compileInvocationSnapshot = (return { graph: compileProjectGraph(project.projectGraph, templatesSnapshot.templates), widgetStates };}+ if (route.sourceId === 'upscale') {+ const values = normalizeUpscaleWidgetValues(getWidgetValues(project, 'upscale'));++ if (!values) {+ return null;+ }++ const syncedValues = models ? syncUpscaleWidgetValuesWithModels(values, models) : values;+ const currentValues: UpscaleWidgetValues = { ...syncedValues, ...getProjectPromptDraft(project) };++ if (getUpscaleValidationReasons(currentValues, models).length > 0) {+ return null;+ }++ const resolvedValues: UpscaleWidgetValues = { ...currentValues, seed: resolveUpscaleSeed(currentValues) };+ const compiledGraph = compileUpscaleGraph(resolvedValues, route.destination, project.settings).graph;++ widgetStates.upscale = {+ ...widgetStates.upscale,+ graphId: compiledGraph.id,+ values: { ...cloneUpscaleWidgetValues(resolvedValues) },+ };++ return { graph: compiledGraph, widgetStates };+ }+if (route.sourceId !== 'generate') {const widgetGraph = project.widgetGraphs[route.sourceId as WidgetTypeId];@@ -1574,6 +1683,8 @@ const enqueueCompiledSnapshot = (const graphHistorySnapshot = createGraphHistorySnapshot(`Queue snapshot ${queueItemId}`, graph);const generateSettings =route.sourceId === 'generate' ? normalizeGenerateSettings(widgetStates.generate.values) : null;+ const upscaleSettings =+ route.sourceId === 'upscale' ? normalizeUpscaleWidgetValues(widgetStates.upscale.values) : null;const queueItem: QueueItem = {cancellable: backendSupportsCancellation,id: queueItemId,@@ -1605,7 +1716,12 @@ const enqueueCompiledSnapshot = (graphHistory: [graphHistorySnapshot, ...project.graphHistory].slice(0, HISTORY_LIMIT),promptHistory: generateSettings? addPromptHistoryItem(project.promptHistory, getPromptHistoryItemFromGenerateSettings(generateSettings))- : project.promptHistory,+ : upscaleSettings+ ? addPromptHistoryItem(project.promptHistory, {+ negativePrompt: upscaleSettings.negativePromptEnabled ? upscaleSettings.negativePrompt : null,+ positivePrompt: upscaleSettings.positivePrompt,+ })+ : project.promptHistory,invocation: {...project.invocation,destination: route.destination,@@ -1614,7 +1730,9 @@ const enqueueCompiledSnapshot = (},queue: { items: [queueItem, ...project.queue.items] },widgetGraphs:- route.sourceId === 'generate' ? { ...project.widgetGraphs, generate: cloneGraph(graph) } : project.widgetGraphs,+ route.sourceId === 'generate' || route.sourceId === 'upscale'+ ? { ...project.widgetGraphs, [route.sourceId]: cloneGraph(graph) }+ : project.widgetGraphs,};};@@ -1961,6 +2079,11 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchReducerupdateProjectWidgetValues(project, 'generate', (values) => patchRecord(values, action.values)));}+ case 'patchProjectPromptDraft': {+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetValues(project, 'generate', (values) => applyProjectPromptDraft(values, action.values))+ );+ }case 'setGenerateBatchCount': {const batchCount = sanitizeBatchCount(action.batchCount);@@ -2422,8 +2545,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchReducer}case 'removeGalleryImages': {const removedImageNames = new Set(action.imageNames);-- return updateGalleryValues(+ const nextState = updateGalleryValues(state,(values) => {const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;@@ -2441,6 +2563,18 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchReducer},action.projectId);++ return updateProjectById(nextState, action.projectId ?? state.activeProjectId, (project) =>+ updateProjectWidgetValues(project, 'upscale', (rawValues) => {+ const values = normalizeUpscaleWidgetValues(rawValues);++ if (!values?.inputImage || !removedImageNames.has(values.inputImage.image_name)) {+ return rawValues;+ }++ return { ...clearDeletedUpscaleInput(values, removedImageNames) };+ })+ );}case 'setGalleryProjectBoardId': {return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);