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(models): v7 alpha generation and model feedback — native upscale scale, scheduler defaults, Add Models memory (#9962)
Josh Corbett3bb0529a414a
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdxindex 96ce06cdd6..dee187c3de 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx@@ -126,15 +126,20 @@ transformer on an image. Each adapter model may be used only once per generationControlNet-LLLite**, its pixels are the control image, and several control layers combine as long aseach uses a different model. The **Model** list holds the control adapters (Sketch, Depth, Scribble,Lineart, Pose); the Inpainting adapter needs an inpaint mask rather than a control image, so it is not- offered there. An adapter installed before Invoke recorded which kind it is is not listed either:- re-identify it in the Model Manager.+ offered there. An adapter installed before Invoke recorded which kind it is appears as a disabled entry+ marked **Needs re-identify**. Its page in the Model Manager explains this and offers **Re-identify model**;+ after you confirm, Invoke re-probes the file and the adapter becomes usable (or is hidden, if it is the+ Inpainting adapter). Re-identifying resets the model's custom variant and default settings. Users who+ cannot manage models see the explanation and are asked to contact an administrator.A control layer from an older project may still be set to **ControlNet**, which Anima cannot run; itssettings say so and offer **Switch to Anima ControlNet-LLLite**, which keeps the selected adapter.- **When inpainting or outpainting on the canvas**, pick the Inpainting adapter as the optional **InpaintAdapter** in the Generate panel's **Components** section, and set its **Inpaint adapter weight** (1 bydefault). Invoke then conditions the adapter on the raster image and the region being generated; the- setting is ignored for text-to-image and image-to-image. The adapter and its weight are recorded in the- image's metadata and restored by **Recall All** and **Remix Image**.+ setting is ignored for text-to-image and image-to-image. Turn off **Use inpaint adapter** to inpaint+ without it; the selected adapter and its weight are kept for when you turn it back on. The adapter and its+ weight are recorded in the image's metadata and restored by **Recall All** and **Remix Image**; recalling an+ inpaint or outpaint image made without the adapter turns **Use inpaint adapter** off.- **In the workflow editor**, add an **Anima ControlNet-LLLite** node, give it the conditioning image anda control model, and connect it to the **Control LLLite** input of **Denoise - Anima**, collectingseveral nodes to combine them.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdxindex cf21a90f32..f8f127c4c7 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx@@ -1,13 +1,37 @@---title: Upscaling-lastUpdated: 2026-10-19+lastUpdated: 2026-10-20sidebar:order: 8----The **Upscale** panel enlarges an image and adds detail in two passes. First a Spandrel upscaling model (such as a Real-ESRGAN variant) enlarges the image. Then a main model runs a short image-to-image pass over the result to invent detail that fits your prompt.+The **Upscale** panel enlarges an image. A Spandrel upscaling model (such as a Real-ESRGAN variant) enlarges it first. In **Refine** mode a main model then runs a short image-to-image pass over the result to invent detail that fits your prompt; in **Model only** mode the upscaler's result is the output.-Open it from the left rail. It is available in the Compose, Edit and Video layouts.+Open it from the left rail. It is available in the Compose, Edit and Video layouts. To upscale a gallery image without opening the panel, use its context menu (see [Upscaling from the image menu](#upscaling-from-the-image-menu)).++## Refine or Model only++The **Mode** switch at the top of the panel picks how the image is upscaled. Projects open in **Refine**, including projects saved before the switch existed.++- **Refine** runs both passes: the upscaler, then the main model's detail pass. Everything below this section applies to it.+- **Model only** runs the upscaler alone, with no main model, prompt or detail pass. The panel keeps only the source image, the Spandrel model and **Scale**; the prompt, Generation and Advanced sections are hidden. Model only does not need the model capability list Refine loads, so it works while that list is loading or could not be loaded.++Switching modes keeps your Refine settings, so switching back restores them. A Model only run always queues once whatever the **Iterations** setting, because the upscaler gives the same image every time.++### Native scale++Each upscaler has a native scale, such as 4× for 4x-UltraSharp. In Model only mode the panel shows a **Native scale** row when the upscaler's native scale is known, and explains how it reaches your **Scale**:++- the upscaler runs until the image is at least the Scale you asked for, then resizes it down to that size, for example "Runs 4× once, then resizes to 2×" or "Runs 2× 2 times";+- a 1× model (a restoration model) keeps the input size, so Scale has no effect.++The output size is rounded down to a multiple of 8.++Upscalers record their native scale when they are installed. Upscalers installed with an earlier version have no recorded scale until you re-identify them in the Model Manager; until then Model only shows no Native scale row, and a note under the Spandrel model says the native scale is unknown. Users who manage models can open the upscaler in the Model Manager from that note.++To record it, open the upscaler's page in the Model Manager. A notice there says its native scale is unknown, and users who manage models can press **Re-identify model** and confirm; Invoke re-probes the file and the page then shows its native scale. Re-identifying also resets the model's custom variant and default settings. Other users are asked to contact an administrator.++The result's metadata is the source image's metadata plus the upscaler and the Scale, so **Recall** on the result restores how the source was made.## Setting up an upscale@@ -55,3 +79,14 @@ For SD1.5 and SDXL the detail pass works in tiles, so the output can be much larFor FLUX.1, FLUX.2, Z-Image, Anima, Krea-2 and Qwen Image the detail pass runs over the whole image at once, so its memory use grows with the output size. There, **Tile size** only sets the tiles for the VAE encode and decode, and **Tile overlap** has no effect. Anima's decode picks its own tiles.For all model families, encoding and decoding the enlarged image with the VAE runs in tiles. See [Low-VRAM mode](/configuration/optimization/low-vram-mode/) if you still run out of memory.++## Upscaling from the image menu++Right-click an image in the gallery and open **Upscale**:++- **Send to Upscale** opens the Upscale panel with the image as its source.+- Under **Upscale now, model only**, each installed upscaler is listed by name with its native scale when it is known. Each one opens a list of factors: 1.5×, 2× and its native scale, marked "(native)". A factor offered twice is listed once, so a 2× upscaler offers 1.5× and 2×, and a 4× upscaler offers 1.5×, 2× and 4×. A 1× (restoration) model offers only 1×. Picking a factor queues a Model only upscale of the image straight away, without changing the Upscale panel or the current Invoke settings. Every factor runs as Model only mode runs it at that Scale, so the result has the same size as one from the Upscale panel (see [Native scale](#native-scale)): the native scale runs the upscaler once, and other factors resize the result to the factor.++When no upscaler is installed, the model-only entry is disabled. An upscaler whose native scale is unknown offers **Native scale**, which runs it once at whatever size it produces, and a disabled **Other factors** entry with a note to re-identify it in the Model Manager. For other factors, or a fractional Scale such as 2.5×, use **Send to Upscale**.++Results go to the gallery's auto-add board, wherever Invoke is currently set to send results. Their metadata is the source image's metadata plus the upscaler and its scale. If the source image's metadata cannot be read, nothing is queued and a notification says so.diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/minimax-h3.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/minimax-h3.mdxindex 55520a2922..c630d9e15f 100644--- a/docs/src/content/docs/Users Guide/05.Video Generation/minimax-h3.mdx+++ b/docs/src/content/docs/Users Guide/05.Video Generation/minimax-h3.mdx@@ -19,7 +19,7 @@ media's video, audio, or both video and audio.MiniMax H3 ships as two task transformers that share every other component. **FL2VA** — *first/last-frame to video with audio* — covers text-to-video, first frame, last frame, both, and extend. **Ref2VA** — *reference to video with audio* — conditions a new clip on **reference media**: up to 3 videos and 9 images, in an order you choose (order changes the result). Every generation from either includes a **jointly generated stereo soundtrack**, muxed into the MP4 as AAC.-The panel switches task by transformer: select the Ref2VA single-file transformer as the **Model** and the conditioning sections become the ordered **References** list; select the FL2VA transformer to get the five frame/extend modes back. A video reference can contribute its image track, its soundtrack, or both; soundtrack-only references can be used on their own. Image references default to a high-detail 2048 px encoding ("Max"); the "Match generation size" option is several times faster at some fidelity cost.+The panel switches task by transformer: select the Ref2VA single-file transformer as the **Model** and the conditioning sections become the ordered **References** list; select the FL2VA transformer to get the five frame/extend modes back. A video reference can contribute its image track, its soundtrack, or both; soundtrack-only references can be used on their own. New image references use "Match generation size", which is several times faster than the high-detail 2048 px encoding ("Max detail") at some fidelity cost; switch a reference to "Max detail" when its fine detail matters.What makes it different from Wan in practice:@@ -94,7 +94,7 @@ The **MiniMax H3** starter bundle (~85 GB) installs the working set:* **MiniMax H3 Components** (~11 GB) — the Diffusers-format install of the tokenizer, processor, and video + audio VAEs, which goes in the panel's **Model components** slot — plus **MiniMax H3 Text Encoder (int8)** (~27 GB), the single-file build for its **Text encoder** slot (the Components install carries no text-encoder weights). The bundled templates wire them the same way.* **MiniMax H3 Turbo LoRA**, **MiniMax H3 LightX2V Turbo LoRA**, and **MiniMax H3 LightX2V Ref2V Turbo LoRA** — independent step-distillation LoRAs; the Turbo toggle picks the one matching the selected task (the Ref2V build is trained against the Ref2VA transformer only). The earlier 4-step *MiniMax H3 Ref2V Turbo LoRA* (v0.1) is no longer a starter: it pans the camera rightward whenever a video reference is used. If you still have it installed, the toggle prefers the LightX2V release once that is installed too.-Reference conditioning adds rows to every denoising step roughly linearly: a few references typically cost ~1–2 GiB of extra activation memory, but a full-detail 2048×2048 image reference alone adds ~4096 rows (about 1 GiB), and three full-length video references can triple the packed sequence. Prefer "Match generation size" for image references and trimmed clips for video references on smaller cards.+Reference conditioning adds rows to every denoising step roughly linearly: a few references typically cost ~1–2 GiB of extra activation memory, but a full-detail 2048×2048 image reference alone adds ~4096 rows (about 1 GiB), and three full-length video references can triple the packed sequence. On smaller cards, keep image references at "Match generation size" and trim video references.H3 is the heaviest local video option — With 16 GB VRAM, `enable_partial_loading` enabled and 32 GB of system RAM it can create a full 345 frame video (about 14s) at 768x768 resolution, but for larger or longer videos a high-VRAM GPU (24 GB+) is strongly recommended.diff --git a/invokeai/backend/model_manager/configs/spandrel.py b/invokeai/backend/model_manager/configs/spandrel.pyindex 8ca8ad5f60..7bd1d2380b 100644--- a/invokeai/backend/model_manager/configs/spandrel.py+++ b/invokeai/backend/model_manager/configs/spandrel.py@@ -27,6 +27,11 @@ class Spandrel_Checkpoint_Config(Config_Base):base: Literal[BaseModelType.Any] = Field(default=BaseModelType.Any)type: Literal[ModelType.SpandrelImageToImage] = Field(default=ModelType.SpandrelImageToImage)format: Literal[ModelFormat.Checkpoint] = Field(default=ModelFormat.Checkpoint)+ scale: int | None = Field(+ default=None,+ description="Native upscale factor of the model (1 = output is the input size). None for models installed "+ "before this field was recorded.",+ )@classmethoddef from_model_on_disk(cls, mod: ModelOnDisk, override_fields: dict[str, Any]) -> Self:@@ -34,12 +39,15 @@ class Spandrel_Checkpoint_Config(Config_Base):raise_for_override_fields(cls, override_fields)- cls._validate_spandrel_loads_model(mod)+ model = cls._load_spandrel_model(mod)- return cls(**override_fields)+ args = dict(override_fields)+ if "scale" not in args:+ args["scale"] = model.scale+ return cls(**args)@classmethod- def _validate_spandrel_loads_model(cls, mod: ModelOnDisk) -> None:+ def _load_spandrel_model(cls, mod: ModelOnDisk) -> SpandrelImageToImageModel:try:# It would be nice to avoid having to load the Spandrel model from disk here. A couple of options were# explored to avoid this:@@ -49,6 +57,6 @@ class Spandrel_Checkpoint_Config(Config_Base):# 2. Spandrel has internal logic to determine a model's type from its state_dict before loading the model.# This logic is not exposed in spandrel's public API. We could copy the logic here, but then we have to# maintain it, and the risk of false positive detections is higher.- SpandrelImageToImageModel.load_from_file(mod.path)+ return SpandrelImageToImageModel.load_from_file(mod.path)except Exception as e:raise NotAMatchError("model does not match SpandrelImageToImage heuristics") from ediff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex d18a018f29..8c219acf01 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -104455,6 +104455,18 @@"const": "checkpoint","title": "Format","default": "checkpoint"+ },+ "scale": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Scale",+ "description": "Native upscale factor of the model (1 = output is the input size). None for models installed before this field was recorded."}},"type": "object",@@ -104472,7 +104484,8 @@"cover_image","base","type",- "format"+ "format",+ "scale"],"title": "Spandrel_Checkpoint_Config","description": "Model config for Spandrel Image to Image models."diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex ffcda85d1e..e4d311e8d4 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -45771,6 +45771,11 @@ export type components = {* @constant*/format: "checkpoint";+ /**+ * Scale+ * @description Native upscale factor of the model (1 = output is the input size). None for models installed before this field was recorded.+ */+ scale: number | null;};/** StarredImagesResult */StarredImagesResult: {diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.mdindex 8c7d4cf8f3..c657e3473b 100644--- a/invokeai/frontend/webv2/AGENTS.md+++ b/invokeai/frontend/webv2/AGENTS.md@@ -32,6 +32,7 @@ Shared generated API contracts and their CI gates: [../api/AGENTS.md](../api/AGENo Python backend: `pnpm dev:mock` serves the app against the in-repo mock backend, which picks its own free port. Arguments go to `vite dev`. Default Vite port 5174 taken: pick a spare, `pnpm dev:mock --port 5273 --strictPort`. `pnpm dev` alone proxies to a real backend at `http://127.0.0.1:9090`.- `INVOKEAI_MOCK_BACKEND_PROFILE`: `representative` (default) or `empty`. `POST /__reset` on the mock origin printed at startup restores fixtures; `?profile=` switches them. Unimplemented endpoints return 404.+- `POST /__models` with `{"set": "anima-lllite"}` or `{"set": "spandrel"}` adds opt-in model seeds (adapters and upscalers installed before their channels or scale were recorded); re-identify fills those fields. `/__reset` drops them.- Stop servers by PID (`ss -ltnp`), not `pkill -f`: its pattern can match the invoking shell. Restart after merges that add mock endpoints.- Provider/context error from a `?t=` module after source edits: full reload before calling it a product bug. HMR can split context modules.diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex d72f3f3a71..f09172736e 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -37,6 +37,7 @@ Ownership follows invariants, not the first caller:- Authentication: `app/main.tsx` hands it to Platform transport before React mounts. Identity owns the credential and every policy about it. Platform captures it once per request and reports that request's outcome.- Platform socket publishes raw events and connection transitions. Queue and other domains interpret them.- Lifecycle-specific production composition stays explicit at its natural root: authenticated socket in `app/router.tsx`, editor runtimes in `app/WorkbenchApp.tsx`, feature UI providers in `app/workbenchPorts.tsx`, lazy editor bridges beside their lazy entry modules. App builds the production Queue runtime from Queue, Workbench, Gallery, Workflow adapters.+ - The authenticated layout in `app/router.tsx` supplies the account's Models UI port (capabilities, preferences, Generation's scheduler rules), which the Launchpad Model Manager reads and the editor's adapter narrows with its active project. It lives there because a new module would join the Launchpad's startup graph; the scheduler rules load on demand from a lazy module.- Platform State owns reusable projections of broad external stores into referentially stable read-only stores. App may build them for a feature port. Listener, caching, equality mechanics stay domain-neutral Platform code.`pnpm architecture:check` is the executable source of truth for dependency direction. It parses TypeScript and classifies static imports, type imports, dynamic imports, re-exports, inline imported types, after resolving aliases and relative paths. Temporary violations go in `src/architecture/migrationExceptions.ts` with owner and removal ticket. Architecture is complete only when that registry is empty.diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 71f8467abc..4f023a0f6b 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -30,11 +30,11 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 29,"scriptRawBytes": 1868300,"scriptRequestCount": 25,- "totalRawBytes": 2114972+ "totalRawBytes": 2120308},"routeReadyMedianMs": 215.30000019073486,"scriptSourceOwnerSet": "launchpad-static",@@ -68,11 +68,11 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 29,"scriptRawBytes": 1868300,"scriptRequestCount": 25,- "totalRawBytes": 2114972+ "totalRawBytes": 2120308},"routeReadyMedianMs": 225.39999961853027,"scriptSourceOwnerSet": "launchpad-static",@@ -106,11 +106,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 87,"scriptRawBytes": 4199867,"scriptRequestCount": 82,- "totalRawBytes": 4490937+ "totalRawBytes": 4496273},"routeReadyMedianMs": 360.90000009536743,"scriptSourceOwnerSet": "editor-minimal-static",@@ -144,11 +144,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 87,"scriptRawBytes": 4199867,"scriptRequestCount": 82,- "totalRawBytes": 4490937+ "totalRawBytes": 4496273},"routeReadyMedianMs": 367.80000019073486,"scriptSourceOwnerSet": "editor-minimal-static",@@ -182,11 +182,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 96,"scriptRawBytes": 4718489,"scriptRequestCount": 91,- "totalRawBytes": 5009559+ "totalRawBytes": 5014895},"routeReadyMedianMs": 1095.3000001907349,"scriptSourceOwnerSet": "editor-canvas-static",@@ -220,11 +220,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 96,"scriptRawBytes": 4718489,"scriptRequestCount": 91,- "totalRawBytes": 5009559+ "totalRawBytes": 5014895},"routeReadyMedianMs": 1042.5,"scriptSourceOwnerSet": "editor-canvas-static",@@ -258,11 +258,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 94,"scriptRawBytes": 4644510,"scriptRequestCount": 88,- "totalRawBytes": 4950993+ "totalRawBytes": 4956329},"routeReadyMedianMs": 1093.0999999046326,"scriptSourceOwnerSet": "editor-workflow-static",@@ -296,11 +296,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 94,"scriptRawBytes": 4644510,"scriptRequestCount": 88,- "totalRawBytes": 4950993+ "totalRawBytes": 4956329},"routeReadyMedianMs": 1105.0999999046326,"scriptSourceOwnerSet": "editor-workflow-static",@@ -334,11 +334,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 87,"scriptRawBytes": 4199867,"scriptRequestCount": 82,- "totalRawBytes": 4490937+ "totalRawBytes": 4496273},"routeReadyMedianMs": 1324.5,"scriptSourceOwnerSet": "editor-minimal-static",@@ -372,11 +372,11 @@"fontRawBytes": 23664,"imageRawBytes": 44398,"largestAssetRawBytes": 752413,- "otherRawBytes": 220849,+ "otherRawBytes": 226185,"requestCount": 87,"scriptRawBytes": 4199867,"scriptRequestCount": 82,- "totalRawBytes": 4490937+ "totalRawBytes": 4496273},"routeReadyMedianMs": 1301.5,"scriptSourceOwnerSet": "editor-minimal-static",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 7b54e34e52..6b04ac9322 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -374,6 +374,7 @@"unableToQueue": "Unable to queue"},"iterations": {+ "fixedModelOnly": "Model only runs once: the upscaler gives the same image every time.","label": "Iterations","tooltip_one": "{{count}} iteration per invoke","tooltip_other": "{{count}} iterations per invoke"@@ -1228,6 +1229,7 @@"accessTokenPlaceholder": "Only needed for protected sources","accessTokenRequiredMessage": "This source needs an access token. Add one to continue.","actions": "Model actions",+ "adapterTypeUnknown": "Adapter type unknown: this adapter was installed before Invoke recorded its type, so control layers can't use it yet.","addModels": "Add Models","addModelsResults": "Add models results","addToken": "Add token",@@ -1299,7 +1301,7 @@"guidance": "Uses the generator default","height": "App default: 1024","preprocessor": "Chosen automatically per image",- "scheduler": "App default: euler_a",+ "scheduler": "Uses the generator default for its base","steps": "App default: 30","vae": "Uses the compatible default VAE","vaePrecision": "App default: fp16",@@ -1449,6 +1451,9 @@"modelManager": "Model manager","modelNoLongerInLibrary": "This model is no longer in the library.","modelReidentified": "Model re-identified",+ "nativeScale": "Native scale",+ "nativeScaleUnknown": "Native scale unknown: this upscaler was installed before Invoke recorded how much it enlarges, so Upscale can't show how it will run it.",+ "nativeScaleValue": "{{scale}}×","modelType": "Model Type","modelUpdated": "Model updated","moreQueueActions": "More queue actions",@@ -1524,6 +1529,9 @@"reidentifiedDescription_one": "{{count}} model re-probed and updated.","reidentifiedDescription_other": "{{count}} models re-probed and updated.","reidentify": "Re-identify model",+ "reidentifyAskAdmin": "Ask an administrator to re-identify it.",+ "reidentifyConfirmBody": "Re-probe this model to re-detect its base, type, and format? Its custom variant and default settings are reset.",+ "reidentifyConfirmTitle": "Re-identify model","reidentifyFailed": "Re-identify failed","reidentifySelected": "Re-identify","removeFromList": "Remove from list",@@ -1549,6 +1557,9 @@"runVaeOnCpuHelp": "Run this VAE on CPU only to reduce VRAM usage. This may be slower.","saveDefaults": "Save Defaults","scan": "Scan",+ "schedulerListLoading": "Loading the schedulers for this model…",+ "schedulerListRetrying": "Retrying…",+ "schedulerListUnavailable": "Scheduler list unavailable.","scanFailed": "Scan failed","scanFailedDescription": "{{reason}} Check that the folder exists and that the server can read it.","statusQueued": "Queued",@@ -1589,6 +1600,7 @@"someCouldNotBeReidentified": "Some models could not be re-identified","sort": {"base": "Base",+ "catalog": "Catalog order","default": "Default","format": "Format","name": "Name",@@ -2892,7 +2904,9 @@"refinerStart": "Refiner start","refinerPositiveAestheticScore": "Positive aesthetic score","refinerNegativeAestheticScore": "Negative aesthetic score",- "animaInpaintAdapterWeight": "Inpaint adapter weight"+ "animaInpaintAdapterWeight": "Inpaint adapter weight",+ "animaInpaintAdapterEnabled": "Use inpaint adapter",+ "animaInpaintAdapterOffHelp": "Off: inpainting runs without the adapter. Your selection is kept."},"upscale": {"concepts": "Concepts",@@ -2942,6 +2956,20 @@"readyDescription": "The upscale graph is ready to queue.","scale": "Scale","scaleHelp": "Output dimensions are the source dimensions multiplied by this value.",+ "mode": "Mode",+ "modeRefine": "Refine",+ "modeModelOnly": "Model only",+ "inputChanged": "The input image changed while the upscale was being prepared, so nothing was queued. Invoke again.",+ "modeHelp": "Model only runs the upscaler alone: no main model, prompt or detail pass.",+ "nativeScale": "Native scale",+ "nativeScaleValue": "{{scale}}×",+ "nativeScalePasses_one": "Runs {{native}}× once",+ "nativeScalePasses_other": "Runs {{native}}× {{count}} times",+ "nativeScalePassesResize_one": "Runs {{native}}× once, then resizes to {{target}}×",+ "nativeScalePassesResize_other": "Runs {{native}}× {{count}} times, then resizes to {{target}}×",+ "nativeScaleNoEnlarge": "This model keeps the input size, so Scale has no effect.",+ "nativeScaleUnknown": "Native scale unknown – re-identify the model in the Model Manager.",+ "openInModelManager": "Open in Model Manager","scheduler": "Scheduler","seed": "Seed","searchCompatibleConcepts": "Search compatible concepts…",@@ -3935,7 +3963,7 @@"spandrel_filter": "Spandrel"},"hiddenModels": {- "lllite_channels_unknown": "ControlNet-LLLite models whose adapter type is unknown are hidden. Re-identify them in the Model Manager.",+ "lllite_channels_unknown": "ControlNet-LLLite models marked \"Needs re-identify\" can't be used yet. Re-identify them from their page in the Model Manager.","lllite_inpaint_adapter": "Inpainting ControlNet-LLLite adapters are hidden: they need an inpaint mask, not a control image."},"invalidLayer": "Control layer \"{{name}}\": {{reason}}",@@ -3958,6 +3986,7 @@"unbalanced": "Unbalanced"},"needsAttention": "Control layer needs attention",+ "needsReidentify": "Needs re-identify","preview": "Preview filter","selectModel": "Select a model","stepRange": "Step range",@@ -4575,6 +4604,18 @@"partial": "{{succeeded}} of {{count}} items unstarred; {{failed}} failed.","success_one": "Unstarred {{count}} item.","success_other": "Unstarred {{count}} items."+ },+ "upscale": {+ "label": "Upscale",+ "sendTo": "Send to Upscale",+ "modelOnlyGroup": "Upscale now, model only",+ "noUpscalers": "Needs an installed upscale model",+ "scaleSuffix": "{{scale}}×",+ "factorNative": "{{scale}}× (native)",+ "nativeScaleUnknownFactor": "Native scale",+ "otherFactors": "Other factors",+ "metadataFailed": "Could not read the metadata of {{name}}. Nothing was queued.",+ "loadFailed": "Couldn't start the upscale. Reload the page and try again."}},"itemsAriaLabel": "Gallery items",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex 1f0a5599b9..82432a94d5 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -426,6 +426,86 @@ const createModels = (count) =>};});+/** A model record in the shape the list endpoint serves; the seed sets below override only what they need. */+const seedModel = ({ key, name, ...fields }) => ({+ base: 'any',+ cover_image: null,+ default_settings: null,+ description: null,+ file_size: 32_000_000,+ format: 'checkpoint',+ hash: `seed-hash-${key}`,+ key,+ name,+ path: `seeds/${key}.safetensors`,+ source: `seeds/${key}.safetensors`,+ source_type: 'path',+ source_url: null,+ trigger_phrases: null,+ variant: null,+ ...fields,+});++/**+ * Opt-in model sets for browser checks, added by `POST /__models` so the profiles' fixture counts stay fixed. Each+ * entry is the record as installed plus `probe`: the fields `POST /api/v2/models/i/{key}/reidentify` fills in, as+ * the backend's probe would for a record installed before it recorded them.+ */+export const MODEL_SEED_SETS = Object.freeze({+ // Anima ControlNet-LLLite adapters: one usable, two from before `cond_in_channels` was recorded.+ 'anima-lllite': [+ { record: seedModel({ base: 'anima', key: 'seed-anima-main', name: 'Anima Preview', type: 'main' }) },+ {+ record: seedModel({+ base: 'anima',+ cond_in_channels: 3,+ key: 'seed-lllite-sketch',+ name: 'Anima LLLite Sketch',+ type: 'controlnet',+ }),+ },+ {+ probe: { cond_in_channels: 3 },+ record: seedModel({+ base: 'anima',+ cond_in_channels: null,+ key: 'seed-lllite-lineart',+ name: 'Anima LLLite Lineart (old install)',+ type: 'controlnet',+ }),+ },+ {+ probe: { cond_in_channels: 4 },+ record: seedModel({+ base: 'anima',+ cond_in_channels: null,+ key: 'seed-lllite-inpaint',+ name: 'Anima LLLite Inpainting (old install)',+ type: 'controlnet',+ }),+ },+ ],+ // Spandrel upscalers with a recorded native scale, a 1x model, and one from before the scale was recorded.+ spandrel: [+ {+ record: seedModel({ key: 'seed-spandrel-4x', name: '4x-UltraSharp', scale: 4, type: 'spandrel_image_to_image' }),+ },+ {+ record: seedModel({ key: 'seed-spandrel-2x', name: '2x-AnimeSharp', scale: 2, type: 'spandrel_image_to_image' }),+ },+ { record: seedModel({ key: 'seed-spandrel-1x', name: '1x-Denoise', scale: 1, type: 'spandrel_image_to_image' }) },+ {+ probe: { scale: 4 },+ record: seedModel({+ key: 'seed-spandrel-legacy',+ name: 'RealESRGAN x4 (old install)',+ scale: null,+ type: 'spandrel_image_to_image',+ }),+ },+ ],+});+const createNodePacks = (nodeCount) =>range(Math.ceil(nodeCount / 5), (packIndex) => {const firstNodeIndex = packIndex * 5;diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex b67f1adcfb..0de6404aad 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -12,6 +12,7 @@ import {MOCK_BACKEND_PROFILE_COUNTS,MOCK_BACKEND_PROFILE_NAMES,MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,+ MODEL_SEED_SETS,PROJECT_FILE_BOARD,PROJECT_FILE_BOARD_ID,validateMockBackendFixture,@@ -1377,6 +1378,42 @@ test('queue chain rules: prune keeps finished children of an active root, and ca});});+test('model seed sets are opt-in, and re-identify fills what the probe would record', async () => {+ await withRepresentativeBackend(async (backend) => {+ const listed = async () => (await getJson(backend, '/api/v2/models/')).models;+ const before = (await listed()).length;+ const post = (path, body) =>+ fetch(`${backend.origin}${path}`, {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });++ assert.equal((await post('/__models', { set: 'nope' })).status, 400);+ const seeded = await (await post('/__models', { set: 'anima-lllite' })).json();+ await post('/__models', { set: 'spandrel' });+ assert.equal((await listed()).length, before + seeded.keys.length + MODEL_SEED_SETS.spandrel.length);++ const byKey = new Map((await listed()).map((model) => [model.key, model]));+ assert.equal(byKey.get('seed-lllite-lineart').cond_in_channels, null);+ assert.equal(byKey.get('seed-spandrel-4x').scale, 4);+ assert.equal(byKey.get('seed-spandrel-legacy').scale, null);++ const reidentify = async (key) => (await post(`/api/v2/models/i/${key}/reidentify`, {})).json();+ assert.equal((await reidentify('seed-lllite-lineart')).cond_in_channels, 3);+ assert.equal((await reidentify('seed-lllite-inpaint')).cond_in_channels, 4);+ assert.equal((await reidentify('seed-spandrel-legacy')).scale, 4);+ // A model with nothing left to record comes back unchanged, and the store serves the filled record.+ assert.deepEqual(await reidentify('seed-spandrel-2x'), byKey.get('seed-spandrel-2x'));+ assert.equal((await getJson(backend, '/api/v2/models/i/seed-lllite-lineart')).cond_in_channels, 3);+ assert.equal((await post('/api/v2/models/i/missing/reidentify', {})).status, 404);++ // A reset drops the seeds, keeping the profile's counts.+ await getJson(backend, '/__reset', { method: 'POST' });+ assert.equal((await listed()).length, before);+ });+});+test('runtime config PATCH keeps the other writable field and validates the queue history limit', async () => {await withRepresentativeBackend(async (backend) => {await getJson(backend, '/api/v1/app/runtime_config', {diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 61d90eaad2..7fdf396a09 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -11,6 +11,7 @@ import {getFixtureProjectWorkflowDocument,getMockBackendFixtureCounts,MOCK_BACKEND_FIXED_EPOCH,+ MODEL_SEED_SETS,} from './mock-backend-fixtures.mjs';/** The canvas schema every mock project declares; the real server keeps the same floor per record. */@@ -288,6 +289,8 @@ const createState = (profile) => {]),images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),models: new Map(fixture.models.map((model) => [model.key, clone(model)])),+ /** What re-identify fills in per model key; only `POST /__models` seeds entries. */+ modelProbes: new Map(),mutationClock: 0,nextBoardNumber: fixture.boards.length + 1,nextImageNumber: fixture.images.length + 1,@@ -1026,6 +1029,25 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {return json(200, { ok: true });}+ if (method === 'POST' && path === '/__models') {+ // Test seam: adds model records, from a named seed set or given whole; the profiles' counts stay fixed.+ const body = await readJsonBody(request);+ if (body.set !== undefined && !Object.hasOwn(MODEL_SEED_SETS, body.set)) {+ return json(400, { detail: `Unknown model seed set: ${String(body.set)}` });+ }+ const entries = [+ ...(body.set === undefined ? [] : MODEL_SEED_SETS[body.set]),+ ...(Array.isArray(body.models) ? body.models.map((record) => ({ record })) : []),+ ];+ for (const { probe, record } of entries) {+ state.models.set(record.key, clone(record));+ if (probe) {+ state.modelProbes.set(record.key, clone(probe));+ }+ }+ return json(200, { keys: entries.map(({ record }) => record.key), ok: true });+ }+if (path === '/__faults') {if (method === 'POST') {const body = await readJsonBody(request);@@ -1809,6 +1831,19 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {return json(200, []);}+ const reidentifyMatch = /^\/api\/v2\/models\/i\/([^/]+)\/reidentify$/.exec(path);+ if (method === 'POST' && reidentifyMatch) {+ // Like the backend's re-probe: fields recorded since the model was installed are filled in.+ const key = decodeURIComponent(reidentifyMatch[1]);+ const model = state.models.get(key);+ if (!model) {+ return json(404, { detail: 'Model not found' });+ }+ const identified = { ...model, ...state.modelProbes.get(key) };+ state.models.set(key, identified);+ return json(200, clone(identified));+ }+const modelMatch = /^\/api\/v2\/models\/i\/([^/]+)$/.exec(path);if (modelMatch) {const key = decodeURIComponent(modelMatch[1]);diff --git a/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsxindex 5397adb8bb..0b55cc9e73 100644--- a/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/AccountLifecycleCoordinator.browser.test.tsx@@ -113,11 +113,13 @@ vi.mock('@workbench/launchpad/Launchpad', () => ({Launchpad: () => null,}));-vi.mock('@workbench/projects/session', () => ({+vi.mock('@workbench/projects/session', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),peekOpenProjectIds: () => Promise.resolve(null),}));-vi.mock('@workbench/settings/store', () => ({+vi.mock('@workbench/settings/store', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),loadWorkbenchSettings: () => Promise.resolve(undefined),}));diff --git a/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsxnew file mode 100644index 0000000000..1e440f6690--- /dev/null+++ b/invokeai/frontend/webv2/src/app/AccountModelsUiProvider.browser.test.tsx@@ -0,0 +1,351 @@+import type { ArchitectureCapabilitiesRow } from '@features/generation/core/architectureCapabilities';+import type { ModelConfig } from '@features/models/core/types';+import type * as ModelsApi from '@features/models/data/api';+import type { DefaultSettingsModel } from '@features/models/ui/detail/defaultSettingsFields';+import type { ReactNode } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { AddModelsView } from '@features/models/ui/add-models/AddModelsView';+import { DefaultSettingsSection } from '@features/models/ui/detail/DefaultSettingsSection';+import { DetailPane } from '@features/models/ui/manager/DetailPane';+import { openModelDetail, setAddModelsQuery } from '@features/models/ui/uiStore';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { AccountModelsUiProvider } from './router';++/**+ * The Model Manager renders on the Launchpad, outside the editor's ports, so the authenticated layout's account Models+ * port is what its Default settings, re-identify notice and Install in place read: real capabilities, account+ * preferences, and Generate's scheduler rules loaded on demand.+ */++const api = vi.hoisted(() => ({+ getFp8StorageSupport: vi.fn(() => Promise.resolve([])),+ getModelsDir: vi.fn(() => Promise.resolve('')),+ listMissingModels: vi.fn(() => Promise.resolve([])),+ listModels: vi.fn(() => Promise.resolve([])),+ updateModel: vi.fn(),+}));+const capabilitiesApi = vi.hoisted(() => ({ get: vi.fn<() => Promise<ArchitectureCapabilitiesRow[]>>() }));+const session = vi.hoisted(() => ({ canManageModels: true }));+const preferences = vi.hoisted(() => ({ patch: vi.fn() }));++vi.mock('@features/models/data/api', async (importOriginal) => ({+ ...(await importOriginal<typeof ModelsApi>()),+ ...api,+}));+vi.mock('@features/generation/data/architectureCapabilitiesApi', () => ({+ getArchitectureCapabilities: () => capabilitiesApi.get(),+}));+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useCapabilities: () => ({ canManageModels: session.canManageModels }),+}));++// The account preferences, kept beyond each mount as the settings store keeps them.+const accountPreferences = createExternalStore({ enableModelDescriptions: true, installInPlace: true });+vi.mock('@workbench/settings/store', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ patchWorkbenchPreferences: (next: Record<string, unknown>) => {+ preferences.patch(next);+ accountPreferences.patchSnapshot(next);+ return Promise.resolve();+ },+ useWorkbenchPreferenceSelector: (select: (value: object) => unknown) => accountPreferences.useSelector(select),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, string>) => (values ? `${key}:${Object.values(values).join(',')}` : key),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const SCHEDULER_LABEL = 'models.defaultFields.scheduler';++const settingsModel = (overrides: Partial<DefaultSettingsModel>): DefaultSettingsModel => ({+ base: 'anima',+ default_settings: null,+ format: 'checkpoint',+ key: 'model-key',+ type: 'main',+ variant: null,+ ...overrides,+});++const schedulerSwitch = (host: HTMLElement) =>+ [...host.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].find((input) =>+ input.closest('label')?.textContent?.includes(`models.customizeDefaultField:${SCHEDULER_LABEL}`)+ );++const schedulerInput = () => document.querySelector<HTMLInputElement>(`input[aria-label="${SCHEDULER_LABEL}"]`);++const openOptions = async (): Promise<string[]> => {+ await act(() => schedulerInput()!.click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);++ return [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');+};++const clickButton = async (host: HTMLElement, label: string) => {+ const button = [...host.querySelectorAll('button')].find((candidate) => candidate.textContent === label);+ await act(async () => {+ button!.click();+ await Promise.resolve();+ });+};++const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });++ return { promise, resolve };+};++describe('Account Models port on the Launchpad', () => {+ let host: HTMLDivElement;+ let root: Root;++ const render = async (children: ReactNode) => {+ await act(async () => {+ root.render(+ <ChakraProvider value={system}>+ <AccountModelsUiProvider>{children}</AccountModelsUiProvider>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ };+ const renderDefaults = (model: DefaultSettingsModel) =>+ render(<DefaultSettingsSection model={model} onError={vi.fn()} onSaved={vi.fn()} />);++ beforeEach(() => {+ session.canManageModels = true;+ accountPreferences.setSnapshot({ enableModelDescriptions: true, installInPlace: true });+ preferences.patch.mockReset();+ capabilitiesApi.get.mockReset();+ capabilitiesApi.get.mockResolvedValue(architectureCapabilitiesFixture);+ // After the API stubs: a table requested earlier in the page is fetched again for the new account.+ accountLifecycle.activate('launchpad-models', ':user:launchpad-models');+ api.updateModel.mockReset();+ api.updateModel.mockImplementation((key: string, changes: { default_settings: object }) =>+ Promise.resolve({ ...settingsModel({ key }), ...changes })+ );+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ setAddModelsQuery('');+ // Clears the architecture table and the models store, as an account change does.+ accountLifecycle.invalidate();+ });++ describe('Default settings scheduler', () => {+ // The rules are a lazy chunk (the reader and the Generation modules it imports); load it up front so the first+ // test is not timing a cold transform. Importing it starts nothing: the section's load does.+ beforeAll(async () => {+ await import('./modelSchedulerPolicyReader');+ });++ it('loads Generate’s rules on demand and offers its Anima schedulers once the table arrives', async () => {+ const table = deferred<ArchitectureCapabilitiesRow[]>();+ capabilitiesApi.get.mockReturnValue(table.promise);+ await renderDefaults(settingsModel({}));++ // Until the table arrives the row holds its place, disabled and saying why.+ await expect.poll(() => capabilitiesApi.get.mock.calls.length).toBe(1);+ expect(schedulerSwitch(host)?.disabled).toBe(true);+ expect(host.textContent).toContain('models.schedulerListLoading');++ await act(async () => {+ table.resolve(architectureCapabilitiesFixture);+ await table.promise;+ });++ await expect.poll(() => schedulerSwitch(host)?.disabled).toBe(false);+ await act(() => schedulerSwitch(host)!.click());+ // Switched on at Anima's own default rather than an SD scheduler it cannot run.+ expect(schedulerInput()?.value).toBe('Euler');+ expect(await openOptions()).toEqual(['Euler', 'Heun (2nd order)', 'DPM++ 2M', 'DPM++ 2M SDE', 'ER-SDE', 'LCM']);+ });++ it('saves ER-SDE chosen for an SDXL model', async () => {+ await renderDefaults(settingsModel({ base: 'sdxl' }));+ await expect.poll(() => schedulerSwitch(host)?.disabled).toBe(false);++ await act(() => schedulerSwitch(host)!.click());+ expect(schedulerInput()?.value).toBe('Euler Ancestral');+ expect(await openOptions()).toContain('ER-SDE');+ const erSde = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (option) => option.textContent === 'ER-SDE'+ );+ await act(() => erSde!.click());+ await clickButton(host, 'models.saveDefaults');++ expect(api.updateModel).toHaveBeenCalledWith(+ 'model-key',+ { default_settings: expect.objectContaining({ scheduler: 'er_sde' }) },+ expect.anything()+ );+ });++ it('keeps a stored scheduler outside the base’s set visible until it is replaced', async () => {+ await renderDefaults(settingsModel({ base: 'flux', default_settings: { scheduler: 'dpmpp_2m_k' } }));+ await expect.poll(() => schedulerInput()?.value).toBe('dpmpp_2m_k');++ expect(await openOptions()).toEqual(['dpmpp_2m_k', 'Euler', 'Heun (2nd order)', 'LCM']);+ });++ it('shows the row on a base whose graph ignores the scheduler only to clear a stored value', async () => {+ await renderDefaults(settingsModel({ base: 'qwen-image', default_settings: { scheduler: 'euler' } }));+ await expect.poll(() => schedulerSwitch(host)?.checked).toBe(true);++ await act(() => schedulerSwitch(host)!.click());+ await clickButton(host, 'models.saveDefaults');+ expect(api.updateModel).toHaveBeenCalledWith(+ 'model-key',+ { default_settings: expect.objectContaining({ scheduler: null }) },+ expect.anything()+ );++ await act(() => root.unmount());+ root = createRoot(host);+ await renderDefaults(settingsModel({ base: 'qwen-image' }));+ await expect.poll(() => schedulerSwitch(host)).toBeUndefined();+ expect(host.textContent).toContain('models.defaultFields.vae');+ });++ it('says the list is unavailable when the table fails, keeps a stored value, and retries', async () => {+ capabilitiesApi.get.mockRejectedValue(new Error('offline'));+ await act(() => accountLifecycle.activate('launchpad-models-offline', ':user:launchpad-models-offline'));+ await renderDefaults(settingsModel({ base: 'sdxl', default_settings: { scheduler: 'er_sde' } }));++ await expect.poll(() => host.textContent).toContain('models.schedulerListUnavailable');+ // The stored choice stays named and can still be cleared; nothing can be picked without the rules.+ expect(schedulerInput()?.value).toBe('er_sde');+ expect(schedulerInput()?.disabled).toBe(true);+ expect(schedulerSwitch(host)?.disabled).toBe(false);++ const failedRequests = capabilitiesApi.get.mock.calls.length;+ const table = deferred<ArchitectureCapabilitiesRow[]>();+ capabilitiesApi.get.mockReturnValue(table.promise);+ const retry = [...host.querySelectorAll('button')].find((button) => button.textContent === 'common.retry')!;+ await act(() => userEvent.click(retry));++ // While the retry loads, the same button stays focused, marked busy rather than disabled.+ await expect.poll(() => retry.textContent).toBe('models.schedulerListRetrying');+ expect(retry.getAttribute('aria-disabled')).toBe('true');+ expect(document.activeElement).toBe(retry);++ await act(async () => {+ table.resolve(architectureCapabilitiesFixture);+ await table.promise;+ });++ await expect.poll(() => schedulerInput()?.disabled).toBe(false);+ expect(capabilitiesApi.get).toHaveBeenCalledTimes(failedRequests + 1);+ expect(host.textContent).not.toContain('models.schedulerListUnavailable');+ expect(schedulerInput()?.value).toBe('ER-SDE');+ // The button left with the note; its focus moved to the scheduler row rather than the page body.+ await expect.poll(() => document.activeElement).toBe(schedulerSwitch(host));++ // The retry is over: a later ordinary load (another account here) says it is loading, not retrying.+ capabilitiesApi.get.mockReturnValue(deferred<ArchitectureCapabilitiesRow[]>().promise);+ await act(() => accountLifecycle.activate('launchpad-models-next', ':user:launchpad-models-next'));+ await expect.poll(() => host.textContent).toContain('models.schedulerListLoading');+ expect(host.textContent).not.toContain('models.schedulerListRetrying');+ });++ it('hands the Retry focus to the section heading when the recovered base has no scheduler row', async () => {+ capabilitiesApi.get.mockRejectedValue(new Error('offline'));+ await act(() => accountLifecycle.activate('launchpad-models-offline', ':user:launchpad-models-offline'));+ // Qwen Image's graph ignores the scheduler and nothing is stored: once the rules arrive the row goes.+ await renderDefaults(settingsModel({ base: 'qwen-image' }));+ await expect.poll(() => host.textContent).toContain('models.schedulerListUnavailable');++ capabilitiesApi.get.mockResolvedValue(architectureCapabilitiesFixture);+ const retry = [...host.querySelectorAll('button')].find((button) => button.textContent === 'common.retry')!;+ await act(() => userEvent.click(retry));++ await expect.poll(() => schedulerSwitch(host)).toBeUndefined();+ const heading = [...host.querySelectorAll<HTMLElement>('[tabindex="-1"]')].find((element) =>+ element.textContent?.startsWith('models.defaultSettings')+ );+ await expect.poll(() => document.activeElement).toBe(heading);+ });+ });++ describe('Model Manager surfaces by capability', () => {+ const UNIDENTIFIED_LLLITE = {+ base: 'anima',+ cond_in_channels: null,+ file_size: 1024,+ format: 'checkpoint',+ hash: 'hash-lllite',+ key: 'lllite-1',+ name: 'Anima LLLite',+ path: '/models/lllite.safetensors',+ source: '/models/lllite.safetensors',+ source_type: 'path',+ type: 'controlnet',+ } as ModelConfig;++ const showDetail = async () => {+ setModelsSnapshotForTests({ models: [UNIDENTIFIED_LLLITE], status: 'loaded' });+ openModelDetail(UNIDENTIFIED_LLLITE.key);+ await render(<DetailPane />);+ };+ const hasReidentifyButton = () =>+ [...host.querySelectorAll('button')].some((button) => button.textContent === 'models.reidentify');++ it('offers Re-identify on the notice to a user who manages models', async () => {+ await showDetail();++ expect(host.textContent).toContain('models.adapterTypeUnknown');+ expect(host.textContent).not.toContain('models.reidentifyAskAdmin');+ expect(hasReidentifyButton()).toBe(true);+ });++ it('shows a user without model management the notice and who to ask, and no button', async () => {+ session.canManageModels = false;+ await showDetail();++ expect(host.textContent).toContain('models.reidentifyAskAdmin');+ expect(hasReidentifyButton()).toBe(false);+ });++ it('saves Install in place to the account and reads it back on the next visit', async () => {+ setModelsSnapshotForTests({ models: [], modelsDir: '/opt/invokeai/models', status: 'loaded' });+ await render(<AddModelsView />);+ const inplaceInput = () =>+ [...host.querySelectorAll('label')]+ .find((label) => label.textContent === 'models.installInPlace')+ ?.querySelector('input');++ await act(() =>+ userEvent.fill(host.querySelector<HTMLInputElement>('input[aria-label="models.searchOrAdd"]')!, '/tmp/x.ckpt')+ );+ await act(() => userEvent.click(inplaceInput()!.closest('label')!));+ expect(preferences.patch).toHaveBeenCalledExactlyOnceWith({ installInPlace: false });++ await act(() => root.unmount());+ root = createRoot(host);+ await render(<AddModelsView />);+ expect(inplaceInput()?.checked).toBe(false);+ });+ });+});diff --git a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsxindex b3e8ee03b0..c37398f0b5 100644--- a/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/ModelsUiAdapter.tsx@@ -1,20 +1,18 @@import type { ModelsUiAdapter } from '@features/models';import type { ReactNode } from 'react';-import { useCapabilities } from '@features/identity';-import { ModelsUiProvider } from '@features/models';-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';+import { ModelsUiProvider, useModelsUi } from '@features/models';import { useActiveProjectId, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useMemo } from 'react';+/** Narrows the account's Models port (see the authenticated layout) so pickers open the manager for this project. */export const ModelsUiAdapterProvider = ({ children }: { children: ReactNode }) => {- const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);+ const account = useModelsUi();const managerProjectId = useActiveProjectId();const { isActiveProject } = useWorkbenchQueries();- const { canManageModels } = useCapabilities();const adapter = useMemo<ModelsUiAdapter>(- () => ({ canManageModels, enableModelDescriptions, isProjectActive: isActiveProject, managerProjectId }),- [canManageModels, enableModelDescriptions, isActiveProject, managerProjectId]+ () => ({ ...account, isProjectActive: isActiveProject, managerProjectId }),+ [account, isActiveProject, managerProjectId]);return <ModelsUiProvider adapter={adapter}>{children}</ModelsUiProvider>;diff --git a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsxindex 40c29fbab6..2503e7bca9 100644--- a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx@@ -28,12 +28,17 @@ const modelSnapshot = {hash: 's',key: 'spandrel',name: 'Spandrel',+ scale: 4,type: 'spandrel_image_to_image',},+ // Installed before Invoke recorded native scales, and not re-identified since.+ { base: 'any', format: 'checkpoint', hash: 'l', key: 'legacy', name: 'Legacy', type: 'spandrel_image_to_image' },] as ModelConfig[],status: 'loaded',};const getArchitectureCapabilities = vi.fn<() => Promise<ArchitectureCapabilitiesRow[]>>();+// Null for a session that may not manage models, as the hook answers.+const modelManager = vi.hoisted(() => ({ open: null as ((modelKey: string) => void) | null }));const noop = () => undefined;const generationAdapter = {sectionPreferences: { sectionsOpen: {}, setSectionOpen: noop },@@ -55,13 +60,25 @@ vi.mock('@features/models', async (importOriginal) => ({ensureModelsLoaded: () => Promise.resolve(),getModelImageUrl: () => '',useModelsSelector: (selector: (snapshot: typeof modelSnapshot) => unknown) => selector(modelSnapshot),- useOpenModelInManager: () => undefined,-}));-// The pickers' transport is not under test; the form around them is.-vi.mock('@features/models/react', async (importOriginal) => ({- ...(await importOriginal<Record<string, unknown>>()),- ModelSelect: () => null,+ useOpenModelInManager: () => modelManager.open,}));+// The pickers' transport is not under test; the form around them is. The stand-in takes its description from the+// enclosing field, as ModelSelect's own tests show the picker does.+vi.mock('@features/models/react', async (importOriginal) => {+ const { useFieldContext } = await import('@chakra-ui/react');++ return {+ ...(await importOriginal<Record<string, unknown>>()),+ ModelSelect: () => (+ <button+ aria-describedby={useFieldContext()?.getInputProps()['aria-describedby']}+ aria-haspopup="listbox"+ aria-label="Model picker"+ type="button"+ />+ ),+ };+});vi.mock('@features/gallery/mediaSlot', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),GalleryMediaSlot: () => null,@@ -113,7 +130,95 @@ afterEach(async () => {accountLifecycle.invalidate();});+const renderUpscale = () =>+ settle(() =>+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <GenerationUiProvider adapter={generationAdapter}>+ <UpscaleUiAdapterProvider>+ <UpscaleWidgetView />+ </UpscaleUiAdapterProvider>+ </GenerationUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );++describe('Upscale Refine and Model only modes', () => {+ const sectionLabels = () =>+ ['widgets.upscale.detailGuidance', 'widgets.upscale.generation', 'widgets.upscale.advanced'].filter((label) =>+ [...host.querySelectorAll('button')].some((button) => button.textContent?.startsWith(label))+ );+ const pickMode = (label: string) =>+ settle(() =>+ [...host.querySelectorAll<HTMLElement>('[data-part="item"]')].find((item) => item.textContent === label)?.click()+ );++ it('hides what only the detail pass reads in Model only, explains the native scale, and restores Refine as left', async () => {+ getArchitectureCapabilities.mockResolvedValue(architectureCapabilitiesFixture);+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ creativity: 5,+ inputImage: { height: 800, image_name: 'input.png', width: 1000 },+ scale: 2,+ });++ await renderUpscale();++ const modes = host.querySelector('[aria-label="widgets.upscale.mode"]');+ expect(modes?.querySelector('[data-state="checked"]')?.textContent).toBe('widgets.upscale.modeRefine');+ expect(sectionLabels()).toHaveLength(3);+ expect(host.querySelector('[aria-label="widgets.upscale.presetsLabel"]')).not.toBeNull();+ expect(host.textContent).not.toContain('widgets.upscale.nativeScale');++ await pickMode('widgets.upscale.modeModelOnly');++ expect(storedValues()).toMatchObject({ creativity: 5, mode: 'model-only' });+ expect(sectionLabels()).toEqual([]);+ expect(host.querySelector('[aria-label="widgets.upscale.presetsLabel"]')).toBeNull();+ expect(host.textContent).not.toContain('widgets.upscale.creativity');+ // The 4x upscaler runs once and resizes down to Scale 2.+ expect(host.textContent).toContain('widgets.upscale.nativeScale');+ expect(host.textContent).toContain('widgets.upscale.nativeScalePassesResize');+ expect(host.textContent).toContain('2,000 × 1,600');++ await pickMode('widgets.upscale.modeRefine');++ expect(storedValues()).toMatchObject({ creativity: 5, mode: 'refine' });+ expect(sectionLabels()).toHaveLength(3);+ expect(host.textContent).not.toContain('widgets.upscale.nativeScale');+ });+});+describe('Upscale without the served architecture table', () => {+ it('keeps Model only usable, since it reads no main-model capabilities, and holds back only Refine', async () => {+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: { height: 800, image_name: 'input.png', width: 1000 },+ mode: 'model-only',+ upscaleModel: modelSnapshot.models[1] as never,+ });+ getArchitectureCapabilities.mockRejectedValue(new Error('Fixture capability outage.'));++ await renderUpscale();++ expect(host.querySelector('[role="alert"]')).toBeNull();+ expect(host.textContent).toContain('widgets.upscale.nativeScale');+ expect(host.textContent).toContain('4,000 × 3,200');++ await settle(() =>+ [...host.querySelectorAll<HTMLElement>('[data-part="item"]')]+ .find((item) => item.textContent === 'widgets.upscale.modeRefine')+ ?.click()+ );++ expect(host.querySelector('[role="alert"]')?.textContent).toContain('widgets.upscale.capabilitiesLoadFailed');+ // The mode stays reachable above the gate, so the user can go back to Model only.+ expect(host.querySelector('[aria-label="widgets.upscale.mode"]')).not.toBeNull();+ expect(storedValues()).toMatchObject({ mode: 'refine', model: null });+ });+it("picks no model until the table loads, then gives the one it picks that model's CFG", async () => {// A fresh widget: no model yet, the widget's CFG 2.store.commands.widgets.patchValues('upscale', { ...createDefaultUpscaleWidgetValues() });@@ -157,3 +262,69 @@ describe('Upscale without the served architecture table', () => {expect(host.querySelector('[aria-label="widgets.upscale.scheduler"]')).toBeNull();});});++describe('Upscale Model only with an upscaler of unknown native scale', () => {+ const NATIVE_SCALE_UNKNOWN = 'widgets.upscale.nativeScaleUnknown';+ const OPEN_IN_MODEL_MANAGER = 'widgets.upscale.openInModelManager';+ const renderWithLegacyUpscaler = (mode: 'model-only' | 'refine') => {+ getArchitectureCapabilities.mockResolvedValue(architectureCapabilitiesFixture);+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: { height: 800, image_name: 'input.png', width: 1000 },+ mode,+ upscaleModel: modelSnapshot.models[2] as never,+ });++ return renderUpscale();+ };+ /** The Spandrel model picker's accessible description, read through its `aria-describedby`. */+ const upscalerDescription = () => {+ const pickers = [...host.querySelectorAll<HTMLElement>('[aria-haspopup="listbox"]')];+ const spandrel = pickers.find((picker) =>+ picker.closest('[data-part="root"]')?.textContent?.includes('widgets.upscale.spandrelModel')+ );++ return (spandrel?.getAttribute('aria-describedby') ?? '')+ .split(' ')+ .map((id) => document.getElementById(id)?.textContent ?? '')+ .join(' ');+ };+ const openButton = () =>+ [...host.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === OPEN_IN_MODEL_MANAGER+ );++ afterEach(() => {+ modelManager.open = null;+ });++ it('says why no plan is shown and opens that upscaler in the Model Manager to re-identify it', async () => {+ const open = vi.fn();+ modelManager.open = open;++ await renderWithLegacyUpscaler('model-only');++ expect(upscalerDescription()).toBe(NATIVE_SCALE_UNKNOWN);+ expect(host.textContent).not.toContain('widgets.upscale.nativeScaleValue');++ await settle(() => openButton()?.click());++ expect(open).toHaveBeenCalledWith('legacy');+ });++ it('keeps the hint without the link for a session that cannot manage models', async () => {+ await renderWithLegacyUpscaler('model-only');++ expect(upscalerDescription()).toBe(NATIVE_SCALE_UNKNOWN);+ expect(openButton()).toBeUndefined();+ });++ it('says nothing in Refine, whose detail pass resizes to Scale whatever the upscaler does', async () => {+ modelManager.open = vi.fn();++ await renderWithLegacyUpscaler('refine');++ expect(host.textContent).not.toContain(NATIVE_SCALE_UNKNOWN);+ expect(upscalerDescription()).toBe('widgets.upscale.spandrelModelHelp');+ });+});diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex dfc664a5ca..810183313c 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -168,6 +168,7 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNodereturn resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),+ formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),models: availabilityModels,owner,prepareCanvasInvocation,diff --git a/invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.ts b/invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.tsnew file mode 100644index 0000000000..724b237e3a--- /dev/null+++ b/invokeai/frontend/webv2/src/app/modelSchedulerPolicyReader.ts@@ -0,0 +1,50 @@+import type { ArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';+import type { SchedulerPolicyReader, SchedulerPolicyState } from '@features/models';++import {+ ensureArchitectureCapabilitiesLoaded,+ getArchitectureCapabilitiesSnapshot,+ subscribeArchitectureCapabilities,+} from '@features/generation/runtime';+import { getDefaultGenerateSettings, getGenerationUiPolicy, getSchedulerOptions } from '@features/generation/settings';++type GenerateMainModel = Parameters<typeof getDefaultGenerateSettings>[0] & { type: 'main' };++/** Generate's per-base rules; the stored default is dropped so the base's own default is read. */+const readSchedulerPolicy: SchedulerPolicyReader = (model, currentValue) => {+ const mainModel = { ...model, default_settings: null, type: 'main' } as GenerateMainModel;++ return {+ appliesToGraph: getGenerationUiPolicy(mainModel).schedulerVisible,+ defaultValue: getDefaultGenerateSettings(mainModel).scheduler,+ options: getSchedulerOptions(mainModel, currentValue ?? undefined),+ };+};++const toPolicyState = (snapshot: ArchitectureCapabilitiesSnapshot): SchedulerPolicyState => {+ if (snapshot.status === 'loaded' && snapshot.revision > 0) {+ return { read: (model, currentValue) => readSchedulerPolicy(model, currentValue), status: 'ready' };+ }+ return snapshot.status === 'error' ? { status: 'unavailable' } : { status: 'loading' };+};++/**+ * Publishes the rules' state now and whenever the architecture table's status or revision changes, with a new reader+ * per revision so memoized callers recompute. Lives for the page, like the table's own store.+ */+export const startSchedulerPolicyReader = (publish: (state: SchedulerPolicyState) => void): void => {+ let published: Pick<ArchitectureCapabilitiesSnapshot, 'revision' | 'status'> | null = null;+ const sync = () => {+ const snapshot = getArchitectureCapabilitiesSnapshot();+ if (published?.revision === snapshot.revision && published.status === snapshot.status) {+ return;+ }+ published = { revision: snapshot.revision, status: snapshot.status };+ publish(toPolicyState(snapshot));+ };+ sync();+ subscribeArchitectureCapabilities(sync);+};++/** Joins or starts the table's load; it never rejects (see `ensureArchitectureCapabilitiesLoaded`). */+export const ensureSchedulerRulesLoaded = (): Promise<void> => ensureArchitectureCapabilitiesLoaded();diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsxindex 2d2b4acd50..b4de9e0889 100644--- a/invokeai/frontend/webv2/src/app/router.tsx+++ b/invokeai/frontend/webv2/src/app/router.tsx@@ -7,10 +7,18 @@ import {LoginScreen,SetupScreen,useAuthSession,+ useCapabilities,type Capabilities,} from '@features/identity';-import { ModelInstallRuntime } from '@features/models';+import {+ ModelInstallRuntime,+ ModelsUiProvider,+ type ModelsUiAdapter,+ type SchedulerPolicySource,+ type SchedulerPolicyState,+} from '@features/models';import { createLogger } from '@platform/logging/logger';+import { createListenerChannel } from '@platform/state/externalStoreCore';import {createHashHistory,createRootRoute,@@ -29,9 +37,15 @@ import { isLaunchpadIntentId } from '@workbench/launchpad/intents';import { Launchpad } from '@workbench/launchpad/Launchpad';import { ProjectFileOptionsProvider } from '@workbench/projects/components/ProjectFileOptionsProvider';import { peekOpenProjectIds, type WorkbenchSearch } from '@workbench/projects/session';-import { loadWorkbenchSettings } from '@workbench/settings/store';+import {+ loadWorkbenchSettings,+ patchWorkbenchPreferences,+ useWorkbenchPreferenceSelector,+} from '@workbench/settings/store';import { loadAppVersion } from '@workbench/shell/whatsNewStore';-import { Fragment } from 'react';+import { Fragment, useMemo, type ReactNode } from 'react';++import type * as SchedulerRules from './modelSchedulerPolicyReader';import { SocketHubRuntime } from './SocketHubRuntime';@@ -57,6 +71,72 @@ const RouterError = ({ error }: ErrorComponentProps) => {const rootRoute = createRootRoute({ component: Outlet, errorComponent: RouterError });+const SCHEDULER_RULES_LOADING: SchedulerPolicyState = { status: 'loading' };+const SCHEDULER_RULES_UNAVAILABLE: SchedulerPolicyState = { status: 'unavailable' };+let schedulerPolicyState: SchedulerPolicyState = SCHEDULER_RULES_LOADING;+let schedulerRules: Promise<typeof SchedulerRules> | null = null;+const schedulerPolicyChannel = createListenerChannel();++const publishSchedulerPolicy = (next: SchedulerPolicyState): void => {+ schedulerPolicyState = next;+ schedulerPolicyChannel.notify();+};++/**+ * Generate's scheduler rules for the Model Manager's defaults. They and the architecture table they read live in+ * Generation, which the Launchpad does not load at startup, so they arrive with the first Default settings section.+ */+const schedulerPolicySource: SchedulerPolicySource = {+ getSnapshot: () => schedulerPolicyState,+ load: () => {+ if (!schedulerRules) {+ if (schedulerPolicyState.status === 'unavailable') {+ publishSchedulerPolicy(SCHEDULER_RULES_LOADING);+ }+ schedulerRules = import('./modelSchedulerPolicyReader').then((rules) => {+ rules.startSchedulerPolicyReader(publishSchedulerPolicy);+ return rules;+ });+ }+ // Asked on every load: it retries a failed table, and an account change clears the table.+ schedulerRules+ .then((rules) => rules.ensureSchedulerRulesLoaded())+ .catch(() => {+ // The rules' chunk failed to load; the next load (Retry, or another section) imports it again.+ schedulerRules = null;+ publishSchedulerPolicy(SCHEDULER_RULES_UNAVAILABLE);+ });+ },+ subscribe: schedulerPolicyChannel.subscribe,+};++const setInstallInPlace = (installInPlace: boolean) => void patchWorkbenchPreferences({ installInPlace });+const NO_ACTIVE_PROJECT = () => false;++/**+ * The account's Models port for every authenticated route: the Model Manager renders on the Launchpad, and the editor+ * narrows this with its active project. Composed here because a new module would enter the Launchpad's startup graph.+ */+export const AccountModelsUiProvider = ({ children }: { children: ReactNode }) => {+ const enableModelDescriptions = useWorkbenchPreferenceSelector((value) => value.enableModelDescriptions);+ const installInPlace = useWorkbenchPreferenceSelector((value) => value.installInPlace);+ const { canManageModels } = useCapabilities();+ const adapter = useMemo<ModelsUiAdapter>(+ () => ({+ canManageModels,+ enableModelDescriptions,+ installInPlace,+ isProjectActive: NO_ACTIVE_PROJECT,+ managerProjectId: null,+ schedulerPolicy: schedulerPolicySource,+ setInstallInPlace,+ }),+ [canManageModels, enableModelDescriptions, installInPlace]+ );++ return <ModelsUiProvider adapter={adapter}>{children}</ModelsUiProvider>;+};+/*** Keep socket and install progress alive across authenticated routes; mount heavier feature listeners only where* needed.@@ -80,7 +160,9 @@ const AuthenticatedLayout = () => {<ModelInstallRuntime /><FontsRuntimeProvider><ProjectFileOptionsProvider>- <Outlet />+ <AccountModelsUiProvider>+ <Outlet />+ </AccountModelsUiProvider></ProjectFileOptionsProvider></FontsRuntimeProvider></Fragment>diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex 9405bcfd44..e76f3d9bd8 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -36,7 +36,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[models: ['launchpad', 'react'],nodes: [],queue: ['contracts', 'devices', 'launchpad', 'menu', 'queries', 'react', 'reveal', 'utility', 'widget'],- upscale: ['widget'],+ upscale: ['sourceMetadata', 'widget'],video: ['widget'],workflow: ['contracts', 'generators', 'graph', 'paletteSearch', 'preview', 'queries', 'react', 'utility', 'widget'],};diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 61ca0422ee..f2fe327b4f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -480,6 +480,7 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generatqwen3VLEncoderModel: null,qwen35EncoderModel: null,animaInpaintAdapterModel: null,+ animaInpaintAdapterEnabled: true,animaInpaintAdapterWeight: DEFAULT_ANIMA_INPAINT_ADAPTER_WEIGHT,wanT5EncoderModel: null,ideogram4UnconditionalModel: null,diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex b872963ab0..ea3a660c81 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -1338,19 +1338,21 @@ describe('compileCanvasGraph — Anima ControlNet-LLLite (integration)', () => {);});- it.each(['inpaint', 'outpaint'] as const)(- 'adds no adapter nodes, edges or metadata to the %s graph without one',- (mode) => {- const { backendGraph } = compile(animaModel, mode, { settings: { animaInpaintAdapterModel: null } });+ it.each([+ ['inpaint', 'without one', { animaInpaintAdapterModel: null }],+ ['outpaint', 'without one', { animaInpaintAdapterModel: null }],+ ['inpaint', 'switched off', { ...withAdapter(0.8), animaInpaintAdapterEnabled: false }],+ ['outpaint', 'switched off', { ...withAdapter(0.8), animaInpaintAdapterEnabled: false }],+ ] as const)('adds no adapter nodes, edges or metadata to the %s graph %s', (mode, _case, settings) => {+ const { backendGraph } = compile(animaModel, mode, { settings });- expect(backendGraph.nodes.anima_inpaint_adapter).toBeUndefined();- expect(backendGraph.nodes.invert_anima_inpaint_adapter_mask).toBeUndefined();- expect(backendGraph.nodes.control_lllite_collector).toBeUndefined();- expect(getEdge(backendGraph, 'denoise_latents', 'control_lllite')).toBeUndefined();- expect(getNodeByType(backendGraph, 'core_metadata')).not.toHaveProperty('anima_inpaint_adapter');- expect(getNodeByType(backendGraph, 'core_metadata')).not.toHaveProperty('anima_inpaint_adapter_weight');- }- );+ expect(backendGraph.nodes.anima_inpaint_adapter).toBeUndefined();+ expect(backendGraph.nodes.invert_anima_inpaint_adapter_mask).toBeUndefined();+ expect(backendGraph.nodes.control_lllite_collector).toBeUndefined();+ expect(getEdge(backendGraph, 'denoise_latents', 'control_lllite')).toBeUndefined();+ expect(getNodeByType(backendGraph, 'core_metadata')).not.toHaveProperty('anima_inpaint_adapter');+ expect(getNodeByType(backendGraph, 'core_metadata')).not.toHaveProperty('anima_inpaint_adapter_weight');+ });it('outpaint with Scale Before Processing: the adapter reads the resized combined mask (legacy addOutpaint.ts:182)', () => {const { backendGraph } = compile(animaModel, 'outpaint', {@@ -1409,6 +1411,16 @@ describe('compileCanvasGraph — Anima ControlNet-LLLite (integration)', () => {expect(() => compile(animaModel, 'outpaint', { settings: withAdapter(10.5) })).toThrow('Anima inpaint adapter weight must be between -10 and 10.');+ // A switched-off adapter is not validated: the kept selection must not block inpainting.+ expect(() =>+ compile(animaModel, 'inpaint', {+ settings: {+ animaInpaintAdapterEnabled: false,+ animaInpaintAdapterModel: { ...inpaintAdapter, cond_in_channels: 3 },+ animaInpaintAdapterWeight: 10.5,+ },+ })+ ).not.toThrow();// Installs that predate `cond_in_channels` are inpaint adapters (legacy isAnimaInpaintControlNetModelConfig).expect(() =>compile(animaModel, 'inpaint', {diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex ea361fd5d0..1a8f66b112 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -79,9 +79,9 @@ const isImageMode = (mode: CompileCanvasGraphInput['mode']): boolean => mode !==const sizesMatch = (left: CanvasSize, right: CanvasSize): boolean =>left.width === right.width && left.height === right.height;-/** Whether an Anima inpaint/outpaint graph gets the adapter: it is picked, and the base is Anima. */+/** Whether an Anima inpaint/outpaint graph gets the adapter: it is switched on and picked, and the base is Anima. */const hasAnimaInpaintAdapter = (model: GenerateModelConfig, settings: GenerateSettings): boolean =>- model.base === 'anima' && settings.animaInpaintAdapterModel !== null;+ model.base === 'anima' && settings.animaInpaintAdapterEnabled && settings.animaInpaintAdapterModel !== null;/*** The legacy PiD guards (`buildSDXLGraph.ts:192–205`, repeated in the other builders): only the txt2img and img2imgdiff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex db1cef340a..f5d373e07d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -392,6 +392,17 @@ describe('the Anima inpaint adapter settings', () => {})).toMatchObject({ animaInpaintAdapterModel: null, animaInpaintAdapterWeight: 1 });});++ it('keeps the adapter switched on unless a stored value turns it off', () => {+ // Projects saved before the toggle existed wired a selected adapter, so a missing value means on.+ expect(normalizeGenerateSettings(legacyStoredValues)?.animaInpaintAdapterEnabled).toBe(true);+ const enabledFrom = (stored: unknown) =>+ normalizeGenerateSettings({ ...legacyStoredValues, animaInpaintAdapterEnabled: stored })+ ?.animaInpaintAdapterEnabled;+ expect(enabledFrom(false)).toBe(false);+ expect(enabledFrom(true)).toBe(true);+ expect(enabledFrom('off')).toBe(true);+ });});describe('Generate widget value snapshots', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex dea964ea14..c3dcc50eb6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -852,6 +852,8 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | nqwen3VLEncoderModel: getModelIdentifierOrNull(values.qwen3VLEncoderModel),qwen35EncoderModel: getModelIdentifierOrNull(values.qwen35EncoderModel),animaInpaintAdapterModel: getModelIdentifierOrNull(values.animaInpaintAdapterModel),+ // Projects saved before the toggle existed wired the adapter whenever one was selected.+ animaInpaintAdapterEnabled: values.animaInpaintAdapterEnabled !== false,animaInpaintAdapterWeight: clampAnimaInpaintAdapterWeight(hasFiniteNumber(values, 'animaInpaintAdapterWeight')? (values.animaInpaintAdapterWeight as number)diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex a2ba70b472..208c3ffa96 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -240,6 +240,8 @@ export interface GenerateSettings {* inpaint mask while inpainting or outpainting; Generate and the other canvas modes ignore it.*/animaInpaintAdapterModel: ComponentModelConfig | null;+ /** Off skips the adapter on the canvas and keeps the selected model and weight. */+ animaInpaintAdapterEnabled: boolean;animaInpaintAdapterWeight: number;/** Wan 2.2's UMT5-XXL text encoder. */wanT5EncoderModel: ComponentModelConfig | null;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsxindex 1450a51c07..9d51ee0878 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx@@ -1,7 +1,7 @@import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { Stack } from '@chakra-ui/react';+import { Stack, Text } from '@chakra-ui/react';import {getComponentSectionPolicy,type ComponentPolicyContext,@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next';import { type GenerateDraft, pickGenerateSettings } from './generateDebounce';import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';+import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';interface GenerateComponentsSectionProps {draft: GenerateDraft;@@ -35,6 +36,7 @@ const toComponentModel = (model: ModelConfig | null): ComponentModelConfig | nulisModelIdentifierConfig(model) ? model : null;const selectComponentSettings = pickGenerateSettings([+ 'animaInpaintAdapterEnabled','animaInpaintAdapterModel','animaInpaintAdapterWeight','clipEmbedModel',@@ -162,7 +164,11 @@ export const GenerateComponentsSection = ({ draft, onCommit, selectedModel }: Ge<ComponentPickerRow key={slot.key} commitSlotValue={commitSlotValue} ctx={ctx!} slot={slot} />))}{settings.animaInpaintAdapterModel && policy.slots.some((slot) => slot.key === 'animaInpaintAdapterModel') ? (- <AnimaInpaintAdapterWeightField value={settings.animaInpaintAdapterWeight} onCommit={onCommit} />+ <AnimaInpaintAdapterControls+ enabled={settings.animaInpaintAdapterEnabled}+ weight={settings.animaInpaintAdapterWeight}+ onCommit={onCommit}+ />) : null}</Stack></GenerateCollapsibleSection>@@ -172,36 +178,57 @@ export const GenerateComponentsSection = ({ draft, onCommit, selectedModel }: Ge/** The legacy slider spanned 0 to 2 with these stops; typed values may use the node's full range. */const ANIMA_INPAINT_ADAPTER_WEIGHT_MARKS = [0, 1, 2];-const AnimaInpaintAdapterWeightField = ({+/** Switching the adapter off keeps its selection and weight, so switching back on restores them. */+const AnimaInpaintAdapterControls = ({+ enabled,onCommit,- value,+ weight,}: {+ enabled: boolean;onCommit: (patch: Partial<GenerateSettings>) => void;- value: number;+ weight: number;}) => {const { t } = useTranslation();- const onChange = useCallback(- (weight: number) => {- if (Number.isFinite(weight)) {- onCommit({ animaInpaintAdapterWeight: weight });+ const onEnabledChange = useCallback(+ (checked: boolean) => onCommit({ animaInpaintAdapterEnabled: checked }),+ [onCommit]+ );+ const onWeightChange = useCallback(+ (value: number) => {+ if (Number.isFinite(value)) {+ onCommit({ animaInpaintAdapterWeight: value });}},[onCommit]);return (- <ScrubberField- defaultValue={DEFAULT_ANIMA_INPAINT_ADAPTER_WEIGHT}- inputMax={MAX_ANIMA_INPAINT_ADAPTER_WEIGHT}- inputMin={MIN_ANIMA_INPAINT_ADAPTER_WEIGHT}- label={t('widgets.generate.animaInpaintAdapterWeight')}- marks={ANIMA_INPAINT_ADAPTER_WEIGHT_MARKS}- max={2}- min={0}- step={0.05}- value={value}- onChange={onChange}- />+ <Stack gap="1.5">+ <GenerateToggleSwitch+ checked={enabled}+ label={t('widgets.generate.animaInpaintAdapterEnabled')}+ labelVisible+ onCheckedChange={onEnabledChange}+ />+ {enabled ? null : (+ <Text color="fg.muted" fontSize="xs">+ {t('widgets.generate.animaInpaintAdapterOffHelp')}+ </Text>+ )}+ <ScrubberField+ defaultValue={DEFAULT_ANIMA_INPAINT_ADAPTER_WEIGHT}+ disabled={!enabled}+ inputMax={MAX_ANIMA_INPAINT_ADAPTER_WEIGHT}+ inputMin={MIN_ANIMA_INPAINT_ADAPTER_WEIGHT}+ label={t('widgets.generate.animaInpaintAdapterWeight')}+ marks={ANIMA_INPAINT_ADAPTER_WEIGHT_MARKS}+ max={2}+ min={0}+ step={0.05}+ value={weight}+ onChange={onWeightChange}+ />+ </Stack>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsxindex 4c83f094b9..8d4e2cfa29 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx@@ -338,6 +338,52 @@ describe('GenerateSettingsForm Anima inpaint adapter', () => {expect(storedValues().getSnapshot()).toMatchObject({ animaInpaintAdapterWeight: 1.05 });});++ it('switches the adapter off and back on without losing the pick or the weight', async () => {+ const switchLabel = 'widgets.generate.animaInpaintAdapterEnabled';+ const offHelp = 'widgets.generate.animaInpaintAdapterOffHelp';+ const adapterSwitch = () =>+ [...host!.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].find(+ (input) => input.labels?.[0]?.textContent === switchLabel+ );+ stableGroups.models.catalog = [MODEL, ANIMA, ANIMA_INPAINT_ADAPTER];+ await renderAdapter(buildAdapter());+ await settle(() =>+ storedValues().patchSnapshot({+ ...getDefaultGenerateSettings(ANIMA as never),+ animaInpaintAdapterModel: ANIMA_INPAINT_ADAPTER as never,+ animaInpaintAdapterWeight: 0.6,+ modelKey: ANIMA.key,+ })+ );++ expect(adapterSwitch()?.checked).toBe(true);+ expect(host!.textContent).not.toContain(offHelp);+ expect(sliderNamed(weightLabel).getAttribute('aria-disabled')).toBeNull();++ await userEvent.click(adapterSwitch()!.labels![0]!);+ await settle(flushGenerateDrafts);++ expect(storedValues().getSnapshot()).toMatchObject({+ animaInpaintAdapterEnabled: false,+ animaInpaintAdapterModel: ANIMA_INPAINT_ADAPTER,+ animaInpaintAdapterWeight: 0.6,+ });+ expect(adapterSwitch()?.checked).toBe(false);+ expect(host!.textContent).toContain(offHelp);+ expect(adapterSlot()?.getAttribute('data-component-value')).toBe(ANIMA_INPAINT_ADAPTER.key);+ expect(sliderNamed(weightLabel).getAttribute('aria-disabled')).toBe('true');++ await userEvent.click(adapterSwitch()!.labels![0]!);+ await settle(flushGenerateDrafts);++ expect(storedValues().getSnapshot()).toMatchObject({+ animaInpaintAdapterEnabled: true,+ animaInpaintAdapterModel: ANIMA_INPAINT_ADAPTER,+ animaInpaintAdapterWeight: 0.6,+ });+ expect(sliderNamed(weightLabel).getAttribute('aria-disabled')).toBeNull();+ });});describe('GenerateSettingsForm Z-Image Qwen3 encoder', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsxindex ca09c26ed3..f0dedf594e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.browser.test.tsx@@ -1,5 +1,9 @@import { ChakraProvider } from '@chakra-ui/react';import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';+import {+ findHalfPixelWrapEdge,+ type HalfPixelWrapSide,+} from '@features/generation/ui/promptFields/textareaWrapWidth.testing';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -9,19 +13,26 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const render = async (value: string, widthPx = 320) => {- host = document.createElement('div');+const render = async (+ value: string,+ widthPx = 320,+ { fontSize, heightPx = 200 }: { fontSize?: string; heightPx?: number } = {}+) => {+ if (!host) {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ }host.style.width = `${widthPx}px`;- document.body.append(host);- root = createRoot(host);await act(() => {root?.render(<ChakraProvider value={system}><PromptTextareaaria-label="Values"- defaultHeightPx={200}- minHeightPx={96}+ defaultHeightPx={heightPx}+ fontSize={fontSize}+ minHeightPx={Math.min(96, heightPx)}readOnlyresizeHandleAriaLabel="Resize"showLineNumbers@@ -33,6 +44,7 @@ const render = async (value: string, widthPx = 320) => {});// The gutter sizes itself from a measured mirror, so let layout settle.await act(async () => {+ await document.fonts.ready;await new Promise((resolve) => {requestAnimationFrame(() => requestAnimationFrame(resolve));});@@ -85,4 +97,40 @@ describe('prompt line numbers', () => {expect(heights[1]).toBeGreaterThan(heights[0] * 2);expect(heights[2]).toBeCloseTo(heights[0], 1);});++ it.each([+ ['wraps', 2],+ ['fits', 1],+ ] as const satisfies ReadonlyArray<readonly [HalfPixelWrapSide, number]>)(+ 'sizes a line the way the textarea wraps it at a half-pixel width, when its last word %s',+ async (side, lines) => {+ const words = 'masterpiece portrait of a lighthouse keeper at dusk with soft rim light and heavy fog'.split(' ');+ // A fractional font size spreads word ends across sub-pixel widths; a short box lets scrollHeight count lines.+ const options = { fontSize: '13.3px', heightPx: 20 };+ const px = (value: string) => Number.parseFloat(value);+ const paddingBoxWidth = (textarea: HTMLTextAreaElement) =>+ textarea.getBoundingClientRect().width - px(getComputedStyle(textarea).borderLeftWidth) * 2;++ await render(words.join(' '), 600, options);+ const textarea = host!.querySelector('textarea')!;+ const edge = findHalfPixelWrapEdge(textarea, words, side);+ await render(+ edge.text,+ edge.paddingBoxWidth + host!.getBoundingClientRect().width - paddingBoxWidth(textarea),+ options+ );++ const computed = getComputedStyle(textarea);+ const lineHeight = px(computed.lineHeight);+ const textareaLines = Math.round(+ (textarea.scrollHeight - px(computed.paddingTop) - px(computed.paddingBottom)) / lineHeight+ );++ expect(paddingBoxWidth(textarea)).toBeCloseTo(edge.paddingBoxWidth, 2);+ expect(textareaLines).toBe(lines);+ expect(gutterEntries().map((entry) => Math.round(entry.getBoundingClientRect().height / lineHeight))).toEqual([+ lines,+ ]);+ }+ );});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsxindex 5d39c13c6f..49981770d8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptLineNumbers.tsx@@ -14,11 +14,11 @@ export interface PromptLineNumbersMetrics {fontFamily: BoxProps['fontFamily'];fontSize: BoxProps['fontSize'];lineHeight: BoxProps['lineHeight'];- /** The textarea's border-box width, so the mirror wraps identically. */- clientWidth: number | null;paddingInline: string;paddingBlock: string;scrollTop: number;+ /** The textarea's unrounded wrap width (`getTextareaWrapWidth`), so the mirror wraps identically. */+ wrapWidth: number | null;}/** Width the textarea must reserve on its leading edge for `lineCount` numbers. */@@ -54,7 +54,7 @@ export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumberesizeObserver.observe(mirror);return () => resizeObserver.disconnect();- }, [lines, metrics.clientWidth, metrics.fontSize, metrics.lineHeight]);+ }, [lines, metrics.wrapWidth, metrics.fontSize, metrics.lineHeight]);const sharedTextStyles = {fontFamily: metrics.fontFamily,@@ -74,7 +74,7 @@ export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbepaddingBlock={metrics.paddingBlock}paddingInline={metrics.paddingInline}paddingInlineStart={`calc(${metrics.paddingInline} + ${gutterWidth})`}- w={metrics.clientWidth ? `${metrics.clientWidth}px` : '100%'}+ w={metrics.wrapWidth ? `${metrics.wrapWidth}px` : '100%'}{...sharedTextStyles}>{lines.map((line, index) => (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.browser.test.tsxnew file mode 100644index 0000000000..63262f84cd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.browser.test.tsx@@ -0,0 +1,144 @@+import { ChakraProvider } from '@chakra-ui/react';+import { getTextareaCaretRect } from '@features/generation/ui/promptFields/promptCaret';+import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';+import {+ findHalfPixelWrapEdge,+ type HalfPixelWrapSide,+} from '@features/generation/ui/promptFields/textareaWrapWidth.testing';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';++/**+ * The highlight mirror and the autocomplete caret must wrap exactly where the textarea does. `clientWidth` rounds to+ * whole pixels, so at a padding-box width ending in .5 a mirror sized from it wraps a word the textarea keeps, or the+ * reverse, and the caret lands a word and a line away from its glyph.+ */++const WORDS = 'masterpiece portrait of a lighthouse keeper at dusk with soft rim light and heavy fog'.split(' ');+// A fractional size gives the monospace advance a fraction, so word prefixes end at varied sub-pixel widths.+const FONT_SIZE = '13.3px';+const noop = () => undefined;++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const settleLayout = () =>+ act(async () => {+ await document.fonts.ready;+ await new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ });+ });++const render = async (value: string, widthPx: number) => {+ if (!host) {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ }+ host.style.width = `${widthPx}px`;++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ {/* A short box makes the text overflow, so scrollHeight counts the textarea's own lines. */}+ <PromptTextarea+ aria-label="Prompt"+ defaultHeightPx={20}+ fontSize={FONT_SIZE}+ minHeightPx={20}+ resizeHandleAriaLabel="Resize"+ showSyntaxHighlighting+ value={value}+ onChange={noop}+ />+ </ChakraProvider>+ );+ });+ await settleLayout();+};++const textarea = () => host!.querySelector('textarea')!;+const mirror = () => host!.querySelector('pre')!;++const px = (value: string) => Number.parseFloat(value);+const lineHeightPx = () => px(getComputedStyle(textarea()).lineHeight);+const linesIn = (contentHeight: number) => Math.round(contentHeight / lineHeightPx());++const textareaLines = () => {+ const computed = getComputedStyle(textarea());++ return linesIn(textarea().scrollHeight - px(computed.paddingTop) - px(computed.paddingBottom));+};++const mirrorLines = () => {+ const computed = getComputedStyle(mirror());++ return linesIn(mirror().getBoundingClientRect().height - px(computed.paddingTop) - px(computed.paddingBottom));+};++/** The textarea's padding box, from its fractional border box. */+const paddingBoxWidth = () => {+ const computed = getComputedStyle(textarea());++ return textarea().getBoundingClientRect().width - px(computed.borderLeftWidth) - px(computed.borderRightWidth);+};++/** Renders the prefix of WORDS whose wrap edge sits half a pixel from a .5 padding-box width, at that width. */+const renderAtHalfPixelEdge = async (side: HalfPixelWrapSide) => {+ await render(WORDS.join(' '), 600);+ const edge = findHalfPixelWrapEdge(textarea(), WORDS, side);+ const hostOverhead = host!.getBoundingClientRect().width - paddingBoxWidth();++ await render(edge.text, edge.paddingBoxWidth + hostOverhead);+ expect(paddingBoxWidth()).toBeCloseTo(edge.paddingBoxWidth, 2);++ return edge;+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('prompt mirrors at a fractional width', () => {+ it('sizes the highlight mirror to the textarea wrap box, not its rounded clientWidth', async () => {+ await render('a lighthouse', 368.5);++ expect(paddingBoxWidth() % 1).toBeCloseTo(0.5, 2);+ expect(mirror().getBoundingClientRect().width).toBeCloseTo(paddingBoxWidth(), 2);+ });++ it.each([+ ['wraps', 2],+ ['fits', 1],+ ] as const)('wraps the highlight mirror like the textarea when the last word %s', async (side, lines) => {+ await renderAtHalfPixelEdge(side);++ expect(textareaLines()).toBe(lines);+ expect(mirrorLines()).toBe(lines);+ });++ it.each([+ ['wraps', 1],+ ['fits', 0],+ ] as const)('puts the caret on the line the textarea wraps to when the last word %s', async (side, line) => {+ const edge = await renderAtHalfPixelEdge(side);+ const computed = getComputedStyle(textarea());+ const contentTop =+ textarea().getBoundingClientRect().top ++ px(computed.borderTopWidth) ++ px(computed.paddingTop) -+ textarea().scrollTop;+ const caret = getTextareaCaretRect(textarea(), edge.edgeWordIndex);++ expect(textareaLines()).toBe(line + 1);+ expect(caret).not.toBeNull();+ expect(Math.round((caret!.y - contentTop) / lineHeightPx())).toBe(line);+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsxindex bba963e2f9..ef1b339075 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTextarea.tsx@@ -3,12 +3,15 @@ import type { Ref, UIEvent } from 'react';import { Box } from '@chakra-ui/react';import { PROMPT_ATTENTION_TARGET_PROPS } from '@features/generation/ui/promptFields/promptAttentionHotkeys';+import { getTextareaWrapWidth } from '@features/generation/ui/promptFields/promptCaret';import { HighlightedPrompt, MAX_HIGHLIGHTED_PROMPT_LENGTH } from '@features/generation/ui/promptFields/PromptHighlight';import { getLineNumberGutterCh, PromptLineNumbers } from '@features/generation/ui/promptFields/PromptLineNumbers';import { ResizableTextarea } from '@platform/ui';import { PROMPT_FONT_SIZE } from '@theme/scale';import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';+/** Layout moves in 1/64 px steps; a smaller difference in the parsed width is not a resize. */+const WRAP_WIDTH_EPSILON_PX = 0.01;// Use literal lengths; fractional Chakra spacing variables fail inside calc.const PROMPT_TEXTAREA_PX = '0.625rem';const PROMPT_TEXTAREA_PY = '0.5rem';@@ -75,7 +78,7 @@ export const PromptTextarea = ({}: PromptTextareaProps) => {const localTextareaRef = useRef<HTMLTextAreaElement | null>(null);const [scroll, setScroll] = useState({ left: 0, top: 0 });- const [textareaClientWidth, setTextareaClientWidth] = useState<number | null>(null);+ const [textareaWrapWidth, setTextareaWrapWidth] = useState<number | null>(null);const isWithinHighlightBudget = value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;const highlightsSyntax = showSyntaxHighlighting && (attentionSyntax !== 'none' || highlightDynamicPrompts);// Template chunk emphasis is independent of the syntax-highlighting preference.@@ -99,20 +102,25 @@ export const PromptTextarea = ({}const textarea = localTextareaRef.current;- const syncClientWidth = () => {- const nextWidth = textarea.clientWidth;+ // Live: it reflects later layout, so one lookup serves every measurement of this run.+ const computed = window.getComputedStyle(textarea);+ // Re-run on value: typing can add or remove a vertical scrollbar, which narrows the wrap box.+ const syncWrapWidth = () => {+ const nextWidth = getTextareaWrapWidth(textarea, computed);- setTextareaClientWidth((currentWidth) => (currentWidth === nextWidth ? currentWidth : nextWidth));+ setTextareaWrapWidth((currentWidth) =>+ currentWidth !== null && Math.abs(currentWidth - nextWidth) < WRAP_WIDTH_EPSILON_PX ? currentWidth : nextWidth+ );};- const resizeObserver = new ResizeObserver(syncClientWidth);+ const resizeObserver = new ResizeObserver(syncWrapWidth);- syncClientWidth();+ syncWrapWidth();resizeObserver.observe(textarea);- window.addEventListener('resize', syncClientWidth);+ window.addEventListener('resize', syncWrapWidth);return () => {resizeObserver.disconnect();- window.removeEventListener('resize', syncClientWidth);+ window.removeEventListener('resize', syncWrapWidth);};}, [needsMirror, value]);@@ -134,15 +142,15 @@ export const PromptTextarea = ({const lineNumberMetrics = useMemo(() => ({- clientWidth: textareaClientWidth,fontFamily,fontSize: effectiveFontSize,lineHeight: effectiveLineHeight,paddingBlock: PROMPT_TEXTAREA_PY,paddingInline: PROMPT_TEXTAREA_PX,scrollTop: scroll.top,+ wrapWidth: textareaWrapWidth,}),- [effectiveFontSize, effectiveLineHeight, fontFamily, scroll.top, textareaClientWidth]+ [effectiveFontSize, effectiveLineHeight, fontFamily, scroll.top, textareaWrapWidth]);const highlightUnderlay = useMemo(@@ -174,7 +182,7 @@ export const PromptTextarea = ({paddingInlineStart={paddingInlineStart}transform={`translate(${-scroll.left}px, ${-scroll.top}px)`}whiteSpace="pre-wrap"- w={textareaClientWidth ? `${textareaClientWidth}px` : '100%'}+ w={textareaWrapWidth ? `${textareaWrapWidth}px` : '100%'}>{templateChunks ? (<>@@ -208,7 +216,7 @@ export const PromptTextarea = ({scroll.top,shouldHighlight,templateChunks,- textareaClientWidth,+ textareaWrapWidth,value,]);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.tsindex 404a27a25f..935a63cbb0 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptCaret.ts@@ -5,6 +5,35 @@ export interface CaretRect {y: number;}+/**+ * The width a textarea wraps its text in: its padding box minus any vertical scrollbar, which is what `clientWidth`+ * reports, but without `clientWidth`'s rounding to whole pixels. At a fractional layout width a mirror sized from the+ * rounded value is up to half a pixel wider than the textarea and can keep a word on a line the textarea wraps.+ *+ * Pass the textarea's live computed style when measuring repeatedly, so it is looked up once.+ */+export const getTextareaWrapWidth = (+ textarea: HTMLTextAreaElement,+ computed: CSSStyleDeclaration = window.getComputedStyle(textarea)+): number => {+ const width = Number.parseFloat(computed.width);++ if (!Number.isFinite(width)) {+ return textarea.clientWidth;+ }++ const borderInline =+ (Number.parseFloat(computed.borderLeftWidth) || 0) + (Number.parseFloat(computed.borderRightWidth) || 0);+ const paddingBoxWidth =+ computed.boxSizing === 'border-box'+ ? width - borderInline+ : width + (Number.parseFloat(computed.paddingLeft) || 0) + (Number.parseFloat(computed.paddingRight) || 0);+ // A scrollbar takes whole pixels, so the rounded box sizes measure it exactly; overlay scrollbars measure 0.+ const scrollbar = Math.max(0, Math.round(textarea.offsetWidth - textarea.clientWidth - borderInline));++ return paddingBoxWidth - scrollbar;+};+const MIRRORED_STYLES = ['direction','fontFamily',@@ -66,7 +95,7 @@ export const getTextareaCaretRect = (textarea: HTMLTextAreaElement, index: numbemirror.style.overflow = 'hidden';mirror.style.boxSizing = 'border-box';mirror.style.border = '0';- mirror.style.width = `${textarea.clientWidth}px`;+ mirror.style.width = `${getTextareaWrapWidth(textarea, computed)}px`;mirror.textContent = textarea.value.slice(0, index);marker.textContent = textarea.value.slice(index) || '';diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/textareaWrapWidth.testing.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/textareaWrapWidth.testing.tsnew file mode 100644index 0000000000..776415b2c0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/textareaWrapWidth.testing.ts@@ -0,0 +1,72 @@+/**+ * Geometry for the fractional-width mirror tests: a word-prefix of `words` whose one-line width falls inside half a+ * pixel of a textarea padding-box width ending in .5. A mirror sized from the rounded `clientWidth` lands on the other+ * side of that edge in one of the two cases, whichever way the browser rounds.+ */+export type HalfPixelWrapSide = 'fits' | 'wraps';++export interface HalfPixelWrapEdge {+ /** Index in `text` of the word that sits on the wrap edge. */+ edgeWordIndex: number;+ /** The textarea's padding-box width to lay out at: whole pixels plus a half. */+ paddingBoxWidth: number;+ text: string;+}++// Chrome resolves the `font` shorthand to an empty string, so copy the longhands.+const TEXT_STYLES = [+ 'fontFamily',+ 'fontFeatureSettings',+ 'fontKerning',+ 'fontSize',+ 'fontStretch',+ 'fontStyle',+ 'fontVariant',+ 'fontWeight',+ 'letterSpacing',+ 'wordSpacing',+] as const;++const measureTextWidth = (computed: CSSStyleDeclaration, text: string): number => {+ const span = document.createElement('span');++ for (const property of TEXT_STYLES) {+ span.style[property] = computed[property];+ }+ span.style.position = 'absolute';+ span.style.whiteSpace = 'pre';+ span.textContent = text;+ document.body.append(span);+ const { width } = span.getBoundingClientRect();+ span.remove();++ return width;+};++export const findHalfPixelWrapEdge = (+ textarea: HTMLTextAreaElement,+ words: readonly string[],+ side: HalfPixelWrapSide+): HalfPixelWrapEdge => {+ const computed = window.getComputedStyle(textarea);+ const paddingInline = Number.parseFloat(computed.paddingLeft) + Number.parseFloat(computed.paddingRight);++ for (let count = 2; count <= words.length; count += 1) {+ const text = words.slice(0, count).join(' ');+ // The narrowest padding box that holds `text` on one line.+ const threshold = measureTextWidth(computed, text) + paddingInline;+ const fraction = threshold - Math.floor(threshold);+ // Stay clear of the edge itself so layout's 1/64 px steps cannot decide the case.+ const isUsable = side === 'wraps' ? fraction >= 0.6 && fraction <= 0.9 : fraction >= 0.1 && fraction <= 0.4;++ if (isUsable) {+ return {+ edgeWordIndex: text.length - words[count - 1]!.length,+ paddingBoxWidth: Math.floor(threshold) + 0.5,+ text,+ };+ }+ }++ throw new Error(`no prefix of the words puts the wrap edge on the ${side} side of a half pixel`);+};diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.test.tsindex 4af5160ae2..065328c588 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {isAbsoluteModelPath,+ canonicalLocalPath,isInModelsDir,mainDefaultSettingsSchema,modelPathSchema,@@ -91,6 +92,19 @@ describe('mainDefaultSettingsSchema', () => {});});+describe('canonicalLocalPath', () => {+ it.each([+ ['C:\\Users\\Me\\x.safetensors', 'c:/users/me/x.safetensors'],+ [' C:/Users/Me/loras/ ', 'c:/users/me/loras'],+ ['C:\\', 'c:'],+ ['\\\\NAS\\Models\\', '//nas/models'],+ ['/home/Me/Models//', '/home/Me/Models'],+ ['loras/X.safetensors', 'loras/X.safetensors'],+ ])('spells %j as %j', (path, canonical) => {+ expect(canonicalLocalPath(path)).toBe(canonical);+ });+});+describe('isInModelsDir', () => {it.each([['/data/models', '/data/models'],diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.tsindex 1de52f932b..ba1dc67040 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.ts@@ -92,7 +92,16 @@ export const isAbsoluteModelPath = (path: string): boolean =>export const resolveModelAbsolutePath = (path: string, modelsDir: string | null): string =>isAbsoluteModelPath(path) || !modelsDir ? path : `${modelsDir.replace(/\/+$/, '')}/${path}`;-const comparablePath = (path: string): string => path.trim().replaceAll('\\', '/').replace(/\/+$/, '');+/**+ * One spelling per local path, for comparing paths the server reports in different forms: scan rows carry OS-native+ * separators while install records store forward slashes. Trims, turns `\` into `/`, drops trailing slashes, and+ * case-folds Windows drive and UNC paths only, since POSIX file systems are case-sensitive.+ */+export const canonicalLocalPath = (path: string): string => {+ const canonical = path.trim().replaceAll('\\', '/').replace(/\/+$/, '');++ return /^([A-Za-z]:(\/|$)|\/\/)/.test(canonical) ? canonical.toLowerCase() : canonical;+};/*** Whether `path` is the models directory or inside it. The comparison is textual — the server reports the directory@@ -104,18 +113,13 @@ export const isInModelsDir = (path: string, modelsDir: string | null): boolean =return false;}- let dir = comparablePath(modelsDir);- let candidate = comparablePath(path);+ const dir = canonicalLocalPath(modelsDir);+ const candidate = canonicalLocalPath(path);if (/(^|\/)\.\.(\/|$)/.test(candidate)) {return false;}- if (/^([A-Za-z]:\/|\/\/)/.test(dir)) {- dir = dir.toLowerCase();- candidate = candidate.toLowerCase();- }-return dir !== '' && (candidate === dir || candidate.startsWith(`${dir}/`));};diff --git a/invokeai/frontend/webv2/src/features/models/core/starters.test.ts b/invokeai/frontend/webv2/src/features/models/core/starters.test.tsindex 6b0c7384fb..ad1811956e 100644--- a/invokeai/frontend/webv2/src/features/models/core/starters.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/starters.test.ts@@ -21,8 +21,21 @@ const catalog: StarterModel[] = [];describe('filterStarterModels', () => {- it('keeps catalog order under the default sort', () => {- expect(filterStarterModels(catalog, DEFAULT_STARTER_MODEL_FILTERS, '').map((m) => m.name)).toEqual([+ it('sorts by name, ignoring case, unless the user picks another order', () => {+ const mixedCase = [...catalog, createStarter({ name: 'bright LoRA', type: 'lora' })];++ expect(filterStarterModels(mixedCase, DEFAULT_STARTER_MODEL_FILTERS, '').map((m) => m.name)).toEqual([+ 'Alpha FLUX',+ 'bright LoRA',+ 'Detail Tweaker',+ 'Juggernaut XL',+ ]);+ });++ it('keeps catalog order under the catalog sort', () => {+ const catalogOrder = { ...DEFAULT_STARTER_MODEL_FILTERS, sortField: 'default' as const };++ expect(filterStarterModels(catalog, catalogOrder, '').map((m) => m.name)).toEqual(['Juggernaut XL','Alpha FLUX','Detail Tweaker',diff --git a/invokeai/frontend/webv2/src/features/models/core/starters.ts b/invokeai/frontend/webv2/src/features/models/core/starters.tsindex 847ae7a191..ff866b328c 100644--- a/invokeai/frontend/webv2/src/features/models/core/starters.ts+++ b/invokeai/frontend/webv2/src/features/models/core/starters.ts@@ -22,7 +22,7 @@ export interface StarterModelFilters {export const DEFAULT_STARTER_MODEL_FILTERS: StarterModelFilters = {baseFilter: null,sortDirection: 'asc',- sortField: 'default',+ sortField: 'name',typeFilter: null,};@@ -44,7 +44,7 @@ const compareStarterModels = (a: IndexedStarterModel, b: IndexedStarterModel, fi}};-/** Filter by taxonomy + free-text terms, then sort; 'default' keeps catalog order. */+/** Filter by taxonomy + free-text terms, then sort; 'default' keeps catalog order (labelled "Catalog order"). */export const filterStarterModels = (models: readonly StarterModel[],filters: StarterModelFilters,diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.tsindex 8c6a45199e..c12654fe19 100644--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.test.ts@@ -7,6 +7,7 @@ import {getModelTypeLabel,getModelVariantLabel,getVariantOptionsFor,+ getUnrecordedModelFact,} from './taxonomy';describe('label fallbacks', () => {@@ -89,3 +90,23 @@ describe('getModelSourceHref', () => {expect(getModelSourceHref('some-name', 'unknown')).toBeNull();});});++describe('getUnrecordedModelFact', () => {+ const fact = (model: Partial<Parameters<typeof getUnrecordedModelFact>[0]>) =>+ getUnrecordedModelFact({ base: 'any', type: 'main', ...model } as Parameters<typeof getUnrecordedModelFact>[0]);++ it('flags Anima ControlNets whose adapter channels were never recorded', () => {+ expect(fact({ base: 'anima', cond_in_channels: null, type: 'controlnet' })).toBe('adapter_type');+ expect(fact({ base: 'anima', type: 'controlnet' })).toBe('adapter_type');+ expect(fact({ base: 'anima', cond_in_channels: 3, type: 'controlnet' })).toBeNull();+ expect(fact({ base: 'anima', cond_in_channels: 4, type: 'controlnet' })).toBeNull();+ expect(fact({ base: 'sdxl', cond_in_channels: null, type: 'controlnet' })).toBeNull();+ });++ it('flags upscalers whose native scale was never recorded', () => {+ expect(fact({ scale: null, type: 'spandrel_image_to_image' })).toBe('native_scale');+ expect(fact({ type: 'spandrel_image_to_image' })).toBe('native_scale');+ expect(fact({ scale: 1, type: 'spandrel_image_to_image' })).toBeNull();+ expect(fact({ scale: null, type: 'main' })).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts b/invokeai/frontend/webv2/src/features/models/core/taxonomy.tsindex 313d5ce36c..aa090732cb 100644--- a/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts+++ b/invokeai/frontend/webv2/src/features/models/core/taxonomy.ts@@ -1,4 +1,4 @@-import type { ModelFileFormat, ModelTaxonomyType } from './types';+import type { ModelConfig, ModelFileFormat, ModelTaxonomyType } from './types';import { toTitleCase } from './baseIdentity';@@ -202,3 +202,25 @@ export const getVariantOptionsFor = (base: string, type: string): readonly strinreturn VARIANTS_BY_TYPE[type] ?? [];};++/** A fact the probe records that this model's record predates; re-identifying fills it in. */+export type UnrecordedModelFact = 'adapter_type' | 'native_scale';++/**+ * What re-identifying would record for a model installed before the probe recorded it, or null. No migration fills+ * these fields.+ * - `adapter_type`: an Anima ControlNet-LLLite without `cond_in_channels`. Control layers cannot tell a control+ * adapter from an inpaint one, so it stays unusable there.+ * - `native_scale`: a Spandrel upscaler without `scale`. Upscale cannot show how it will run it.+ */+export const getUnrecordedModelFact = (+ model: Pick<ModelConfig, 'base' | 'cond_in_channels' | 'scale' | 'type'>+): UnrecordedModelFact | null => {+ if (model.type === 'controlnet' && model.base === 'anima' && (model.cond_in_channels ?? null) === null) {+ return 'adapter_type';+ }+ if (model.type === 'spandrel_image_to_image' && (model.scale ?? null) === null) {+ return 'native_scale';+ }+ return null;+};diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex de39d5ea2d..a7f3100098 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -152,6 +152,8 @@ export interface ModelConfig {image_encoder_model_id?: string;/** Anima ControlNet-LLLite: 3 = control image, 4 = inpainting; null when installed before it was recorded. */cond_in_channels?: number | null;+ /** Spandrel upscalers: native scale (1 = same size); null when installed before it was recorded. */+ scale?: number | null;/** External API models. */provider_id?: string;provider_model_id?: string;diff --git a/invokeai/frontend/webv2/src/features/models/index.ts b/invokeai/frontend/webv2/src/features/models/index.tsindex c0f818e38c..21cddf0c7b 100644--- a/invokeai/frontend/webv2/src/features/models/index.ts+++ b/invokeai/frontend/webv2/src/features/models/index.ts@@ -32,7 +32,12 @@ export { ModelInstallRuntime } from './ui/ModelInstallRuntime';export { ModelsPage } from './ui/ModelsPage';export {ModelsUiProvider,+ useModelsUi,useOpenAddModelsSearch,useOpenModelInManager,+ type ModelSchedulerPolicy,type ModelsUiAdapter,+ type SchedulerPolicyReader,+ type SchedulerPolicySource,+ type SchedulerPolicyState,} from './ui/ModelsUiContext';diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsxindex 2a00c4593c..d5e72e88dc 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.test.tsx@@ -2,7 +2,12 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';import { renderToStaticMarkup } from 'react-dom/server';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { ModelsUiProvider, useOpenAddModelsSearch, useOpenModelInManager } from './ModelsUiContext';+import {+ ModelsUiProvider,+ NO_SCHEDULER_POLICY,+ useOpenAddModelsSearch,+ useOpenModelInManager,+} from './ModelsUiContext';import { getModelsUiSnapshotForTests } from './uiStore';const { navigate, router } = vi.hoisted(() => ({@@ -16,8 +21,11 @@ let activeProjectId = 'project-a';const adapter = {canManageModels: true,enableModelDescriptions: true,+ installInPlace: true,isProjectActive: (projectId: string) => activeProjectId === projectId,managerProjectId: 'project-a',+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace: () => undefined,};const captureActions = () => {@@ -66,7 +74,7 @@ describe('deferred Model Manager navigation', () => {expect(getModelsUiSnapshotForTests()).toMatchObject(action === 'details'? { activeModelKey: 'model-a', activeTab: 'details' }- : { addModelsSeed: 'encoder-a', activeTab: 'add' }+ : { activeTab: 'add', addModelsQuery: 'encoder-a' });});@@ -85,6 +93,6 @@ describe('deferred Model Manager navigation', () => {await vi.dynamicImportSettled();expect(navigate).not.toHaveBeenCalled();- expect(getModelsUiSnapshotForTests()).toMatchObject({ activeModelKey: null, addModelsSeed: null });+ expect(getModelsUiSnapshotForTests()).toMatchObject({ activeModelKey: null, addModelsQuery: '' });});});diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsxindex b6b1ed7cc4..d374a7cb58 100644--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx@@ -1,23 +1,76 @@+import type { ModelConfig } from '@features/models/core/types';import type { ReactNode } from 'react';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { useNavigate, useRouter } from '@tanstack/react-router';import { createContext, use, useCallback } from 'react';-/** This UI port preserves dependency direction: Models cannot import Workbench. */+export interface SchedulerChoice {+ label: string;+ value: string;+}++/** Generate's scheduler rules for one main model, so its defaults offer exactly what Generate runs. */+export interface ModelSchedulerPolicy {+ /** False where the base's graph ignores the scheduler; Generate hides the control there. */+ appliesToGraph: boolean;+ /** The scheduler Generate starts this base on. */+ defaultValue: string;+ /** Generate's choices for the base, led by `currentValue` when it is outside them. */+ options: readonly SchedulerChoice[];+}++/** The main model's architecture; Generate's scheduler rules key on these alone. */+export type SchedulerPolicyModel = Pick<ModelConfig, 'base' | 'format' | 'variant'>;++export type SchedulerPolicyReader = (model: SchedulerPolicyModel, currentValue: string | null) => ModelSchedulerPolicy;++/**+ * Generate's scheduler rules: `loading` until the rules and the architecture table they read arrive, `unavailable`+ * when either failed, and `ready` with a reader that is replaced whenever the table changes.+ */+export type SchedulerPolicyState =+ | { status: 'loading' }+ | { status: 'unavailable' }+ | { read: SchedulerPolicyReader; status: 'ready' };++/** Generate's scheduler rules, loaded on first use so the Model Manager carries no Generation code at startup. */+export interface SchedulerPolicySource {+ getSnapshot: () => SchedulerPolicyState;+ /** Starts loading the rules and the table, or retries after a failure; joins a load already running. */+ load: () => void;+ subscribe: (listener: () => void) => () => void;+}++const SCHEDULER_POLICY_UNAVAILABLE: SchedulerPolicyState = { status: 'unavailable' };+/** For surfaces composed without Generation, such as isolated tests: the rules never arrive. */+export const NO_SCHEDULER_POLICY: SchedulerPolicySource = {+ getSnapshot: () => SCHEDULER_POLICY_UNAVAILABLE,+ load: () => undefined,+ subscribe: () => () => undefined,+};++/** This UI port preserves dependency direction: Models cannot import Workbench or Generation. */export interface ModelsUiAdapter {/** Whether this session may open the Model Manager; its route redirects everyone else away. */canManageModels: boolean;enableModelDescriptions: boolean;+ /** Add Models' "Install in place" choice, an account preference. */+ installInPlace: boolean;isProjectActive: (projectId: string) => boolean;managerProjectId: string | null;+ schedulerPolicy: SchedulerPolicySource;+ setInstallInPlace: (installInPlace: boolean) => void;}const DEFAULT_MODELS_UI_ADAPTER: ModelsUiAdapter = {canManageModels: false,enableModelDescriptions: true,+ installInPlace: true,isProjectActive: () => false,managerProjectId: null,+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace: () => undefined,};const ModelsUiContext = createContext<ModelsUiAdapter>(DEFAULT_MODELS_UI_ADAPTER);diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsxindex 11f81705c6..444f54037a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx@@ -1,12 +1,15 @@import type { FoundModel, ModelConfig } from '@features/models/core/types';+import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { getModelsDir, listMissingModels, listModels, scanFolderForModels } from '@features/models/data/api';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { getModelsUiSnapshotForTests, updateModelsUi } from '@features/models/ui/uiStore';+import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';+import { getModelsUiSnapshotForTests, setAddModelsQuery, updateModelsUi } from '@features/models/ui/uiStore';+import { createExternalStore } from '@platform/state/externalStore';import { ApiError } from '@platform/transport/http';import { system } from '@theme/system';-import { act, StrictMode } from 'react';+import { act, StrictMode, useMemo } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';@@ -14,8 +17,8 @@ import { userEvent } from 'vitest/browser';import { AddModelsView } from './AddModelsView';/**- * Verify one-shot external search handover into local input state; the seed must not become account-lived- * filtering.+ * The search box lives in the Model Manager's session store; "Install in place" is an account preference, stood in for+ * here by a store that outlives each mount as the account settings do.*/vi.mock('react-i18next', () => ({@@ -83,7 +86,33 @@ vi.mock('@features/models/ui/useModelsNotify', () => ({ useNotify: () => notify(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-describe('AddModelsView search seed', () => {+const accountPreferences = createExternalStore({ installInPlace: true });+const setInstallInPlace = (installInPlace: boolean) => accountPreferences.setSnapshot({ installInPlace });++const WithAccountPreferences = ({ children }: { children: ReactNode }) => {+ const { installInPlace } = accountPreferences.useSnapshot();+ const adapter = useMemo<ModelsUiAdapter>(+ () => ({+ canManageModels: true,+ enableModelDescriptions: true,+ installInPlace,+ isProjectActive: () => true,+ managerProjectId: null,+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace,+ }),+ [installInPlace]+ );++ return <ModelsUiProvider adapter={adapter}>{children}</ModelsUiProvider>;+};++const resetSessionAndPreferences = () => {+ setAddModelsQuery('');+ setInstallInPlace(true);+};++describe('AddModelsView search box', () => {let host: HTMLDivElement;let root: Root;@@ -96,7 +125,9 @@ describe('AddModelsView search seed', () => {root.render(<StrictMode><ChakraProvider value={system}>- <AddModelsView />+ <WithAccountPreferences>+ <AddModelsView />+ </WithAccountPreferences></ChakraProvider></StrictMode>);@@ -112,34 +143,49 @@ describe('AddModelsView search seed', () => {await act(() => root.unmount());};- beforeEach(async () => {+ beforeEach(() => {host = document.createElement('div');document.body.append(host);- const store = await import('@features/models/ui/uiStore');- store.clearAddModelsSeeds();+ resetSessionAndPreferences();});afterEach(() => {host.remove();+ resetSessionAndPreferences();});- it('opens searching for a seeded model, then forgets it on the next open', async () => {+ it('opens searching for a requested model, replacing what the box held', async () => {const { requestAddModelsSearch } = await import('@features/models/ui/uiStore');+ setAddModelsQuery('something typed earlier');requestAddModelsSearch('Wan 2.2 I2V A14B');await mount();- // StrictMode double-invokes the `useState` initializer, so the read has to- // survive being run twice — this is the case that catches a take-and-clear- // initializer.expect(searchBox()?.value).toBe('Wan 2.2 I2V A14B');await unmount();+ });++ it('keeps the typed text and the Install in place choice when the view is reopened', async () => {await mount();+ const outside = '/home/user/downloads/outside.safetensors';+ const inplaceInput = () =>+ [...document.querySelectorAll('label')]+ .find((label) => label.textContent === 'models.installInPlace')+ ?.querySelector('input');- // Unmount resets local search; consumed seeds must not reappear on later visits.- expect(searchBox()?.value).toBe('');+ await act(() => userEvent.fill(searchBox()!, outside));+ expect(inplaceInput()?.checked).toBe(true);+ await act(() => userEvent.click(inplaceInput()!.closest('label')!));+ expect(inplaceInput()?.checked).toBe(false);++ // Switching tabs or closing the manager unmounts the view.+ await unmount();+ await mount();++ expect(searchBox()?.value).toBe(outside);+ expect(inplaceInput()?.checked).toBe(false);await unmount();});@@ -227,6 +273,36 @@ describe('AddModelsView search seed', () => {await unmount();});+ it('offers the starter sorts it implements, with the catalog order named for what it is', async () => {+ await mount();++ await act(() =>+ userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.filterAndSortStarterModels"]')!)+ );+ const sortBy = await vi.waitFor(() => {+ const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((element) =>+ element.textContent?.startsWith('models.sortBy')+ );+ expect(item).toBeDefined();+ return item!;+ });+ // The summary names the default sort.+ expect(sortBy.textContent).toContain('models.sort.name');+ await act(() => userEvent.click(sortBy));++ await expect+ .poll(() =>+ [...document.querySelectorAll('[role="menuitemradio"], [role="menuitemcheckbox"]')]+ .map((item) => item.textContent ?? '')+ .filter((text) => text.startsWith('models.sort.'))+ // The selected sort also shows its direction.+ .map((text) => text.replace(/common\.(asc|desc)$/u, ''))+ )+ .toEqual(['models.sort.catalog', 'models.sort.name', 'models.sort.base', 'models.sort.format']);++ await unmount();+ });+it('links each installed starter to the library model it became', async () => {setModelsSnapshotForTests({models: [@@ -255,7 +331,8 @@ describe('AddModelsView search seed', () => {(button) => button.textContent === 'models.viewModel');expect(links).toHaveLength(2);- for (const [index, key] of ['by-source', 'by-name'].entries()) {+ // The list sorts by name: Dreamshaper XL, then Juggernaut XL.+ for (const [index, key] of ['by-name', 'by-source'].entries()) {updateModelsUi({ activeModelKey: null, activeTab: 'add' });await act(() => links[index]!.click());expect(getModelsUiSnapshotForTests()).toMatchObject({ activeModelKey: key, activeTab: 'details' });@@ -276,7 +353,9 @@ describe('AddModelsView models folder scan', () => {await act(async () => {root.render(<ChakraProvider value={system}>- <AddModelsView />+ <WithAccountPreferences>+ <AddModelsView />+ </WithAccountPreferences></ChakraProvider>);await new Promise<void>((resolve) => {@@ -317,6 +396,7 @@ describe('AddModelsView models folder scan', () => {host.remove();updateModelsUi({ hfLookup: null, scan: null });setModelsSnapshotForTests({ models: [], modelsDir: null, status: 'loaded' });+ resetSessionAndPreferences();});it.each(['/opt/invokeai/models', '/mnt/fast disk/Invoke Models'])(@@ -381,7 +461,8 @@ describe('AddModelsView models folder scan', () => {await act(() => userEvent.click(buttonNamed('models.pull')!));expect(installActions.install).toHaveBeenLastCalledWith(expect.objectContaining({ inplace: true, source: inside }));- // Leaving the folder restores the user's own choice.+ // Leaving the folder restores the user's own choice, which the forced state never overwrote.+ expect(accountPreferences.getSnapshot().installInPlace).toBe(false);await act(() => userEvent.fill(searchBox, outside));expect(inplaceInput().checked).toBe(false);expect(inplaceInput().disabled).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsxindex 9317501c3a..8a414bd380 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx@@ -17,12 +17,13 @@ import {} from '@features/models/data/externalProvidersStore';import { useModelsSelector } from '@features/models/data/modelsStore';import { ensureStartersLoaded, useStartersSelector } from '@features/models/data/startersStore';+import { useModelsUi } from '@features/models/ui/ModelsUiContext';import {- clearAddModelsSeeds,- getAddModelsSeed,+ clearAddModelsTypeSeed,getAddModelsTypeSeed,openExternalProviderKeys,openModelManagerTab,+ setAddModelsQuery,updateModelsUi,useModelsUiSelector,} from '@features/models/ui/uiStore';@@ -75,23 +76,23 @@ export const AddModelsView = () => {const loadError = useStartersSelector((snapshot) => snapshot.error);const response = useStartersSelector((snapshot) => snapshot.response);const status = useStartersSelector((snapshot) => snapshot.status);- const { hfLookup, scan, selectedBundleName } = useModelsUiSelector(+ const { hfLookup, query, scan, selectedBundleName } = useModelsUiSelector((snapshot) => ({hfLookup: snapshot.hfLookup,+ query: snapshot.addModelsQuery,scan: snapshot.scan,selectedBundleName: snapshot.selectedBundleName,}),(left, right) =>left.hfLookup === right.hfLookup &&+ left.query === right.query &&left.scan === right.scan &&left.selectedBundleName === right.selectedBundleName);- // Read the one-shot seed purely for StrictMode initialization; consume it after mount and keep subsequent input- // state local.- const [query, setQuery] = useState(getAddModelsSeed);const [accessToken, setAccessToken] = useState('');- const [inplace, setInplace] = useState(true);+ // The account's last choice; a source inside the models folder is forced in place without changing it.+ const { installInPlace: inplace, setInstallInPlace: setInplace } = useModelsUi();const modelsDir = useModelsSelector((snapshot) => snapshot.modelsDir);// Sources in the models folder always install in place; otherwise the install would move their files into a new// managed folder within it.@@ -120,8 +121,8 @@ export const AddModelsView = () => {});useMountEffect(() => {- // One-shot: a seed only ever fills the view it was opened with.- clearAddModelsSeeds();+ // One-shot: a type seed only ever fills the view it was opened with.+ clearAddModelsTypeSeed();ensureStartersLoaded();const owner = captureAccountScope();@@ -238,7 +239,7 @@ export const AddModelsView = () => {(await install({ accessToken: token, config: installConfig, source: trimmed })) &&isAccountScopeCurrent(owner)) {- setQuery('');+ setAddModelsQuery('');}return;@@ -260,7 +261,7 @@ export const AddModelsView = () => {(await install({ accessToken: token, config: installConfig, source: onlyUrl })) &&isAccountScopeCurrent(owner)) {- setQuery('');+ setAddModelsQuery('');}return;@@ -280,7 +281,7 @@ export const AddModelsView = () => {})) &&isAccountScopeCurrent(owner)) {- setQuery('');+ setAddModelsQuery('');}},(message) => notify.error(t('models.installFailed'), message)@@ -334,7 +335,7 @@ export const AddModelsView = () => {placeholder={t('models.searchOrAddPlaceholder')}size="lg"value={query}- onChange={(event) => setQuery(event.currentTarget.value)}+ onChange={(event) => setAddModelsQuery(event.currentTarget.value)}onKeyDown={(event) => {if (event.key !== 'Enter') {return;diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsxindex db6237e44f..0e6f52cfed 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.browser.test.tsx@@ -79,5 +79,15 @@ describe('BundleChips overflow', () => {expect(horizontalScrollbar!.getAttribute('data-orientation')).toBe('horizontal');expect(viewport!.contains(trailing)).toBe(false);++ // (b) the scrollbar sits in its own gutter: it overlaps no chip and no count badge.+ const scrollbarRect = horizontalScrollbar!.getBoundingClientRect();+ const chipParts = [...viewport!.querySelectorAll<HTMLElement>('button, .chakra-badge')];+ expect(chipParts.length).toBeGreaterThan(bundles.length);+ expect(scrollbarRect.height).toBeGreaterThan(0);+ for (const part of chipParts) {+ const rect = part.getBoundingClientRect();+ expect(rect.bottom, part.textContent ?? '').toBeLessThanOrEqual(scrollbarRect.top);+ }});});diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsxindex e62e0bb8c8..e97bb62816 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/BundleChips.tsx@@ -3,7 +3,7 @@ import type { StarterModelBundle } from '@features/models/core/types';import type { ReactNode } from 'react';import { Badge, Box, HStack, Icon } from '@chakra-ui/react';-import { Button } from '@platform/ui';+import { Button } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { CheckIcon, FolderIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -38,7 +38,8 @@ export const BundleChips = ({orientation="horizontal"variant="hover">- <HStack gap="1.5">+ {/* The overlay scrollbar gets its own gutter (its size plus margins) so it never covers chips or badges. */}+ <HStack gap="1.5" pb="var(--scrollbar-click-area)"><BundleChipisSelected={selectedName === null}label={t('common.all')}diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsxindex f7f6edeaed..41280e55d6 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.browser.test.tsx@@ -44,6 +44,11 @@ const installedModel = {const noop = () => undefined;const NO_PENDING: ReadonlySet<string> = new Set<string>();const SCAN = { path: '/home/user/downloads', results: [{ is_installed: false, path: SCANNED_PATH }] };+// What a scan on Windows reports: OS-native separators.+const WINDOWS_SCAN = {+ path: 'C:\\Users\\me\\loras',+ results: [{ is_installed: false, path: 'C:\\Users\\me\\loras\\x.safetensors' }],+};const Harness = () => (<ChakraProvider value={system}>@@ -113,6 +118,62 @@ describe('ScanResults install badge lifecycle', () => {});});+describe('ScanResults on Windows paths', () => {+ let host: HTMLDivElement;+ let root: Root;++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+ });++ it('marks a backslash row installed once the library holds it under forward slashes, with no rescan', async () => {+ accountLifecycle.activate('scan-results-windows', ':user:scan-results-windows');+ setModelsSnapshotForTests({ models: [], status: 'loaded' });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <ScanResults+ fp8Storage={false}+ inplace+ pendingSources={NO_PENDING}+ scan={WINDOWS_SCAN}+ onClear={noop}+ onInstall={noop}+ onInstallAll={noop}+ onSetFp8Storage={noop}+ onSetInplace={noop}+ />+ </ChakraProvider>+ );+ });+ expect(host.textContent).not.toContain('models.installed');++ // Install records store paths with forward slashes, as the backend writes them.+ await act(async () => {+ setModelsSnapshotForTests({+ models: [+ {+ ...installedModel,+ key: 'windows-lora',+ path: 'C:/Users/me/loras/x.safetensors',+ source: 'C:/Users/me/loras/x.safetensors',+ },+ ],+ status: 'loaded',+ });+ await Promise.resolve();+ });++ expect(host.textContent).toContain('models.installed');+ expect([...host.querySelectorAll('button')].some((button) => button.textContent === 'models.viewModel')).toBe(true);+ });+});+describe('ScanResults row context menu', () => {let host: HTMLDivElement;let root: Root;diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsxindex 932068864a..38175dc8bf 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/ScanResults.tsx@@ -9,7 +9,7 @@ import {} from '@features/models/ui/shared/InstallSourceMenu';import { InstallPathRow } from '@features/models/ui/shared/InstallSourceRow';import { ResultsListHeader } from '@features/models/ui/shared/ResultsListHeader';-import { useInstalledSourceKeys } from '@features/models/ui/shared/useInstalledSources';+import { findInstalledLocalPathKey, useInstalledSourceKeys } from '@features/models/ui/shared/useInstalledSources';import { sourceLocation, useSourceNameFilter } from '@features/models/ui/shared/useSourceNameFilter';import { IconButton } from '@platform/ui';import { ListStack } from '@platform/ui/list/ListStack';@@ -50,9 +50,10 @@ export const ScanResults = ({// Live library state: `is_installed` is a scan-time snapshot, so a model// installed from this list would otherwise keep offering Install forever.const installedSourceKeys = useInstalledSourceKeys();- const isRowInstalled = (result: FoundModel) => result.is_installed || installedSourceKeys.has(result.path);+ const installedKeyOf = (result: FoundModel) => findInstalledLocalPathKey(result.path, installedSourceKeys);+ const isRowInstalled = (result: FoundModel) => result.is_installed || installedKeyOf(result) !== null;const statusOf = (result: FoundModel): InstallSourceStatus => ({- installedModelKey: installedSourceKeys.get(result.path) ?? null,+ installedModelKey: installedKeyOf(result),isInstalled: isRowInstalled(result),isPending: pendingSources.has(result.path),});diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsxindex 59b4bb7115..6badb709b7 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx@@ -3,12 +3,16 @@ import type { ModelTaxonomyType } from '@features/models/core/types';import type { ModelFilterSortOption } from '@features/models/ui/shared/ModelFilterMenu';/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import { ModelFilterMenu, SORT_FIELD_OPTIONS } from '@features/models/ui/shared/ModelFilterMenu';+import { ModelFilterMenu } from '@features/models/ui/shared/ModelFilterMenu';import { useTranslation } from 'react-i18next';-const STARTER_SORT_FIELDS = SORT_FIELD_OPTIONS.filter(- (option): option is ModelFilterSortOption<StarterSortField> => option.field !== 'size'-);+/** Name is the starter list's default, so the catalog's own order is named for what it is, not "Default". */+const STARTER_SORT_FIELDS: readonly ModelFilterSortOption<StarterSortField>[] = [+ { field: 'default', labelKey: 'models.sort.catalog' },+ { field: 'name', labelKey: 'models.sort.name' },+ { field: 'base', labelKey: 'models.sort.base' },+ { field: 'format', labelKey: 'models.sort.format' },+];const isFiltering = (filters: StarterModelFilters): boolean =>filters.typeFilter !== null || filters.baseFilter !== null;diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsxindex 11a09d83bc..36248e41ee 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx@@ -2,7 +2,7 @@ import type { ModelConfig } from '@features/models';import { ChakraProvider, Field as ChakraField } from '@chakra-ui/react';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';-import { ModelsUiProvider } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';import { auditAccessibility, contrastOffenderTexts } from '@platform/browser/auditAccessibility.testing';import { Field } from '@platform/ui/Field';import { system } from '@theme/system';@@ -41,8 +41,11 @@ const secondSdxlModel = { ...model, key: 'sdxl-other', name: 'Another SDXL' } asconst MODELS_UI_ADAPTER = {canManageModels: true,enableModelDescriptions: true,+ installInPlace: true,isProjectActive: () => true,managerProjectId: null,+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace: () => undefined,};const MAIN_MODEL_TYPES: ['main'] = ['main'];const CROSS_TYPE_MODEL_TYPES: ['main', 'lora'] = ['main', 'lora'];diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsxindex 6741709eaf..0c9ed7ce68 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/DefaultSettingsSection.tsx@@ -1,5 +1,6 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import type { AnyModelDefaultSettings } from '@features/models/core/types';+import type { SchedulerPolicyState } from '@features/models/ui/ModelsUiContext';import { createListCollection, Grid, HStack, Icon, NumberInput, Stack, Switch, Text } from '@chakra-ui/react';import { updateModel } from '@features/models/data/api';@@ -22,15 +23,16 @@ import {useModelDraft,type ModelDraft,} from '@features/models/ui/modelDraftsStore';+import { useModelsUi } from '@features/models/ui/ModelsUiContext';import { useMountEffect } from '@platform/react/useMountEffect';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';import { Button, Combobox, FieldLabel, Panel, Select } from '@platform/ui';import { MoveHorizontalIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';-import type { DefaultSettingsControl, DefaultSettingsModel } from './defaultSettingsFields';+import type { DefaultSettingsControl, DefaultSettingsModel, SchedulerFieldRules } from './defaultSettingsFields';import { getFieldsForModel, validateDefaults } from './defaultSettingsFields';import { DraftConflictNotice, UnsavedChangesLabel } from './ModelDraftNotices';@@ -63,10 +65,6 @@ const FieldControl = ({ control, disabled, label, modelBase, setValue, value }:() => (control.kind === 'select' ? buildCollection(control.options) : null),[control]);- const comboboxOptions = useMemo(- () => (control.kind === 'combobox' ? control.options.map((option) => ({ label: option, value: option })) : null),- [control]- );if (control.kind === 'number') {return (@@ -125,12 +123,12 @@ const FieldControl = ({ control, disabled, label, modelBase, setValue, value }:);}- if (control.kind === 'combobox' && comboboxOptions) {+ if (control.kind === 'combobox') {return (<Comboboxaria-label={label}disabled={disabled}- options={comboboxOptions}+ options={control.options}size="lg"value={typeof value === 'string' ? value : null}onValueChange={setValue}@@ -177,7 +175,65 @@ export const DefaultSettingsSection = ({void ensureFp8StorageSupportLoaded();});const fp8StorageSupported = useFp8StorageSupportSelector((snapshot) => isFp8StorageSupported(snapshot, model));- const fields = useMemo(() => getFieldsForModel(model, fp8StorageSupported), [fp8StorageSupported, model]);+ // Generate's scheduler rules load with the section, as the FP8 answer does; the row shows disabled until they do.+ const { schedulerPolicy: schedulerPolicySource } = useModelsUi();+ useMountEffect(() => {+ schedulerPolicySource.load();+ });+ const schedulerPolicyState = useSyncExternalStore(+ schedulerPolicySource.subscribe,+ schedulerPolicySource.getSnapshot,+ schedulerPolicySource.getSnapshot+ );+ const schedulerRules = useMemo((): SchedulerFieldRules | null => {+ if (model.type !== 'main') {+ return null;+ }+ return schedulerPolicyState.status === 'ready'+ ? schedulerPolicyState.read(model, model.default_settings?.scheduler ?? null)+ : schedulerPolicyState.status;+ }, [model, schedulerPolicyState]);+ // The failure a retry started from. The retry is over once the rules arrive or a new failure replaces it, so a later+ // ordinary load (another account, say) shows the plain loading text rather than "Retrying…".+ const [retriedFailure, setRetriedFailure] = useState<SchedulerPolicyState | null>(null);+ if (+ retriedFailure &&+ (schedulerPolicyState.status === 'ready' ||+ (schedulerPolicyState.status === 'unavailable' && schedulerPolicyState !== retriedFailure))+ ) {+ setRetriedFailure(null);+ }+ const isRetryingSchedulerRules = retriedFailure !== null;+ const schedulerSwitchRef = useRef<HTMLInputElement | null>(null);+ const headingRef = useRef<HTMLDivElement | null>(null);+ const retrySchedulerRules = () => {+ if (schedulerPolicyState.status !== 'unavailable') {+ return;+ }+ setRetriedFailure(schedulerPolicyState);+ schedulerPolicySource.load();+ };+ // When a retry succeeds the Retry button leaves with the note; hand the focus it held to the scheduler row, or to+ // the section heading when the base ignores the scheduler and the whole row left with it.+ const handOverRetryFocus = useCallback((button: HTMLButtonElement | null) => {+ if (!button) {+ return undefined;+ }+ return () => {+ if (button !== document.activeElement) {+ return;+ }+ // After the commit, once the row has either stayed or gone.+ queueMicrotask(() => {+ const schedulerSwitch = schedulerSwitchRef.current;+ (schedulerSwitch?.isConnected ? schedulerSwitch : headingRef.current)?.focus();+ });+ };+ }, []);+ const fields = useMemo(+ () => getFieldsForModel(model, fp8StorageSupported, schedulerRules),+ [fp8StorageSupported, model, schedulerRules]+ );const saved = model.default_settings ?? EMPTY_SETTINGS;const draft = useModelDraft(model.key, selectDefaultsDraft);const settings = useMemo(() => applyModelDraftFields(saved, draft), [draft, saved]);@@ -230,7 +286,7 @@ export const DefaultSettingsSection = ({return (<Stack gap="3"><HStack justify="space-between">- <Stack gap="0.5">+ <Stack ref={headingRef} gap="0.5" tabIndex={-1}><FieldLabel>{t('models.defaultSettings')}</FieldLabel><Text color="fg.subtle" fontSize="xs">{t('models.defaultSettingsHelp')}@@ -270,10 +326,12 @@ export const DefaultSettingsSection = ({<Switch.Rootchecked={isEnabled}colorPalette="accent"+ // Without the rules there is no default to turn on, but a stored value can still be cleared.+ disabled={field.pending !== undefined && !isEnabled}size="sm"onCheckedChange={(event) => setFieldValue(field.key, event.checked ? field.defaultValue : null)}>- <Switch.HiddenInput />+ <Switch.HiddenInput ref={field.key === 'scheduler' ? schedulerSwitchRef : undefined} /><Switch.Control><Switch.Thumb /></Switch.Control>@@ -283,16 +341,42 @@ export const DefaultSettingsSection = ({{field.control ? (<FieldControlcontrol={field.control}- disabled={!isEnabled}+ disabled={!isEnabled || field.pending !== undefined}label={t(field.labelKey)}modelBase={String(model.base)}setValue={(nextValue) => setFieldValue(field.key, nextValue)}value={isEnabled ? value : field.defaultValue}/>) : null}- <Text color="fg.subtle" fontSize="xs">- {isEnabled ? t('models.customizedForThisModel') : t(field.inheritLabelKey)}- </Text>+ {field.pending === 'unavailable' || (field.pending === 'loading' && isRetryingSchedulerRules) ? (+ // One Retry button across the failure and the retry's load, so the focus it holds stays put.+ <HStack gap="2" justify="space-between" role={field.pending === 'unavailable' ? 'alert' : 'status'}>+ <Text color={field.pending === 'unavailable' ? 'fg.warning' : 'fg.subtle'} fontSize="xs">+ {field.pending === 'unavailable'+ ? t('models.schedulerListUnavailable')+ : t('models.schedulerListLoading')}+ </Text>+ <Button+ ref={handOverRetryFocus}+ aria-busy={field.pending === 'loading'}+ // `aria-disabled` rather than `disabled`: a disabled button drops the focus it holds.+ aria-disabled={field.pending === 'loading'}+ size="xs"+ variant="outline"+ onClick={retrySchedulerRules}+ >+ {field.pending === 'loading' ? t('models.schedulerListRetrying') : t('common.retry')}+ </Button>+ </HStack>+ ) : (+ <Text color="fg.subtle" fontSize="xs" role={field.pending === 'loading' ? 'status' : undefined}>+ {field.pending === 'loading'+ ? t('models.schedulerListLoading')+ : isEnabled+ ? t('models.customizedForThisModel')+ : t(field.inheritLabelKey)}+ </Text>+ )}</Panel>);})}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex a354aa5f32..7069f44e8b 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -6,7 +6,7 @@ import { chakra, DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text }import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';import { isLinkableType } from '@features/models/core/relationships';import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';-import { getModelSourceHref } from '@features/models/core/taxonomy';+import { getModelSourceHref, getUnrecordedModelFact } from '@features/models/core/taxonomy';import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';import {discardModelDraft,@@ -14,6 +14,7 @@ import {useModelDraft,type ModelDraft,} from '@features/models/ui/modelDraftsStore';+import { useModelsUi } from '@features/models/ui/ModelsUiContext';import { ModelActionMenuItems, type PendingModelAction } from '@features/models/ui/shared/ModelActionsMenu';import { useNotify } from '@features/models/ui/useModelsNotify';import { formatBytes } from '@platform/i18n/languages';@@ -34,6 +35,7 @@ import { ModelImageUpload } from './ModelImageUpload';import { ModelSettingsMenuItems } from './ModelSettingsMenuItems';import { RelatedModelsSection } from './RelatedModelsSection';import { MemoizedTriggerPhrasesEditor } from './TriggerPhrasesEditor';+import { UnrecordedFactNotice } from './UnrecordedFactNotice';import { UpdatePathDialog } from './UpdatePathDialog';const TRIGGER_PHRASE_TYPES = new Set(['main', 'lora', 'embedding']);@@ -45,6 +47,7 @@ type CpuOnlyModel = Pick<ModelConfig, 'cpu_only' | 'key' | 'name' | 'type'>;type ModelIdentityModel = Pick<ModelConfig,| 'base'+ | 'cond_in_channels'| 'config_path'| 'cover_image'| 'description'@@ -59,6 +62,7 @@ type ModelIdentityModel = Pick<| 'provider_id'| 'provider_model_id'| 'repo_variant'+ | 'scale'| 'source'| 'source_type'| 'source_url'@@ -83,6 +87,7 @@ const selectModelIdentity = (snapshot: ModelsSnapshot, modelKey: string): ModelIreturn model? {base: model.base,+ cond_in_channels: model.cond_in_channels,config_path: model.config_path,cover_image: model.cover_image,description: model.description,@@ -97,6 +102,7 @@ const selectModelIdentity = (snapshot: ModelsSnapshot, modelKey: string): ModelIprovider_id: model.provider_id,provider_model_id: model.provider_model_id,repo_variant: model.repo_variant,+ scale: model.scale,source: model.source,source_type: model.source_type,source_url: model.source_url,@@ -110,7 +116,8 @@ const selectDefaultSettingsModel = (snapshot: ModelsSnapshot, modelKey: string):const model = findModel(snapshot, modelKey);// `base` and `format` are projected too: together with the type they are the loader key the backend- // answers the FP8 Storage question on, and all three parts change the answer.+ // answers the FP8 Storage question on, and all three parts change the answer. `variant` joins them+ // for Generate's scheduler rules, which differ by variant within a base.return model? {base: model.base,@@ -118,6 +125,7 @@ const selectDefaultSettingsModel = (snapshot: ModelsSnapshot, modelKey: string):format: model.format,key: model.key,type: model.type,+ variant: model.variant,}: null;};@@ -228,6 +236,8 @@ const ModelIdentitySection = memo(function ModelIdentitySection({}: ModelIdentitySectionProps) {const notify = useNotify();const { t } = useTranslation();+ const { canManageModels } = useModelsUi();+ const unrecordedFact = getUnrecordedModelFact(model);// The open editor lives with the model's retained draft, so it survives leaving the pane and coming back.const isEditing = useModelDraft(model.key, isIdentityEditorOpen);@@ -273,6 +283,13 @@ const ModelIdentitySection = memo(function ModelIdentitySection({/></HStack>+ {unrecordedFact ? (+ <UnrecordedFactNotice+ fact={unrecordedFact}+ onReidentify={canManageModels ? () => onRequestConfirm({ kind: 'reidentify', model }) : null}+ />+ ) : null}+{isEditing ? (<ModelEditFormmodel={model}@@ -315,7 +332,12 @@ const ModelDetailActions = ({</Button><Menu.Root positioning={{ placement: 'bottom-end' }}><Menu.Trigger asChild>- <IconButton aria-label={t('models.actions')} loading={isActionBusy} variant="ghost">+ <IconButton+ aria-label={t('models.actions')}+ data-model-actions-trigger=""+ loading={isActionBusy}+ variant="ghost"+ ><Icon as={MoreHorizontalIcon} boxSize="4" /></IconButton></Menu.Trigger>@@ -436,6 +458,10 @@ const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: Mode{ label: t('models.fileSize'), value: formatBytes(model.file_size) },{ label: t('models.variant'), value: model.variant ?? '—' },{ label: t('models.predictionType'), value: model.prediction_type ?? '—' },+ // Recorded by the probe for upscalers; an unrecorded one is explained by the notice above instead.+ ...(typeof model.scale === 'number'+ ? [{ label: t('models.nativeScale'), value: t('models.nativeScaleValue', { scale: model.scale }) }]+ : []),{ label: t('models.hash'), value: model.hash },{action: canUpdatePath ? (diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsxindex ab4338140c..cd466e3c97 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx@@ -3,7 +3,7 @@ import type { ModelConfig } from '@features/models';import { ChakraProvider } from '@chakra-ui/react';import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';import { setRelationshipsSnapshotForTests } from '@features/models/data/relationshipsStore';-import { ModelsUiProvider } from '@features/models/ui/ModelsUiContext';+import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';import { system } from '@theme/system';@@ -48,8 +48,11 @@ const externalMain = createModel({ base: 'external', key: 'gpt-image', name: 'GPconst MODELS_UI_ADAPTER = {canManageModels: true,enableModelDescriptions: false,+ installInPlace: true,isProjectActive: () => true,managerProjectId: null,+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace: () => undefined,};const SECTION_MODEL = { base: 'flux', key: 'flux-main', type: 'main' } as const;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/UnrecordedFactNotice.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/UnrecordedFactNotice.tsxnew file mode 100644index 0000000000..e199eeeeda--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/UnrecordedFactNotice.tsx@@ -0,0 +1,56 @@+import type { UnrecordedModelFact } from '@features/models/core/taxonomy';++import { HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { RefreshCcwIcon, TriangleAlertIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++const MESSAGE_KEYS: Record<UnrecordedModelFact, string> = {+ adapter_type: 'models.adapterTypeUnknown',+ native_scale: 'models.nativeScaleUnknown',+};++/**+ * Explains what a model installed before the probe recorded it is missing, and offers Re-identify. `onReidentify` is+ * null for users who cannot manage models; they are told to ask an administrator instead.+ */+export const UnrecordedFactNotice = ({+ fact,+ onReidentify,+}: {+ fact: UnrecordedModelFact;+ onReidentify: (() => void) | null;+}) => {+ const { t } = useTranslation();++ return (+ <HStack+ align="start"+ bg="bg.subtle"+ borderColor="border.subtle"+ borderRadius="md"+ borderWidth="1px"+ gap="2"+ p="2.5"+ wrap="wrap"+ >+ <Icon as={TriangleAlertIcon} boxSize="3.5" color="fg.warning" flexShrink={0} mt="0.5" />+ <Stack flex="1 1 14rem" gap="0.5" minW="0">+ <Text color="fg.muted" fontSize="xs">+ {t(MESSAGE_KEYS[fact])}+ </Text>+ {onReidentify ? null : (+ <Text color="fg.subtle" fontSize="xs">+ {t('models.reidentifyAskAdmin')}+ </Text>+ )}+ </Stack>+ {onReidentify ? (+ <Button flexShrink={0} ms="auto" variant="outline" onClick={onReidentify}>+ <Icon as={RefreshCcwIcon} boxSize="3" />+ {t('models.reidentify')}+ </Button>+ ) : null}+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.tsindex 074d71d960..9d3aba52e9 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.test.ts@@ -1,14 +1,33 @@import type { ModelConfig } from '@features/models/core/types';+import type { ModelSchedulerPolicy } from '@features/models/ui/ModelsUiContext';import { describe, expect, it } from 'vitest';-import { getFieldsForModel, validateDefaults } from './defaultSettingsFields';+import { getFieldsForModel, validateDefaults, type SchedulerFieldRules } from './defaultSettingsFields';-const model = (base: string, type: string): Pick<ModelConfig, 'base' | 'type'> =>- ({ base, type }) as Pick<ModelConfig, 'base' | 'type'>;+type FieldsModel = Pick<ModelConfig, 'base' | 'default_settings' | 'type'>;-const fieldKeys = (candidate: Pick<ModelConfig, 'base' | 'type'>, fp8StorageSupported = true): string[] =>- getFieldsForModel(candidate, fp8StorageSupported).map((field) => String(field.key));+const model = (base: string, type: string, defaultSettings: ModelConfig['default_settings'] = null): FieldsModel =>+ ({ base, default_settings: defaultSettings, type }) as FieldsModel;++const ANIMA_POLICY: ModelSchedulerPolicy = {+ appliesToGraph: true,+ defaultValue: 'euler',+ options: [+ { label: 'Euler', value: 'euler' },+ { label: 'ER-SDE', value: 'er_sde' },+ ],+};+const IGNORED_POLICY: ModelSchedulerPolicy = { ...ANIMA_POLICY, appliesToGraph: false };++const fieldKeys = (+ candidate: FieldsModel,+ fp8StorageSupported = true,+ schedulerRules: SchedulerFieldRules | null = ANIMA_POLICY+): string[] => getFieldsForModel(candidate, fp8StorageSupported, schedulerRules).map((field) => String(field.key));++const schedulerField = (candidate: FieldsModel, policy: ModelSchedulerPolicy) =>+ getFieldsForModel(candidate, false, policy).find((field) => field.key === 'scheduler');describe('getFieldsForModel', () => {it('appends fp8_storage to the main-model fields without disturbing the existing ones', () => {@@ -50,6 +69,48 @@ describe('getFieldsForModel', () => {});});+describe('getFieldsForModel scheduler row', () => {+ it("offers the injected policy's options and turns on at its default", () => {+ const field = schedulerField(model('anima', 'main'), ANIMA_POLICY);++ expect(field?.control).toEqual({+ kind: 'combobox',+ options: [+ { label: 'Euler', value: 'euler' },+ { label: 'ER-SDE', value: 'er_sde' },+ ],+ });+ expect(field?.defaultValue).toBe('euler');+ });++ it('leaves the row out where the graph ignores the scheduler and nothing is stored', () => {+ expect(fieldKeys(model('flux2', 'main'), false, IGNORED_POLICY)).not.toContain('scheduler');+ });++ it('keeps the row where the graph ignores the scheduler but a value is stored, so it can be cleared', () => {+ expect(fieldKeys(model('flux2', 'main', { scheduler: 'euler_a' }), false, IGNORED_POLICY)).toContain('scheduler');+ });++ it.each(['loading', 'unavailable'] as const)(+ 'shows the row %s, keeping a stored value as its only choice',+ (rules) => {+ const pending = getFieldsForModel(model('flux2', 'main', { scheduler: 'euler_a' }), false, rules).find(+ (field) => field.key === 'scheduler'+ );++ expect(pending).toMatchObject({+ control: { kind: 'combobox', options: [{ label: 'euler_a', value: 'euler_a' }] },+ pending: rules,+ });+ expect(fieldKeys(model('flux2', 'main'), false, rules)).toContain('scheduler');+ }+ );++ it('keeps the row second, after the VAE', () => {+ expect(fieldKeys(model('sdxl', 'main'), false).slice(0, 3)).toEqual(['vae', 'scheduler', 'steps']);+ });+});+describe('validateDefaults', () => {const t = ((key: string) => key) as Parameters<typeof validateDefaults>[2];diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.tsindex 8b7c2a7a60..3191e85547 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/defaultSettingsFields.ts@@ -1,48 +1,19 @@import type { AnyModelDefaultSettings, ModelConfig, ModelTaxonomyType } from '@features/models/core/types';+import type { ModelSchedulerPolicy, SchedulerChoice } from '@features/models/ui/ModelsUiContext';import type { TFunction } from 'i18next';import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/models/core/schemas';-export type DefaultSettingsModel = Pick<ModelConfig, 'base' | 'default_settings' | 'format' | 'key' | 'type'>;+export type DefaultSettingsModel = Pick<+ ModelConfig,+ 'base' | 'default_settings' | 'format' | 'key' | 'type' | 'variant'+>;const CONTROL_ADAPTER_TYPES = new Set(['controlnet', 't2i_adapter', 'control_lora']);export const supportsDefaultSettings = (model: Pick<ModelConfig, 'type'>): boolean =>model.type === 'main' || model.type === 'lora' || CONTROL_ADAPTER_TYPES.has(model.type);-const SCHEDULERS = [- 'ddim',- 'ddpm',- 'deis',- 'deis_k',- 'dpmpp_2s',- 'dpmpp_2s_k',- 'dpmpp_2m',- 'dpmpp_2m_k',- 'dpmpp_2m_sde',- 'dpmpp_2m_sde_k',- 'dpmpp_3m',- 'dpmpp_3m_k',- 'dpmpp_sde',- 'dpmpp_sde_k',- 'euler',- 'euler_k',- 'euler_a',- 'heun',- 'heun_k',- 'kdpm_2',- 'kdpm_2_k',- 'kdpm_2_a',- 'kdpm_2_a_k',- 'lcm',- 'lms',- 'lms_k',- 'pndm',- 'tcd',- 'unipc',- 'unipc_k',-];-const PREPROCESSORS = ['canny_edge_detection','color_map',@@ -63,7 +34,7 @@ const PREPROCESSORS = [export type DefaultSettingsControl =| { kind: 'number'; max?: number; min?: number; step?: number }| { kind: 'select'; options: readonly string[] }- | { kind: 'combobox'; options: readonly string[] }+ | { kind: 'combobox'; options: readonly SchedulerChoice[] }| {kind: 'model';modelTypes: readonly ModelTaxonomyType[];@@ -85,8 +56,13 @@ export interface FieldSpec {defaultValue: unknown;/** Translation key for what applies while the toggle is off. */inheritLabelKey: string;+ /** The rules this row's choices come from are still loading or failed: it shows, disabled, without them. */+ pending?: 'loading' | 'unavailable';}+/** Generate's rules for a main model's scheduler, or why they are not here yet. */+export type SchedulerFieldRules = ModelSchedulerPolicy | 'loading' | 'unavailable';+/*** Only fp8_storage=true changes backend behavior; the row toggle covers it without a redundant body switch. Mirror* backend exclusions.@@ -98,23 +74,18 @@ const FP8_STORAGE_FIELD: FieldSpec = {labelKey: 'models.defaultFields.fp8Storage',};+const VAE_FIELD: FieldSpec = {+ control: { kind: 'model', modelTypes: ['vae'], placeholderKey: 'models.defaultVae', sameBase: true },+ // The backend sentinel for "the compatible default VAE" — what legacy+ // writes when the toggle is on but no specific model is picked.+ defaultValue: 'default',+ inheritLabelKey: 'models.defaultFieldInherited.vae',+ key: 'vae',+ labelKey: 'models.defaultFields.vae',+};++/** Main-model fields after the VAE and scheduler rows. */const MAIN_FIELDS: FieldSpec[] = [- {- control: { kind: 'model', modelTypes: ['vae'], placeholderKey: 'models.defaultVae', sameBase: true },- // The backend sentinel for "the compatible default VAE" — what legacy- // writes when the toggle is on but no specific model is picked.- defaultValue: 'default',- inheritLabelKey: 'models.defaultFieldInherited.vae',- key: 'vae',- labelKey: 'models.defaultFields.vae',- },- {- control: { kind: 'combobox', options: SCHEDULERS },- defaultValue: 'euler_a',- inheritLabelKey: 'models.defaultFieldInherited.scheduler',- key: 'scheduler',- labelKey: 'models.defaultFields.scheduler',- },{control: { kind: 'number', max: 10000, min: 1 },defaultValue: 30,@@ -166,6 +137,24 @@ const MAIN_FIELDS: FieldSpec[] = [},];+const SCHEDULER_FIELD = {+ inheritLabelKey: 'models.defaultFieldInherited.scheduler',+ key: 'scheduler',+ labelKey: 'models.defaultFields.scheduler',+} as const;++/** Generate's options and default for the base; see {@link getFieldsForModel}. */+const getSchedulerField = (rules: SchedulerFieldRules, stored: string | null): FieldSpec =>+ typeof rules === 'string'+ ? {+ ...SCHEDULER_FIELD,+ // Without the rules, only a stored value can be named; it stays visible.+ control: { kind: 'combobox', options: stored === null ? [] : [{ label: stored, value: stored }] },+ defaultValue: stored,+ pending: rules,+ }+ : { ...SCHEDULER_FIELD, control: { kind: 'combobox', options: rules.options }, defaultValue: rules.defaultValue };+const LORA_FIELDS: FieldSpec[] = [{control: { kind: 'number', max: 10, min: -10, step: 0.05 },@@ -205,12 +194,26 @@ const CONTROL_ADAPTER_FIELDS: FieldSpec[] = [* here. It used to be `type === 'main' || 'controlnet' || 't2i_adapter'`, which offered the control for* 19 of the 52 loader keys that ignore it: the answer also depends on the model's format, and on* whether its loader implements the cast at all — neither of which this module can see.+ *+ * `schedulerRules` is Generate's rule set for a main model's base. Where the base's graph ignores the+ * scheduler the row is left out, as Generate hides it, unless a stored value needs a row to be cleared. While the+ * rules load or after they fail the row shows disabled, so it neither jumps in later nor silently disappears.*/-export const getFieldsForModel = (model: Pick<ModelConfig, 'type'>, fp8StorageSupported: boolean): FieldSpec[] => {+export const getFieldsForModel = (+ model: Pick<ModelConfig, 'default_settings' | 'type'>,+ fp8StorageSupported: boolean,+ schedulerRules: SchedulerFieldRules | null+): FieldSpec[] => {const fp8Fields = fp8StorageSupported ? [FP8_STORAGE_FIELD] : [];if (model.type === 'main') {- return [...MAIN_FIELDS, ...fp8Fields];+ const storedScheduler = model.default_settings?.scheduler ?? null;+ const schedulerFields =+ schedulerRules &&+ (typeof schedulerRules === 'string' || schedulerRules.appliesToGraph || storedScheduler !== null)+ ? [getSchedulerField(schedulerRules, storedScheduler)]+ : [];+ return [VAE_FIELD, ...schedulerFields, ...MAIN_FIELDS, ...fp8Fields];}if (model.type === 'lora') {diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsxindex fb3f763b8a..a22e6f038a 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.browser.test.tsx@@ -1,7 +1,8 @@import type { ModelConfig } from '@features/models/core/types';import { ChakraProvider } from '@chakra-ui/react';-import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { getModelsSnapshot, setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';import { getModelsUiSnapshotForTests, openModelDetail } from '@features/models/ui/uiStore';import { accountLifecycle } from '@platform/state/accountLifecycle';import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';@@ -13,14 +14,21 @@ import { userEvent } from 'vitest/browser';import { DetailPane } from './DetailPane';-const api = vi.hoisted(() => ({ deleteModel: vi.fn(() => Promise.resolve()) }));+const api = vi.hoisted(() => ({+ deleteModel: vi.fn(() => Promise.resolve()),+ reidentifyModel: vi.fn<(key: string) => Promise<ModelConfig>>(),+}));vi.mock('@features/models/data/api', async (importOriginal) => ({...(await importOriginal<object>()),deleteModel: api.deleteModel,+ reidentifyModel: api.reidentifyModel,}));vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string, options?: { name?: string }) => `${key}${options?.name ?? ''}` }),+ useTranslation: () => ({+ t: (key: string, options?: { name?: string; scale?: number }) =>+ `${key}${options?.name ?? ''}${options?.scale ?? ''}`,+ }),}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -104,3 +112,144 @@ describe('models DetailPane', () => {expect(frames).not.toHaveLength(0);});});++describe('models DetailPane for a model installed before the probe recorded a fact', () => {+ const UNIDENTIFIED_LLLITE = {+ ...VAE,+ base: 'anima',+ cond_in_channels: null,+ hash: 'hash-lllite',+ key: 'lllite-1',+ name: 'Anima LLLite',+ path: '/models/lllite.safetensors',+ source: '/models/lllite.safetensors',+ type: 'controlnet',+ } as ModelConfig;+ const adapter = (canManageModels: boolean): ModelsUiAdapter => ({+ canManageModels,+ enableModelDescriptions: true,+ installInPlace: true,+ isProjectActive: () => true,+ managerProjectId: null,+ schedulerPolicy: NO_SCHEDULER_POLICY,+ setInstallInPlace: () => undefined,+ });+ let host: HTMLDivElement;+ let root: Root;++ const UNSCALED_UPSCALER = {+ ...VAE,+ base: 'any',+ hash: 'hash-upscaler',+ key: 'upscaler-1',+ name: 'RealESRGAN x4',+ path: '/models/realesrgan.safetensors',+ scale: null,+ source: '/models/realesrgan.safetensors',+ type: 'spandrel_image_to_image',+ } as ModelConfig;+ const render = async (canManageModels: boolean, model: ModelConfig = UNIDENTIFIED_LLLITE) => {+ accountLifecycle.activate('detail-pane-lllite', ':user:detail-pane-lllite');+ setModelsSnapshotForTests({ models: [model], status: 'loaded' });+ openModelDetail(model.key);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <ModelsUiProvider adapter={adapter(canManageModels)}>+ <DetailPane />+ </ModelsUiProvider>+ </ChakraProvider>+ )+ );+ };+ const reidentifyButton = () =>+ [...host.querySelectorAll('button')].find((button) => button.textContent === 'models.reidentify');+ const openConfirm = async () => {+ await act(() => userEvent.click(reidentifyButton()!));+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');+ return document.querySelector<HTMLElement>('[role="alertdialog"]')!;+ };+ const dialogButton = (dialog: HTMLElement, label: string) =>+ [...dialog.querySelectorAll('button')].find((button) => button.textContent === label)!;++ beforeEach(() => {+ api.reidentifyModel.mockReset();+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+ });++ it('explains the unknown type and re-identifies only after a confirm that names the reset', async () => {+ api.reidentifyModel.mockResolvedValue({ ...UNIDENTIFIED_LLLITE, cond_in_channels: 3 });+ await render(true);++ expect(host.textContent).toContain('models.adapterTypeUnknown');+ expect(host.textContent).not.toContain('models.reidentifyAskAdmin');++ const cancelled = await openConfirm();+ expect(cancelled.textContent).toContain('models.reidentifyConfirmBody');+ await act(() => userEvent.click(dialogButton(cancelled, 'Cancel')));+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();+ expect(api.reidentifyModel).not.toHaveBeenCalled();+ // Cancel returns focus to the button that opened the dialog.+ expect(document.activeElement).toBe(reidentifyButton());++ const confirmed = await openConfirm();+ await act(() => userEvent.click(dialogButton(confirmed, 'models.reidentify')));++ await expect.poll(() => getModelsSnapshot().modelsByKey.get(UNIDENTIFIED_LLLITE.key)?.cond_in_channels).toBe(3);+ expect(api.reidentifyModel).toHaveBeenCalledExactlyOnceWith(UNIDENTIFIED_LLLITE.key, expect.anything());+ expect(host.textContent).not.toContain('models.adapterTypeUnknown');+ // The notice and its button are gone; focus lands on the model's actions rather than the page body.+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();+ await expect.poll(() => document.activeElement).toBe(host.querySelector('[aria-label="models.actions"]'));+ });++ it('tells users who cannot manage models to ask an administrator, without the button', async () => {+ await render(false);++ expect(host.textContent).toContain('models.adapterTypeUnknown');+ expect(host.textContent).toContain('models.reidentifyAskAdmin');+ expect(reidentifyButton()).toBeUndefined();+ });++ it('shows an upscaler’s recorded native scale, with no notice', async () => {+ await render(true, { ...UNSCALED_UPSCALER, scale: 4 } as ModelConfig);++ expect(host.textContent).toContain('models.nativeScale');+ expect(host.textContent).toContain('models.nativeScaleValue4');+ expect(host.textContent).not.toContain('models.nativeScaleUnknown');+ expect(reidentifyButton()).toBeUndefined();+ });++ it('explains an unrecorded native scale and records it on a confirmed re-identify', async () => {+ api.reidentifyModel.mockResolvedValue({ ...UNSCALED_UPSCALER, scale: 4 } as ModelConfig);+ await render(true, UNSCALED_UPSCALER);++ expect(host.textContent).toContain('models.nativeScaleUnknown');+ expect(host.textContent).not.toContain('models.nativeScaleValue');++ const dialog = await openConfirm();+ expect(dialog.textContent).toContain('models.reidentifyConfirmBody');+ await act(() => userEvent.click(dialogButton(dialog, 'models.reidentify')));++ await expect.poll(() => getModelsSnapshot().modelsByKey.get(UNSCALED_UPSCALER.key)?.scale).toBe(4);+ expect(api.reidentifyModel).toHaveBeenCalledExactlyOnceWith(UNSCALED_UPSCALER.key, expect.anything());+ expect(host.textContent).not.toContain('models.nativeScaleUnknown');+ expect(host.textContent).toContain('models.nativeScaleValue4');+ });++ it('tells a user who cannot manage models to ask about an unrecorded scale', async () => {+ await render(false, UNSCALED_UPSCALER);++ expect(host.textContent).toContain('models.nativeScaleUnknown');+ expect(host.textContent).toContain('models.reidentifyAskAdmin');+ expect(reidentifyButton()).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsxindex 6a4fa54b15..6fc2c4ab9d 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx@@ -15,7 +15,7 @@ import { Scrollable, Tabs } from '@platform/ui';import { ManagerDetailHeader } from '@platform/ui/ManagerLayout';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { BoxIcon, KeyRoundIcon, PlusIcon } from 'lucide-react';-import { useCallback, useState } from 'react';+import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';/** The tabbed detail pane: selected model, Add Models and API Keys. The install queue is the layout's footer. */@@ -81,6 +81,26 @@ const DetailTab = ({ modelKey }: { modelKey: string | null }) => {// Owned above the keyed detail: a delete unmounts it while this dialog is still animating out.const [pendingAction, setPendingAction] = useState<PendingModelAction>(null);const handleDeleted = useCallback(() => updateModelsUi({ activeModelKey: null }), []);+ const detailRef = useRef<HTMLDivElement | null>(null);+ const confirmOpenerRef = useRef<{ element: HTMLElement | null; kind: NonNullable<PendingModelAction>['kind'] }>({+ element: null,+ kind: 'delete',+ });+ const requestConfirm = useCallback((pending: NonNullable<PendingModelAction>) => {+ confirmOpenerRef.current = {+ element: document.activeElement instanceof HTMLElement ? document.activeElement : null,+ kind: pending.kind,+ };+ setPendingAction(pending);+ }, []);+ // A confirmed re-identify clears the notice whose button opened the dialog; focus the model's actions instead.+ const getConfirmFinalFocus = useCallback(() => {+ const { element, kind } = confirmOpenerRef.current;+ if (kind !== 'reidentify' || element?.isConnected) {+ return null;+ }+ return detailRef.current?.querySelector<HTMLElement>('[data-model-actions-trigger]') ?? null;+ }, []);return (<>@@ -95,11 +115,12 @@ const DetailTab = ({ modelKey }: { modelKey: string | null }) => {</Text></Flex>) : (- <Scrollable h="full" label={t('models.details')} minH="0" p="3">- <ModelDetail key={modelKey} modelKey={modelKey} onRequestConfirm={setPendingAction} />+ <Scrollable h="full" label={t('models.details')} minH="0" p="3" viewportRef={detailRef}>+ <ModelDetail key={modelKey} modelKey={modelKey} onRequestConfirm={requestConfirm} /></Scrollable>)}<ModelActionConfirmDialog+ finalFocusEl={getConfirmFinalFocus}pending={pendingAction}onClose={() => setPendingAction(null)}onDeleted={handleDeleted}diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsxindex bd7fc65ee5..55ceed7dbf 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelActionsMenu.tsx@@ -17,7 +17,7 @@ import { useTranslation } from 'react-i18next';export type ModelActionsModel = Pick<ModelConfig, 'base' | 'format' | 'key' | 'name' | 'type'>;-export type PendingModelAction = { kind: 'convert' | 'delete'; model: ModelActionsModel } | null;+export type PendingModelAction = { kind: 'convert' | 'delete' | 'reidentify'; model: ModelActionsModel } | null;export const ModelActionMenuItems = ({extraItems,@@ -70,7 +70,20 @@ export const ModelActionMenuItems = ({);};-/** Confirms whichever destructive action is pending (convert replaces the original checkpoint file). */+/**+ * Confirms whichever destructive action is pending: convert replaces the original checkpoint file; re-identify resets+ * the model's custom variant and default settings.+ */+const CONFIRM_COPY = {+ convert: { bodyKey: 'models.convertBody', confirmKey: 'models.convert', titleKey: 'models.convertToDiffusers' },+ delete: { bodyKey: 'models.deleteBody', confirmKey: 'models.deleteModel', titleKey: 'models.deleteModel' },+ reidentify: {+ bodyKey: 'models.reidentifyConfirmBody',+ confirmKey: 'models.reidentify',+ titleKey: 'models.reidentifyConfirmTitle',+ },+} as const;+export const ModelActionConfirmDialog = ({finalFocusEl,onClose,@@ -85,19 +98,16 @@ export const ModelActionConfirmDialog = ({pending: PendingModelAction;}) => {const { t } = useTranslation();- const { convert, remove } = useModelActions();+ const { convert, reidentify, remove } = useModelActions();+ const copy = CONFIRM_COPY[pending?.kind ?? 'delete'];return (<ConfirmDialog- body={- pending?.kind === 'convert'- ? t('models.convertBody', { name: pending.model.name })- : t('models.deleteBody', { name: pending?.model.name ?? '' })- }- confirmLabel={pending?.kind === 'convert' ? t('models.convert') : t('models.deleteModel')}+ body={t(copy.bodyKey, { name: pending?.model.name ?? '' })}+ confirmLabel={t(copy.confirmKey)}finalFocusEl={finalFocusEl}isOpen={pending !== null}- title={pending?.kind === 'convert' ? t('models.convertToDiffusers') : t('models.deleteModel')}+ title={t(copy.titleKey)}onClose={onClose}onConfirm={async () => {if (!pending) {@@ -109,6 +119,11 @@ export const ModelActionConfirmDialog = ({return;}+ if (pending.kind === 'reidentify') {+ await reidentify(pending.model);+ return;+ }+if (await remove(pending.model)) {onDeleted?.();}diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsxindex 30c221117d..d75b050071 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx@@ -27,7 +27,7 @@ export interface ModelFilterSortOption<Field extends ModelSortField = ModelSortFlabelKey: string;}-/** The one source of sort options; derive narrower menus by filtering. */+/** The installed library's sort options; the starter list names its own (see `StarterFilterMenu`). */export const SORT_FIELD_OPTIONS: readonly ModelFilterSortOption[] = [{ field: 'default', labelKey: 'models.sort.default' },{ field: 'name', labelKey: 'models.sort.name' },diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.test.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.test.tsindex 5427c87d93..e4a6a76882 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.test.ts@@ -1,8 +1,13 @@import type { ModelConfig, StarterModel } from '@features/models/core/types';+import type { ModelsSnapshot } from '@features/models/data/modelsStore';import { describe, expect, it } from 'vitest';-import { findInstalledStarterModelKey } from './useInstalledSources';+import {+ findInstalledLocalPathKey,+ findInstalledStarterModelKey,+ selectInstalledSourceKeys,+} from './useInstalledSources';const model = (overrides: Partial<ModelConfig>): ModelConfig =>({@@ -40,3 +45,33 @@ describe('findInstalledStarterModelKey', () => {expect(findInstalledStarterModelKey(starter, new Map(), models.slice(0, 2))).toBeNull();});});++describe('findInstalledLocalPathKey', () => {+ const installedKeys = (models: ModelConfig[], modelsDir: string | null = null) =>+ selectInstalledSourceKeys({ models, modelsDir } as ModelsSnapshot);++ it('finds a model recorded with forward slashes from a Windows scan path', () => {+ const keys = installedKeys([+ model({ key: 'lora', path: 'C:/Users/me/loras/x.safetensors', source: 'C:/Users/me/loras/x.safetensors' }),+ ]);++ expect(findInstalledLocalPathKey('C:\\Users\\me\\loras\\x.safetensors', keys)).toBe('lora');+ expect(findInstalledLocalPathKey('c:\\users\\ME\\loras\\x.safetensors', keys)).toBe('lora');+ });++ it('finds a managed model by its path under the models folder', () => {+ const keys = installedKeys(+ [model({ key: 'managed', path: 'loras/x.safetensors', source: 'https://example/x' })],+ 'C:/invokeai/models'+ );++ expect(findInstalledLocalPathKey('C:\\invokeai\\models\\loras\\x.safetensors', keys)).toBe('managed');+ });++ it('keeps POSIX paths case-sensitive', () => {+ const keys = installedKeys([model({ key: 'posix', path: '/a/X.safetensors', source: '/a/X.safetensors' })]);++ expect(findInstalledLocalPathKey('/a/X.safetensors', keys)).toBe('posix');+ expect(findInstalledLocalPathKey('/a/x.safetensors', keys)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.tsindex c6e4a3ba62..3a1b214863 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/useInstalledSources.ts@@ -1,7 +1,7 @@import type { ModelConfig, StarterModel } from '@features/models/core/types';import type { ModelsSnapshot } from '@features/models/data/modelsStore';-import { resolveModelAbsolutePath } from '@features/models/core/schemas';+import { canonicalLocalPath, isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';import { useModelsSelector } from '@features/models/data/modelsStore';const areMapsEqual = (left: ReadonlyMap<string, string>, right: ReadonlyMap<string, string>): boolean =>@@ -12,13 +12,19 @@ let lastModels: ModelsSnapshot['models'] | null = null;let lastModelsDir: string | null = null;let lastSources: ReadonlyMap<string, string> = new Map<string, string>();-const selectInstalledSourceKeys = (snapshot: ModelsSnapshot): ReadonlyMap<string, string> => {+export const selectInstalledSourceKeys = (snapshot: ModelsSnapshot): ReadonlyMap<string, string> => {if (snapshot.models !== lastModels || snapshot.modelsDir !== lastModelsDir) {const sources = new Map<string, string>();for (const model of snapshot.models) {sources.set(model.source, model.key);- sources.set(resolveModelAbsolutePath(model.path, snapshot.modelsDir), model.key);+ // Local paths are indexed in canonical form too, so callers can match any spelling the server reports.+ if (isAbsoluteModelPath(model.source)) {+ sources.set(canonicalLocalPath(model.source), model.key);+ }+ const resolvedPath = resolveModelAbsolutePath(model.path, snapshot.modelsDir);+ sources.set(resolvedPath, model.key);+ sources.set(canonicalLocalPath(resolvedPath), model.key);}lastModels = snapshot.models;@@ -36,6 +42,12 @@ const selectInstalledSourceKeys = (snapshot: ModelsSnapshot): ReadonlyMap<stringexport const useInstalledSourceKeys = (): ReadonlyMap<string, string> =>useModelsSelector(selectInstalledSourceKeys, areMapsEqual);+/** The installed model at a local path in any spelling: a Windows scan reports `C:\…` for a model recorded as `C:/…`. */+export const findInstalledLocalPathKey = (+ path: string,+ installedSourceKeys: ReadonlyMap<string, string>+): string | null => installedSourceKeys.get(canonicalLocalPath(path)) ?? null;+const starterIdentity = (base: string, type: string, name: string): string => `${base}\u0000${type}\u0000${name}`;/**diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.tsindex 02186c124a..3534407cc9 100644--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.test.ts@@ -39,44 +39,45 @@ describe('models ui store', () => {// Clear prior scan, repo, and bundle results so the requested starter catalog remains visible.expect(snapshot.activeTab).toBe('add');- expect(store.getAddModelsSeed()).toBe('Juggernaut XL');+ expect(snapshot.addModelsQuery).toBe('Juggernaut XL');expect(snapshot.hfLookup).toBeNull();expect(snapshot.scan).toBeNull();expect(snapshot.selectedBundleName).toBeNull();});- it('hands the Add Models seed over exactly once', async () => {+ it('keeps the Add Models box text until a search request replaces it or the account changes', async () => {const store = await import('./uiStore');+ const { accountLifecycle } = await import('@platform/state/accountLifecycle');+ accountLifecycle.activate('account-a');+ const query = () => store.getModelsUiSnapshotForTests().addModelsQuery;- expect(store.getAddModelsSeed()).toBe('');+ expect(query()).toBe('');+ store.setAddModelsQuery('/home/me/loras');+ store.openModelManagerTab('keys');+ expect(query()).toBe('/home/me/loras');store.requestAddModelsSearch('Juggernaut XL');+ expect(query()).toBe('Juggernaut XL');- // Reading is pure — StrictMode double-invokes the initializer that reads it.- expect(store.getAddModelsSeed()).toBe('Juggernaut XL');- expect(store.getAddModelsSeed()).toBe('Juggernaut XL');-- store.clearAddModelsSeeds();-- // The next time Add Models opens on its own, the box is empty again.- expect(store.getAddModelsSeed()).toBe('');+ accountLifecycle.activate('account-b');+ expect(query()).toBe('');});- it('hands the starter type-filter seed over exactly once, and the two seeds displace each other', async () => {+ it('hands the starter type-filter seed over exactly once, clearing a search that would hide it', async () => {const store = await import('./uiStore');+ const query = () => store.getModelsUiSnapshotForTests().addModelsQuery;+ store.requestAddModelsSearch('Juggernaut XL');store.requestAddModelsTypeFilter('text_llm');expect(store.getModelsUiSnapshotForTests().activeTab).toBe('add');expect(store.getAddModelsTypeSeed()).toBe('text_llm');- expect(store.getAddModelsSeed()).toBe('');+ expect(query()).toBe('');store.requestAddModelsSearch('Juggernaut XL');expect(store.getAddModelsTypeSeed()).toBeNull();store.requestAddModelsTypeFilter('llava_onevision');- expect(store.getAddModelsSeed()).toBe('');-- store.clearAddModelsSeeds();+ store.clearAddModelsTypeSeed();expect(store.getAddModelsTypeSeed()).toBeNull();});diff --git a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts b/invokeai/frontend/webv2/src/features/models/ui/uiStore.tsindex 3237bbba8c..c41e983a48 100644--- a/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/uiStore.ts@@ -19,8 +19,8 @@ export interface HFLookupState {export interface ModelsUiSnapshot {activeTab: ModelManagerTab;- /** Consume Add Models search once on mount; null means no seed, distinct from a seeded empty string. */- addModelsSeed: string | null;+ /** Add Models' search / URL / path box, kept while the manager is closed or another tab shows. */+ addModelsQuery: string;/** One-shot starter type filter for links identifying a missing model kind rather than a name. */addModelsTypeSeed: ModelTaxonomyType | null;/** Model focused in the manager library's detail pane. */@@ -55,7 +55,7 @@ export interface ModelsUiSnapshot {const createInitialModelsUiSnapshot = (): ModelsUiSnapshot => ({activeModelKey: null,activeTab: 'add',- addModelsSeed: null,+ addModelsQuery: '',addModelsTypeSeed: null,detailOpen: null,filters: { ...DEFAULT_LIBRARY_FILTERS },@@ -178,13 +178,13 @@ export const openAddModelsWithBundle = (bundleName: string): void => {};/**- * Seed Add Models search for external requirement links and clear scan/repo results that would hide the starter- * catalog.+ * Search Add Models for external requirement links, replacing whatever the box held, and clear scan/repo results that+ * would hide the starter catalog.*/export const requestAddModelsSearch = (query: string): void => {updateModelsUi({activeTab: 'add',- addModelsSeed: query,+ addModelsQuery: query,addModelsTypeSeed: null,hfLookup: null,queueMaximized: false,@@ -197,7 +197,8 @@ export const requestAddModelsSearch = (query: string): void => {export const requestAddModelsTypeFilter = (typeFilter: ModelTaxonomyType): void => {updateModelsUi({activeTab: 'add',- addModelsSeed: null,+ // Old search text would hide the very models the link asks for.+ addModelsQuery: '',addModelsTypeSeed: typeFilter,hfLookup: null,queueMaximized: false,@@ -206,18 +207,19 @@ export const requestAddModelsTypeFilter = (typeFilter: ModelTaxonomyType): void});};-/** Reads a pending seed without consuming it — safe to call from a `useState` initializer, which StrictMode double-invokes. */-export const getAddModelsSeed = (): string => store.getSnapshot().addModelsSeed ?? '';+export const setAddModelsQuery = (addModelsQuery: string): void => {+ updateModelsUi({ addModelsQuery });+};-/** Pure read, like {@link getAddModelsSeed}. */+/** Reads the pending type seed without consuming it, so a `useState` initializer StrictMode runs twice sees it. */export const getAddModelsTypeSeed = (): ModelTaxonomyType | null => store.getSnapshot().addModelsTypeSeed;-/** Consume seeds silently; subscribers do not read them and the mounting reader already captured them. */-export const clearAddModelsSeeds = (): void => {+/** Consume the type seed silently; subscribers do not read it and the mounting reader already captured it. */+export const clearAddModelsTypeSeed = (): void => {const snapshot = store.getSnapshot();- if (snapshot.addModelsSeed !== null || snapshot.addModelsTypeSeed !== null) {- store.setSnapshotSilently({ ...snapshot, addModelsSeed: null, addModelsTypeSeed: null });+ if (snapshot.addModelsTypeSeed !== null) {+ store.setSnapshotSilently({ ...snapshot, addModelsTypeSeed: null });}};diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.jsonindex 96b3e4a9e2..45c8d28ef5 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json@@ -1416,6 +1416,21 @@"vae"]},+ "spandrel_image_to_image": {+ "inputs": [],+ "literalInputs": {+ "image": [],+ "image_to_image_model": [],+ "is_intermediate": [+ false+ ],+ "metadata": [],+ "use_cache": [+ false+ ]+ },+ "outputs": []+ },"spandrel_image_to_image_autoscale": {"inputs": [],"literalInputs": {@@ -1425,12 +1440,16 @@"image": [],"image_to_image_model": [],"is_intermediate": [+ false,true],+ "metadata": [],"scale": [+ 2,4],"use_cache": [+ false,true]},diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.tsindex 819acfeac8..8ff7ed677f 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts@@ -7,12 +7,13 @@ import { describe, expect, it } from 'vitest';import type { TileControlNetModelConfig, UpscaleWidgetValues } from './types';import {+ compileModelOnlyUpscaleGraph,compileUpscaleGraph,getUpscaleControlNetValues,getUpscaleDenoisingStart,getZImageTileControlValues,} from './graph';-import { createDefaultUpscaleWidgetValues } from './settings';+import { createDefaultUpscaleWidgetValues, normalizeUpscaleWidgetValues } from './settings';const model = (key: string, type: string, base: string, name = key): ModelConfig => ({base,@@ -130,6 +131,145 @@ describe('compileUpscaleGraph', () => {expect(graph.nodes.core_metadata?.rand_device).toBe('xpu');});++ it('refines values saved before modes existed, whatever source metadata is offered', () => {+ const { mode: _mode, ...saved } = createValues('sd-1');+ const values = normalizeUpscaleWidgetValues(saved) as UpscaleWidgetValues;+ const nodes = compileUpscaleGraph(values, 'gallery', { useCpuNoise: false }, 'cuda', { prompt: 'source' })+ .backendGraph.nodes;++ expect(nodes.tiled_multidiffusion_denoise_latents).toBeDefined();+ expect(nodes.core_metadata).toMatchObject({ creativity: 0, type: 'core_metadata' });+ expect(nodes.core_metadata).not.toHaveProperty('prompt');+ });+});++describe('model-only upscale graph', () => {+ const image = { height: 101, image_name: 'input.png', width: 203 };+ const upscaler = (scale: number | null) => ({+ ...model('ultrasharp', 'spandrel_image_to_image', 'any', '4x-UltraSharp'),+ scale,+ type: 'spandrel_image_to_image' as const,+ });+ const UPSCALER_ID = {+ base: 'any',+ hash: 'ultrasharp-hash',+ key: 'ultrasharp',+ name: '4x-UltraSharp',+ type: 'spandrel_image_to_image',+ };+ const SOURCE_METADATA = {+ height: 512,+ metadata_version: 1,+ model: { key: 'legacy-main', model_name: 'old shape' },+ positive_prompt: 'a lighthouse',+ seed: 42,+ upscale_initial_image: { height: 1, image_name: 'older.png', width: 1 },+ upscale_model: { key: 'older-upscaler' },+ upscale_scale: 8,+ width: 768,+ };++ it('runs the upscaler alone at the widget Scale, with no main model', () => {+ const values = {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: image,+ mode: 'model-only' as const,+ scale: 2,+ upscaleModel: upscaler(4),+ };++ for (const destination of ['gallery', 'canvas'] as const) {+ const compiled = compileUpscaleGraph(values, destination, { useCpuNoise: false }, 'cuda', null);+ const { edges, nodes } = compiled.backendGraph;++ expect(Object.keys(nodes).sort()).toEqual(['negative_prompt', 'positive_prompt', 'seed', 'upscale_output']);+ expect(edges).toEqual([]);+ expect(compiled.outputNodeId).toBe('upscale_output');+ expect(nodes.upscale_output).toMatchObject({+ fit_to_multiple_of_8: true,+ image: { image_name: 'input.png' },+ image_to_image_model: UPSCALER_ID,+ is_intermediate: destination === 'canvas',+ scale: 2,+ type: 'spandrel_image_to_image_autoscale',+ use_cache: false,+ });+ }+ });++ it('runs an upscaler of unknown native scale once, as a plain pass', () => {+ const output = compileModelOnlyUpscaleGraph({+ destination: 'gallery',+ image,+ scale: 'native',+ sourceMetadata: null,+ upscaleModel: upscaler(null),+ }).backendGraph.nodes.upscale_output;++ expect(output).toMatchObject({ is_intermediate: false, type: 'spandrel_image_to_image', use_cache: false });+ expect(output).not.toHaveProperty('scale');+ expect(output).not.toHaveProperty('fit_to_multiple_of_8');+ });++ it('sizes a recorded native scale as that Scale, so the menu and the widget give the same result', () => {+ const compile = (scale: number | 'native') =>+ compileModelOnlyUpscaleGraph({+ destination: 'gallery',+ image,+ scale,+ sourceMetadata: null,+ upscaleModel: upscaler(4),+ }).backendGraph.nodes.upscale_output;++ expect(compile('native')).toEqual(compile(4));+ expect(compile('native')).toMatchObject({+ fit_to_multiple_of_8: true,+ scale: 4,+ type: 'spandrel_image_to_image_autoscale',+ });+ });++ it("copies the source image's metadata verbatim, replacing only what it says about an earlier upscale", () => {+ const metadata = compileModelOnlyUpscaleGraph({+ destination: 'gallery',+ image,+ scale: 2,+ sourceMetadata: SOURCE_METADATA,+ upscaleModel: upscaler(4),+ }).backendGraph.nodes.upscale_output?.metadata;++ expect(metadata).toEqual({+ height: 512,+ metadata_version: 1,+ model: { key: 'legacy-main', model_name: 'old shape' },+ positive_prompt: 'a lighthouse',+ seed: 42,+ upscale_initial_image: { height: 101, image_name: 'input.png', width: 203 },+ upscale_model: UPSCALER_ID,+ upscale_scale: 2,+ width: 768,+ });+ });++ it('records only the upscale for a source with no metadata, and no scale when the model never recorded one', () => {+ const metadata = (scale: number | null) =>+ compileModelOnlyUpscaleGraph({+ destination: 'gallery',+ image,+ scale: 'native',+ sourceMetadata: scale === null ? SOURCE_METADATA : null,+ upscaleModel: upscaler(scale),+ }).backendGraph.nodes.upscale_output?.metadata;++ expect(metadata(4)).toEqual({+ upscale_initial_image: { height: 101, image_name: 'input.png', width: 203 },+ upscale_model: UPSCALER_ID,+ upscale_scale: 4,+ });+ expect(metadata(null)).not.toHaveProperty('upscale_scale');+ expect(metadata(null)).toMatchObject({ positive_prompt: 'a lighthouse', upscale_model: UPSCALER_ID });+ });});const createFluxValues = (options: { withEncoders?: boolean } = {}) => {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex bba85261cc..f5a3cbaab0 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -2,6 +2,7 @@ import type {BackendGraphContract,BackendInvocationContract,GenerationProjectSettings,+ ImageWithDims,MainModelConfig,ResultDestination,} from '@features/generation/contracts';@@ -20,11 +21,12 @@ import {import { isBundledMainForBase } from '@features/generation/settings';import type { UpscaleBase, UpscaleIndexClipping } from './settings';-import type { CompiledUpscaleGraph, UpscaleWidgetValues } from './types';+import type { CompiledUpscaleGraph, SpandrelModelConfig, UpscaleWidgetValues } from './types';import {activeUpscaleComponents,coerceUpscaleScheduler,+ getSpandrelNativeScale,getUpscaleValidationReasons,upscaleArchitectureFor,upscaleDenoiseDimension,@@ -965,11 +967,91 @@ const UPSCALE_PATH_BUILDERS = {'z-image': buildZImageUpscalePath,} satisfies Record<UpscaleBase, UpscalePathBuilder>;+export interface ModelOnlyUpscaleRequest {+ image: ImageWithDims;+ upscaleModel: SpandrelModelConfig;+ /**+ * A Scale runs the upscaler until it reaches it; `'native'` runs the model once, at its own scale, sized as that Scale+ * would be when it is recorded and left unsized when it is not.+ */+ scale: number | 'native';+ destination: ResultDestination;+ /** The source image's metadata, copied into the result's; null when the source has none. */+ sourceMetadata: Record<string, unknown> | null;+}++/**+ * The upscaler alone, with no main model or detail pass: the Upscale widget's Model only mode at its Scale, and the+ * image menu's one-click upscale at one of its factors or the model's native scale.+ *+ * The result carries the source image's metadata, so Recall and Remix restore how the source was made, plus what the+ * upscale did. It sits on the output node as a literal rather than in a `core_metadata` node, which would validate the+ * copied keys against today's fields (an older image's model record fails that) and stamp today's `metadata_version`+ * over the source's.+ */+export const compileModelOnlyUpscaleGraph = ({+ destination,+ image,+ scale,+ sourceMetadata,+ upscaleModel,+}: ModelOnlyUpscaleRequest): CompiledUpscaleGraph => {+ const graph: BackendGraphContract = { edges: [], id: 'upscale-graph', nodes: {} };+ // The queue's generate submission writes the batch's prompts and seed into these; nothing in this graph reads them.+ addNode(graph, { id: 'positive_prompt', type: 'string' });+ addNode(graph, { id: 'negative_prompt', type: 'string' });+ addNode(graph, { id: 'seed', type: 'integer' });++ const upscaleScale = scale === 'native' ? getSpandrelNativeScale(upscaleModel) : scale;+ // A source that was itself upscaled names its own upscale; none of those keys may survive into this one.+ const {+ upscale_initial_image: _initialImage,+ upscale_model: _model,+ upscale_scale: _scale,+ ...copiedMetadata+ } = sourceMetadata ?? {};+ const metadata = {+ ...copiedMetadata,+ upscale_initial_image: { height: image.height, image_name: image.image_name, width: image.width },+ upscale_model: toModelIdentifier(upscaleModel),+ ...(upscaleScale === null ? {} : { upscale_scale: upscaleScale }),+ };++ addNode(graph, {+ id: 'upscale_output',+ image: { image_name: image.image_name },+ image_to_image_model: toModelIdentifier(upscaleModel),+ is_intermediate: destination === 'canvas',+ metadata,+ // Matches the Refine graph's first pass, so both modes size a result alike. Only an upscaler of unknown native+ // scale runs a plain pass: there is no factor to give the autoscale node.+ ...(upscaleScale === null+ ? { type: 'spandrel_image_to_image' }+ : { fit_to_multiple_of_8: true, scale: upscaleScale, type: 'spandrel_image_to_image_autoscale' }),+ // A cached output would hand back the earlier result's image instead of a new one.+ use_cache: false,+ });++ return {+ backendGraph: graph,+ graph: toGraphContract(graph, `${upscaleModel.name} upscale`),+ negativePromptNodeId: 'negative_prompt',+ outputNodeId: 'upscale_output',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ };+};++/**+ * `sourceMetadata` is read only in Model only mode: the input image's metadata, which that mode copies into the+ * result's.+ */export const compileUpscaleGraph = (settings: UpscaleWidgetValues,destination: ResultDestination,projectSettings: UpscaleProjectSettings,- randDevice = projectSettings.useCpuNoise ? 'cpu' : 'cuda'+ randDevice = projectSettings.useCpuNoise ? 'cpu' : 'cuda',+ sourceMetadata: Record<string, unknown> | null = null): CompiledUpscaleGraph => {const reasons = getUpscaleValidationReasons(settings);@@ -977,6 +1059,20 @@ export const compileUpscaleGraph = (throw new Error(reasons[0]);}+ if (settings.mode === 'model-only') {+ if (!settings.inputImage || !settings.upscaleModel) {+ throw new Error('Upscale settings are incomplete.');+ }++ return compileModelOnlyUpscaleGraph({+ destination,+ image: settings.inputImage,+ scale: settings.scale,+ sourceMetadata,+ upscaleModel: settings.upscaleModel,+ });+ }+const { inputImage, model, upscaleModel } = settings;if (!inputImage || !model || !upscaleModel) {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.tsindex ee67a52626..4d0a3a1951 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts@@ -12,6 +12,11 @@ import { describe, expect, it } from 'vitest';import {clearDeletedUpscaleInput,createDefaultUpscaleWidgetValues,+ getModelOnlyUpscaleFactors,+ getModelOnlyUpscalePlan,+ isUpscaleBatchCountFixed,+ resolveUpscaleSubmissionValues,+ getSpandrelNativeScale,getUpscaleOutputDimensions,getUpscaleValidationReasons,normalizeUpscaleWidgetValues,@@ -110,7 +115,12 @@ describe('upscale settings', () => {scale: 4,tileSize: 1024,});- expect(getUpscaleOutputDimensions({ height: 101, width: 203 }, 2.5, MODELS[0] as never)).toEqual({+ expect(+ getUpscaleOutputDimensions(+ { height: 101, width: 203 },+ { mode: 'refine', model: MODELS[0] as never, scale: 2.5, upscaleModel: null }+ )+ ).toEqual({height: 248,width: 504,});@@ -731,9 +741,132 @@ describe('upscaleDenoiseDimension', () => {it("shows the size the result comes out at, which a 16px pass makes smaller than Spandrel's", () => {// 1004 at 2x: Spandrel gives 2008, which FLUX.1 and Z-Image resize to 2000.const widths = ['sd-1', 'flux', 'z-image', 'anima'].map(- (base) => getUpscaleOutputDimensions({ height: 1004, width: 1004 }, 2, model(base, 'main', base) as never).width+ (base) =>+ getUpscaleOutputDimensions(+ { height: 1004, width: 1004 },+ { mode: 'refine', model: model(base, 'main', base) as never, scale: 2, upscaleModel: null }+ ).width);expect(widths).toEqual([2008, 2000, 2000, 2008]);});});++describe('upscale model-only mode', () => {+ const upscaler = (scale?: number | null) => ({+ ...model('ultrasharp', 'spandrel_image_to_image', 'any', '4x-UltraSharp'),+ type: 'spandrel_image_to_image' as const,+ ...(scale === undefined ? {} : { scale }),+ });+ const image = { height: 101, image_name: 'source.png', width: 203 };+ const modelOnly = (overrides = {}) => ({+ ...createDefaultUpscaleWidgetValues(),+ inputImage: image,+ mode: 'model-only' as const,+ upscaleModel: upscaler(4),+ ...overrides,+ });++ it('opens projects saved before modes, and anything unknown, in Refine', () => {+ expect(createDefaultUpscaleWidgetValues().mode).toBe('refine');+ expect(normalizeUpscaleWidgetValues({})?.mode).toBe('refine');+ expect(normalizeUpscaleWidgetValues({ mode: 'upscale-only' })?.mode).toBe('refine');+ expect(normalizeUpscaleWidgetValues({ mode: 'model-only' })?.mode).toBe('model-only');+ });++ it('is ready with an image and an upscaler alone, even before the served table loads', () => {+ resetArchitectureCapabilities();++ try {+ expect(getUpscaleValidationReasons(modelOnly({ model: null, tileControlnetModel: null, vae: null }))).toEqual([]);+ } finally {+ seedArchitectureCapabilities();+ }+ });++ it('names only what the upscaler itself lacks', () => {+ expect(+ getUpscaleValidationReasons(modelOnly({ inputImage: null, model: null, scale: 32, upscaleModel: null }), MODELS)+ ).toEqual([+ 'Upscale needs an input image. Upload one or send one from Gallery.',+ 'Upscale needs a Spandrel image-to-image model.',+ 'Scale must be between 1 and 16.',+ ]);+ expect(getUpscaleValidationReasons(modelOnly({ steps: 0, cfgScale: 99 }), [upscaler(4)])).toEqual([]);+ expect(getUpscaleValidationReasons(modelOnly(), MODELS)).toEqual(['4x-UltraSharp is no longer installed.']);+ });++ it('reads a recorded native scale and treats anything else as unknown', () => {+ expect(getSpandrelNativeScale(upscaler(4))).toBe(4);+ expect(getSpandrelNativeScale(upscaler(1))).toBe(1);+ expect(getSpandrelNativeScale(upscaler(null))).toBeNull();+ expect(getSpandrelNativeScale(upscaler())).toBeNull();+ expect(getSpandrelNativeScale(upscaler(0))).toBeNull();+ expect(getSpandrelNativeScale(null)).toBeNull();+ });++ it('plans the passes the autoscale node runs and whether it resizes after them', () => {+ expect(getModelOnlyUpscalePlan(4, 2)).toEqual({ kind: 'passes', passes: 1, resizes: true });+ expect(getModelOnlyUpscalePlan(4, 4)).toEqual({ kind: 'passes', passes: 1, resizes: false });+ expect(getModelOnlyUpscalePlan(4, 16)).toEqual({ kind: 'passes', passes: 2, resizes: false });+ expect(getModelOnlyUpscalePlan(2, 4)).toEqual({ kind: 'passes', passes: 2, resizes: false });+ expect(getModelOnlyUpscalePlan(2, 5)).toEqual({ kind: 'passes', passes: 3, resizes: true });+ expect(getModelOnlyUpscalePlan(1, 4)).toEqual({ kind: 'no-enlarge' });+ expect(getModelOnlyUpscalePlan(null, 4)).toBeNull();+ });++ it('offers one-click factors of 1.5x, 2x and the native scale, once each, and none while that scale is unknown', () => {+ expect(getModelOnlyUpscaleFactors(upscaler(4))).toEqual([1.5, 2, 4]);+ expect(getModelOnlyUpscaleFactors(upscaler(2))).toEqual([1.5, 2]);+ expect(getModelOnlyUpscaleFactors(upscaler(3))).toEqual([1.5, 2, 3]);+ // A 1x model enlarges nothing, so a larger factor would only be a resize.+ expect(getModelOnlyUpscaleFactors(upscaler(1))).toEqual([1]);+ expect(getModelOnlyUpscaleFactors(upscaler(null))).toBeNull();+ expect(getModelOnlyUpscaleFactors(upscaler())).toBeNull();+ });++ it("sizes the output as Spandrel's frame, or the input for a model that does not enlarge", () => {+ // A FLUX main model would floor Refine's output to 16; Model only runs no pass, so only the multiple of 8 applies.+ const flux = model('flux', 'main', 'flux') as never;++ expect(getUpscaleOutputDimensions({ height: 1004, width: 1004 }, modelOnly({ model: flux, scale: 2 }))).toEqual({+ height: 2008,+ width: 2008,+ });+ expect(getUpscaleOutputDimensions(image, modelOnly({ scale: 4, upscaleModel: upscaler(1) }))).toEqual({+ height: 96,+ width: 200,+ });+ expect(getUpscaleOutputDimensions(image, modelOnly({ scale: 4, upscaleModel: upscaler(null) }))).toEqual({+ height: 400,+ width: 808,+ });+ });++ it('runs a Model only submission once, with no prompt and a fixed seed, for the input its metadata was read from', () => {+ const draft = { negativePrompt: 'blur', negativePromptEnabled: true, positivePrompt: 'the Generate draft' };+ const values = modelOnly({ batchCount: 3, seedMode: 'increment' as const });++ expect(resolveUpscaleSubmissionValues(values, { promptDraft: draft, sourceImageName: 'source.png' })).toMatchObject(+ { batchCount: 1, negativePrompt: '', positivePrompt: '', seedMode: 'fixed' }+ );+ expect(resolveUpscaleSubmissionValues(values, { promptDraft: draft, sourceImageName: 'earlier.png' })).toBeNull();+ expect(resolveUpscaleSubmissionValues(values, { promptDraft: draft, sourceImageName: undefined })).toBeNull();+ });++ it('refines with the shared prompt draft and its own iterations, reading no source metadata', () => {+ const draft = { negativePrompt: 'blur', negativePromptEnabled: false, positivePrompt: 'detail' };+ const values = { ...modelOnly({ batchCount: 3, seedMode: 'increment' as const }), mode: 'refine' as const };++ expect(resolveUpscaleSubmissionValues(values, { promptDraft: draft, sourceImageName: undefined })).toEqual({+ ...values,+ ...draft,+ });+ });++ it('fixes the iteration count only for Model only, saved values included', () => {+ expect(isUpscaleBatchCountFixed({ batchCount: 3, mode: 'model-only' })).toBe(true);+ expect(isUpscaleBatchCountFixed({ batchCount: 3, mode: 'refine' })).toBe(false);+ expect(isUpscaleBatchCountFixed({ batchCount: 3 })).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex 0a71d06e59..88e4a5500d 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -37,7 +37,7 @@ import {} from '@features/generation/settings';import { isSeedMode, SEED_MAX } from '@platform/core/seed';-import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleWidgetValues } from './types';+import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleMode, UpscaleWidgetValues } from './types';// The schedules of the denoise nodes that clip `denoising_start` by step index, for the table's// `indexClipping`; `getIndexClippedDenoisingStart` in graph.ts uses them to start those nodes where@@ -757,6 +757,7 @@ export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[]creativity: 0,inputImage: null,loras: [],+ mode: 'refine',model,negativePrompt: '',negativePromptEnabled: true,@@ -778,6 +779,9 @@ export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[]};};+/** Anything but Model only, a missing value included, is Refine: projects saved before modes existed refine. */+const normalizeUpscaleMode = (value: unknown): UpscaleMode => (value === 'model-only' ? 'model-only' : 'refine');+/*** Heal partial persisted values without clamping invalid user input; invocation validation supplies actionable* range errors.@@ -817,6 +821,7 @@ export const normalizeUpscaleWidgetValues = (value: unknown): UpscaleWidgetValue? value.inputImage: null,loras: normalizeLoras(value.loras),+ mode: normalizeUpscaleMode(value.mode),model: isMainModelConfig(value.model) ? value.model : null,negativePrompt: typeof value.negativePrompt === 'string' ? value.negativePrompt : defaults.negativePrompt,negativePromptEnabled:@@ -945,7 +950,39 @@ const addRangeReason = (reasons: string[], label: string, value: number, min: nu}};+/**+ * Model only needs no main model, encoder, ControlNet or served architecture table: just an image, an installed+ * upscaler and a Scale in range.+ */+const getModelOnlyValidationReasons = (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.');+ }+ addRangeReason(reasons, 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);++ if (models && values.upscaleModel) {+ const installed = models.find((model) => model.key === values.upscaleModel?.key);++ if (!installed) {+ reasons.push(`${values.upscaleModel.name} is no longer installed.`);+ } else if (!isSpandrelModelConfig(installed)) {+ reasons.push(`${values.upscaleModel.name} is not an installed Spandrel model.`);+ }+ }++ return reasons;+};+export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?: readonly ModelConfig[]): string[] => {+ if (values.mode === 'model-only') {+ return getModelOnlyValidationReasons(values, models);+ }+// As in Generate: without the served table every VAE reads as incompatible and the schedulers fall// back, so the other reasons would mislead and the graph would be wrong.if (!hasArchitectureCapabilities()) {@@ -1089,24 +1126,123 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?return reasons;};+/** The upscaler's recorded native scale, or null for a record installed before the probe recorded it. */+export const getSpandrelNativeScale = (model: SpandrelModelConfig | null | undefined): number | null =>+ typeof model?.scale === 'number' && Number.isInteger(model.scale) && model.scale >= 1 ? model.scale : null;++/**+ * How `spandrel_image_to_image_autoscale` reaches a Scale with a model of a known native scale. A model that enlarges+ * runs until the image is at least the target, then resizes to it; one that does not enlarge (1x) runs once and+ * ignores Scale.+ */+export type ModelOnlyUpscalePlan =+ | { kind: 'no-enlarge' }+ | { kind: 'passes'; passes: number; /** The image is resized after the last pass. */ resizes: boolean };++export const getModelOnlyUpscalePlan = (nativeScale: number | null, scale: number): ModelOnlyUpscalePlan | null => {+ if (nativeScale === null || !Number.isFinite(scale) || scale <= 0) {+ return null;+ }+ if (nativeScale === 1) {+ return { kind: 'no-enlarge' };+ }++ // The node compares sizes, not factors; multiplying keeps 4x reaching 16 in exactly two passes.+ let passes = 1;+ let reached = nativeScale;++ while (reached < scale) {+ passes += 1;+ reached *= nativeScale;+ }++ return { kind: 'passes', passes, resizes: reached !== scale };+};++/** The fixed targets one-click Model only upscales offer besides the upscaler's native scale. */+const MODEL_ONLY_PRESET_FACTORS = [1.5, 2];++/**+ * The factors a one-click Model only upscale offers with this upscaler, smallest first: 1.5×, 2× and its native scale,+ * keeping only those the plan reaches (a 1× model enlarges nothing, so it offers its native scale alone). Null while+ * the native scale is unknown, as no plan can be made for it.+ */+export const getModelOnlyUpscaleFactors = (model: SpandrelModelConfig): number[] | null => {+ const nativeScale = getSpandrelNativeScale(model);++ if (nativeScale === null) {+ return null;+ }++ const presets = MODEL_ONLY_PRESET_FACTORS.filter(+ (factor) => factor !== nativeScale && getModelOnlyUpscalePlan(nativeScale, factor)?.kind === 'passes'+ );++ return [...presets, nativeScale].sort((a, b) => a - b);+};+/**- * The size the result comes out at: Spandrel's scaled frame, floored to the grid of a pass that- * resizes it. One exception cannot be seen from here: a 1x restoration model leaves the frame at the- * source size, and SD's pass keeps that size. Spandrel's model configs do not carry the scale.+ * The size the result comes out at. Refine: Spandrel's scaled frame, floored to the grid of a pass that resizes it.+ * Model only: Spandrel's frame alone, floored to a multiple of 8 as the graph asks, or the input size for a model+ * recorded as not enlarging. A 1x model with no recorded scale cannot be seen from here: it leaves the frame at the+ * source size, which SD's pass keeps too.*/export const getUpscaleOutputDimensions = (image: Pick<ImageWithDims, 'width' | 'height'>,- scale: number,- model: MainModelConfig | null+ values: Pick<UpscaleWidgetValues, 'mode' | 'model' | 'scale' | 'upscaleModel'>): { width: number; height: number } => {- const grid = upscaleArchitectureFor(model)?.denoiseGrid ?? 8;+ if (values.mode === 'model-only') {+ const scale = getSpandrelNativeScale(values.upscaleModel) === 1 ? 1 : values.scale;++ return {+ height: spandrelAutoscaleDimension(image.height, scale),+ width: spandrelAutoscaleDimension(image.width, scale),+ };+ }++ const grid = upscaleArchitectureFor(values.model)?.denoiseGrid ?? 8;return {- height: upscaleDenoiseDimension(image.height, scale, grid),- width: upscaleDenoiseDimension(image.width, scale, grid),+ height: upscaleDenoiseDimension(image.height, values.scale, grid),+ width: upscaleDenoiseDimension(image.width, values.scale, grid),};};+/** Model only runs the upscaler alone, which gives the same image every time, so iterations would only repeat it. */+export const isUpscaleBatchCountFixed = (values: Record<string, unknown>): boolean =>+ normalizeUpscaleMode(values.mode) === 'model-only';++/**+ * Whether a Model only run may go ahead with the metadata read for `sourceImageName`: the read must be of the image+ * that is still the input, or the result would carry another image's metadata. Refine reads none.+ */+export const isUpscaleSourceMetadataCurrent = (values: UpscaleWidgetValues, sourceImageName: string | undefined) =>+ values.mode !== 'model-only' || (values.inputImage !== null && sourceImageName === values.inputImage.image_name);++/**+ * The values an Upscale submission runs with, or null when Model only's metadata was read for another image. Refine+ * takes the project's shared prompt draft. Model only reads no prompt, so it carries none for the queue to show; it+ * keeps a fixed seed, leaving the Refine seed where it was; and it runs once, as its iterations would only repeat.+ */+export const resolveUpscaleSubmissionValues = (+ values: UpscaleWidgetValues,+ {+ promptDraft,+ sourceImageName,+ }: {+ promptDraft: Pick<UpscaleWidgetValues, 'negativePrompt' | 'negativePromptEnabled' | 'positivePrompt'>;+ sourceImageName: string | undefined;+ }+): UpscaleWidgetValues | null => {+ if (!isUpscaleSourceMetadataCurrent(values, sourceImageName)) {+ return null;+ }++ return values.mode === 'model-only'+ ? { ...values, batchCount: 1, negativePrompt: '', positivePrompt: '', seedMode: 'fixed' }+ : { ...values, ...promptDraft };+};+export const clearDeletedUpscaleInput = (values: UpscaleWidgetValues,deletedImageNames: ReadonlySet<string>diff --git a/invokeai/frontend/webv2/src/features/upscale/core/types.ts b/invokeai/frontend/webv2/src/features/upscale/core/types.tsindex 982b2386cf..d82adaa98f 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/types.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/types.ts@@ -10,11 +10,22 @@ import type {} from '@features/generation/contracts';import type { SeedMode } from '@platform/core/seed';-export type SpandrelModelConfig = ModelIdentifierConfig & { type: 'spandrel_image_to_image' };+export type SpandrelModelConfig = ModelIdentifierConfig & {+ type: 'spandrel_image_to_image';+ /** The installed record's native scale; null or absent when it was installed before the probe recorded it. */+ scale?: number | null;+};export type TileControlNetModelConfig = ModelIdentifierConfig & { type: 'controlnet' };+/**+ * Refine runs the upscaler and then a detail pass with a main model; Model only runs the upscaler alone. Values saved+ * before modes existed are Refine.+ */+export type UpscaleMode = 'refine' | 'model-only';+/** Project-persisted settings owned by the Upscale widget. */export interface UpscaleWidgetValues {+ mode: UpscaleMode;inputImage: ImageWithDims | null;upscaleModel: SpandrelModelConfig | null;scale: number;diff --git a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.tsindex bf2f1bcfb7..4edf2717ec 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts@@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest';import type { UpscaleWidgetValues } from './types';-import { compileUpscaleGraph } from './graph';+import { compileModelOnlyUpscaleGraph, compileUpscaleGraph } from './graph';import { createDefaultUpscaleWidgetValues, getUpscaleValidationReasons, UPSCALE_ARCHITECTURES } from './settings';seedArchitectureCapabilities();@@ -125,6 +125,31 @@ const compileCase = ({ main, patch }: (typeof CASES)[number]): BackendGraphContrreturn compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph;};+/**+ * Model only, at a Scale (the widget and the image menu) and at the native scale of an upscaler that never recorded+ * it (the image menu's plain pass). It loads no main model, so it has no base of its own: its node types and fields+ * join the contract without a `byBase` entry.+ */+const compileModelOnlyGraphs = (): BackendGraphContract[] => {+ const image = { height: 101, image_name: 'input.png', width: 203 };++ const runs: { nativeScale: number | null; scale: number | 'native' }[] = [+ { nativeScale: 4, scale: 2 },+ { nativeScale: null, scale: 'native' },+ ];++ return runs.map(+ ({ nativeScale, scale }) =>+ compileModelOnlyUpscaleGraph({+ destination: 'gallery',+ image,+ scale,+ sourceMetadata: { positive_prompt: 'source' },+ upscaleModel: { ...INSTALLED[0], scale: nativeScale } as UpscaleWidgetValues['upscaleModel'] & object,+ }).backendGraph+ );+};+describe('upscale graph coverage', () => {it('covers every architecture the widget supports', () => {expect([...new Set(CASES.map(({ main }) => main.base))].sort()).toEqual(Object.keys(UPSCALE_ARCHITECTURES).sort());@@ -140,14 +165,21 @@ describe('upscale graph coverage', () => {const fieldsFor = (nodeType: string) =>(fields[nodeType] ??= { inputs: new Set(), literals: new Map(), outputs: new Set() });- for (const testCase of CASES) {- const graph = compileCase(testCase);- const entry = (byBase[testCase.main.base] ??= { nodeTypes: [] });+ const graphs = [+ ...CASES.map((testCase) => {+ const graph = compileCase(testCase);+ const entry = (byBase[testCase.main.base] ??= { nodeTypes: [] });++ entry.nodeTypes = [+ ...new Set([...entry.nodeTypes, ...Object.values(graph.nodes).map((node) => node.type)]),+ ].sort();- entry.nodeTypes = [- ...new Set([...entry.nodeTypes, ...Object.values(graph.nodes).map((node) => node.type)]),- ].sort();+ return graph;+ }),+ ...compileModelOnlyGraphs(),+ ];+ for (const graph of graphs) {for (const node of Object.values(graph.nodes)) {const { literals } = fieldsFor(node.type);diff --git a/invokeai/frontend/webv2/src/features/upscale/index.ts b/invokeai/frontend/webv2/src/features/upscale/index.tsindex d0c5a4a648..6d326c08e6 100644--- a/invokeai/frontend/webv2/src/features/upscale/index.ts+++ b/invokeai/frontend/webv2/src/features/upscale/index.ts@@ -1,12 +1,17 @@-export { compileUpscaleGraph } from './core/graph';+export { compileModelOnlyUpscaleGraph, compileUpscaleGraph } from './core/graph';export {clearDeletedUpscaleInput,cloneUpscaleWidgetValues,createDefaultUpscaleWidgetValues,+ getModelOnlyUpscaleFactors,+ getSpandrelNativeScale,getUpscaleOutputDimensions,getUpscaleValidationReasons,+ isUpscaleBatchCountFixed,+ isUpscaleSourceMetadataCurrent,normalizeUpscaleWidgetValues,resolveUpscaleSeed,+ resolveUpscaleSubmissionValues,syncUpscaleWidgetValuesWithModels,} from './core/settings';export type {diff --git a/invokeai/frontend/webv2/src/features/upscale/sourceMetadata.ts b/invokeai/frontend/webv2/src/features/upscale/sourceMetadata.tsnew file mode 100644index 0000000000..8c74a5446c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/sourceMetadata.ts@@ -0,0 +1,21 @@+import { galleryImages } from '@features/gallery';+import { ApiError } from '@platform/transport/http';++/**+ * The metadata a Model only upscale copies into its result. Null when the image has none (an upload) or the server no+ * longer has it; any other failure throws, so the run is not queued without the metadata it should carry. Callers load+ * this module on demand, keeping its gallery read out of the editor's startup graph.+ */+export const readUpscaleSourceMetadata = async (+ imageName: string,+ signal?: AbortSignal+): Promise<Record<string, unknown> | null> => {+ try {+ return await galleryImages.metadata(imageName, signal);+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ return null;+ }+ throw error;+ }+};diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex 2cd9107d9f..c78ff1330c 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -2,7 +2,7 @@ import type { GenerateLora, MainModelConfig } from '@features/generation/contracimport type { ProjectPromptDraftPatch } from '@features/generation/settings';import type { ModelConfig, ModelTaxonomyType } from '@features/models';import type { UpscaleComponentField, UpscaleComponentSlot } from '@features/upscale/core/settings';-import type { UpscaleWidgetValues } from '@features/upscale/core/types';+import type { UpscaleMode, UpscaleWidgetValues } from '@features/upscale/core/types';import type { FeatureHintId } from '@platform/ui/hints/hintRegistry';import {@@ -51,6 +51,8 @@ import { ModelSelect } from '@features/models/react';import {coerceUpscaleScheduler,createDefaultUpscaleWidgetValues,+ getModelOnlyUpscalePlan,+ getSpandrelNativeScale,getUpscaleOutputDimensions,isSpandrelModelConfig,isSupportedUpscaleMainModel,@@ -79,7 +81,9 @@ import { SEED_MAX } from '@platform/core/seed';import { useMountEffect } from '@platform/react/useMountEffect';import { useExternalStoreSelector } from '@platform/state/selectors';import { Combobox, Field, Select, Tooltip } from '@platform/ui';+import { Button } from '@platform/ui/Button';import { ScrubberField } from '@platform/ui/ScrubberField';+import { SegmentedControl } from '@platform/ui/SegmentedControl';import { toaster } from '@platform/ui/toaster';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -221,23 +225,44 @@ const formatScale = (scale: number): string => `${scale}×`;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}.`;+/** The muted line under the preflight explaining how Model only reaches Scale with this upscaler. */+const useModelOnlyPlanNote = (nativeScale: number | null, scale: number): string | null => {+ const { t } = useTranslation();+ const plan = getModelOnlyUpscalePlan(nativeScale, scale);++ if (!plan || nativeScale === null) {+ return null;+ }+ if (plan.kind === 'no-enlarge') {+ return t('widgets.upscale.nativeScaleNoEnlarge');+ }+ if (nativeScale === scale) {+ return null;+ }++ return plan.resizes+ ? t('widgets.upscale.nativeScalePassesResize', { count: plan.passes, native: nativeScale, target: scale })+ : t('widgets.upscale.nativeScalePasses', { count: plan.passes, native: nativeScale });+};+const UpscaleOutputPreflight = memo(function UpscaleOutputPreflight({inputImage,+ mode,model,scale,- }: {- inputImage: UpscaleWidgetValues['inputImage'];- model: UpscaleWidgetValues['model'];- scale: number;- }) {+ upscaleModel,+ }: Pick<UpscaleWidgetValues, 'inputImage' | 'mode' | 'model' | 'scale' | 'upscaleModel'>) {const { t } = useTranslation();+ // Refine's detail pass resizes to Scale whatever the upscaler does, so only Model only explains the upscaler.+ const nativeScale = mode === 'model-only' ? getSpandrelNativeScale(upscaleModel) : null;+ const planNote = useModelOnlyPlanNote(nativeScale, scale);if (!inputImage) {return null;}- const output = getUpscaleOutputDimensions(inputImage, scale, model);+ const output = getUpscaleOutputDimensions(inputImage, { mode, model, scale, upscaleModel });const outputMegapixels = (output.width * output.height) / 1_000_000;const isLargeOutput = outputMegapixels >= LARGE_OUTPUT_MEGAPIXELS;@@ -270,6 +295,21 @@ const UpscaleOutputPreflight = memo({scale}×</DataList.ItemValue></DataList.Item>+ {nativeScale === null ? null : (+ <DataList.Item>+ <DataList.ItemLabel color="fg.subtle" fontSize="xs">+ {t('widgets.upscale.nativeScale')}+ </DataList.ItemLabel>+ <DataList.ItemValue+ fontFamily="mono"+ fontSize="md"+ fontVariantNumeric="tabular-nums"+ justifyContent="flex-end"+ >+ {t('widgets.upscale.nativeScaleValue', { scale: nativeScale })}+ </DataList.ItemValue>+ </DataList.Item>+ )}<DataList.Item><DataList.ItemLabel color="fg.subtle" fontSize="xs">{t('widgets.upscale.outputSize')}@@ -305,6 +345,11 @@ const UpscaleOutputPreflight = memo(</DataList.ItemValue></DataList.Item></DataList.Root>+ {planNote ? (+ <Text color="fg.muted" fontSize="xs" textWrap="pretty">+ {planNote}+ </Text>+ ) : null}{isLargeOutput ? (<TextborderTopWidth="1px"@@ -322,11 +367,35 @@ const UpscaleOutputPreflight = memo(},(previous, next) =>previous.scale === next.scale &&+ previous.mode === next.mode &&// The grid comes from the architecture, so another model of the same base changes nothing.previous.model?.base === next.model?.base &&+ getSpandrelNativeScale(previous.upscaleModel) === getSpandrelNativeScale(next.upscaleModel) &&areInputImagesEquivalent(previous.inputImage, next.inputImage));+/** Re-identifying an upscaler records its native scale; shown under the field whose description says it is unknown. */+const OpenUpscalerInModelManager = ({ modelKey, onOpen }: { modelKey: string; onOpen: (modelKey: string) => void }) => {+ const { t } = useTranslation();+ const open = useCallback(() => onOpen(modelKey), [modelKey, onOpen]);++ return (+ <Button+ alignSelf="flex-start"+ fontSize="xs"+ h="auto"+ mt="-1.5"+ px="0"+ size="sm"+ textDecoration="underline"+ variant="plain"+ onClick={open}+ >+ {t('widgets.upscale.openInModelManager')}+ </Button>+ );+};+const UpscaleModelReconciler = ({rawValues,values,@@ -538,6 +607,11 @@ export const UpscaleWidgetView = () => {clipSkip: (clipSkip: number) => patch({ clipSkip }),creativity: (creativity: number) => patch({ creativity }),inputImage: (inputImage: UpscaleWidgetValues['inputImage']) => patch({ inputImage }),+ mode: (mode: string) => {+ if (mode === 'refine' || mode === 'model-only') {+ patch({ mode });+ }+ },scale: (scale: number) => patch({ scale }),scheduler: (scheduler: string) => patch({ scheduler }),spandrelModel: (model: ModelConfig | null) =>@@ -594,9 +668,25 @@ export const UpscaleWidgetView = () => {);const sharedBadge = useMemo(() => <Badge fontFamily="mono">{t('widgets.upscale.shared')}</Badge>, [t]);+ const modeOptions = useMemo(+ () =>+ [+ { label: t('widgets.upscale.modeRefine'), value: 'refine' },+ { label: t('widgets.upscale.modeModelOnly'), value: 'model-only' },+ ] satisfies { label: string; value: UpscaleMode }[],+ [t]+ );+ // Model only keeps the Refine settings as they are, hidden, so switching back restores them.+ const isRefine = values.mode === 'refine';+ // Model only can neither show nor plan the passes of an upscaler installed before Invoke recorded native scales;+ // the field's description says so, and re-identifying it in the Model Manager records it.+ const isNativeScaleUnknown =+ values.mode === 'model-only' &&+ values.upscaleModel !== null &&+ getSpandrelNativeScale(values.upscaleModel) === null;const form = (- <Stack gap={1} minW={0} p="1">+ <Stack gap={1} minW={0}><UpscaleModelReconcilerkey={`${projectId}:${modelsStatus}:${capabilitiesRevision}:${modelsFingerprint}`}rawValues={rawValues}@@ -606,10 +696,22 @@ export const UpscaleWidgetView = () => {<GenerationSettingsSection label={t('widgets.upscale.sourceAndTreatment')} defaultOpen><Stack gap="3" p="2"><UpscaleImageField inputImage={values.inputImage} onChange={set.inputImage} />- <UpscaleOutputPreflight inputImage={values.inputImage} model={values.model} scale={values.scale} />+ <UpscaleOutputPreflight+ inputImage={values.inputImage}+ mode={values.mode}+ model={values.model}+ scale={values.scale}+ upscaleModel={values.upscaleModel}+ /><Fielderror={values.upscaleModel ? undefined : t('widgets.upscale.spandrelModelRequired')}- helpText={values.upscaleModel ? t('widgets.upscale.spandrelModelHelp') : undefined}+ helpText={+ !values.upscaleModel+ ? undefined+ : isNativeScaleUnknown+ ? t('widgets.upscale.nativeScaleUnknown')+ : t('widgets.upscale.spandrelModelHelp')+ }hint="upscaleModel"label={t('widgets.upscale.spandrelModel')}>@@ -621,6 +723,9 @@ export const UpscaleWidgetView = () => {onChange={set.spandrelModel}/></Field>+ {isNativeScaleUnknown && values.upscaleModel && openInModelManager ? (+ <OpenUpscalerInModelManager modelKey={values.upscaleModel.key} onOpen={openInModelManager} />+ ) : null}<ScrubberFielderror={errors.scale}formatValue={formatScale}@@ -634,45 +739,49 @@ export const UpscaleWidgetView = () => {value={values.scale}onChange={set.scale}/>- <SegmentGroup.Root- aria-label={t('widgets.upscale.presetsLabel')}- value={activePresetId}- w="full"- onValueChange={applyPreset}- >- <SegmentGroup.Indicator />- {PRESET_ENTRIES.map(([id, preset]) => {- const tooltipContent = `${t(`widgets.upscale.presetDescriptions.${id}`)} ${t(- 'widgets.upscale.presetValues',- { creativity: preset.creativity, structure: preset.structure }- )}`;-- return (- // The tooltip trigger merges onto the text, not the item: both- // tooltip and segment item write `data-state`, and the tooltip's- // open/closed would clobber the item's checked state.- <SegmentGroup.Item key={id} flex="1" minW="0" value={id}>- <SegmentGroup.ItemHiddenInput />- <Tooltip content={tooltipContent}>- <SegmentGroup.ItemText fontSize="md">{t(`widgets.upscale.presets.${id}`)}</SegmentGroup.ItemText>- </Tooltip>- </SegmentGroup.Item>- );- })}- </SegmentGroup.Root>- <ScrubberField- error={errors.creativity}- helpText={t('widgets.upscale.creativityHelp')}- hint="creativity"- label={t('widgets.upscale.creativity')}- marks={CREATIVITY_MARKS}- max={UPSCALE_CREATIVITY_MAX}- min={UPSCALE_CREATIVITY_MIN}- step={1}- value={values.creativity}- onChange={set.creativity}- />- {showStructure && (+ {isRefine ? (+ <SegmentGroup.Root+ aria-label={t('widgets.upscale.presetsLabel')}+ value={activePresetId}+ w="full"+ onValueChange={applyPreset}+ >+ <SegmentGroup.Indicator />+ {PRESET_ENTRIES.map(([id, preset]) => {+ const tooltipContent = `${t(`widgets.upscale.presetDescriptions.${id}`)} ${t(+ 'widgets.upscale.presetValues',+ { creativity: preset.creativity, structure: preset.structure }+ )}`;++ return (+ // The tooltip trigger merges onto the text, not the item: both+ // tooltip and segment item write `data-state`, and the tooltip's+ // open/closed would clobber the item's checked state.+ <SegmentGroup.Item key={id} flex="1" minW="0" value={id}>+ <SegmentGroup.ItemHiddenInput />+ <Tooltip content={tooltipContent}>+ <SegmentGroup.ItemText fontSize="md">{t(`widgets.upscale.presets.${id}`)}</SegmentGroup.ItemText>+ </Tooltip>+ </SegmentGroup.Item>+ );+ })}+ </SegmentGroup.Root>+ ) : null}+ {isRefine ? (+ <ScrubberField+ error={errors.creativity}+ helpText={t('widgets.upscale.creativityHelp')}+ hint="creativity"+ label={t('widgets.upscale.creativity')}+ marks={CREATIVITY_MARKS}+ max={UPSCALE_CREATIVITY_MAX}+ min={UPSCALE_CREATIVITY_MIN}+ step={1}+ value={values.creativity}+ onChange={set.creativity}+ />+ ) : null}+ {isRefine && showStructure && (<ScrubberFielderror={errors.structure}helpText={t('widgets.upscale.structureHelp')}@@ -689,215 +798,235 @@ export const UpscaleWidgetView = () => {</Stack></GenerationSettingsSection>- <GenerationSettingsSection badges={sharedBadge} label={t('widgets.upscale.detailGuidance')}>- <UpscalePromptFields- loras={values.loras}- model={values.model}- negativePromptHeightPx={values.negativePromptHeightPx}- positivePromptHeightPx={values.positivePromptHeightPx}- promptDraft={promptDraft}- projectId={projectId}- showSyntaxHighlighting={selection.showPromptSyntaxHighlighting}- onPatchPromptDraft={patchPromptDraft}- onPatchValues={patch}- />- </GenerationSettingsSection>-- <GenerationSettingsSection label={t('widgets.upscale.generation')}>- <Stack gap="3" p="2">- <Field- error={values.model ? undefined : t('widgets.upscale.mainModelRequired')}- hint="model"- label={t('widgets.upscale.mainModel')}- >- <ModelSelect- filter={isSelectableMainModel}- invalid={!values.model}- modelTypes={MAIN_MODEL_TYPES}- placeholder={t('widgets.upscale.selectMainModel')}- value={values.model?.key ?? null}- onChange={selectMainModel}- />- </Field>- <Separator borderColor="border.subtle" />- {/* Iterations live in the top bar's invoke cluster, which edits this widget's batch count directly. */}- <ScrubberField- error={errors.steps}- hint="steps"- inputMax={1000}- label={t('widgets.upscale.steps')}- max={STEPS_SLIDER_MAX}- min={upscaleMinSteps(values.model)}- step={1}- value={values.steps}- onChange={set.steps}- />- <ScrubberField- error={errors.cfgScale}- hint="cfgScale"- inputMax={cfgScaleMax}- label={t('widgets.upscale.cfgScale')}- max={Math.min(CFG_SLIDER_MAX, cfgScaleMax)}- min={1}- step={0.5}- value={values.cfgScale}- onChange={set.cfgScale}- />- {schedulerOptions.length > 1 ? (- <Field hint="scheduler" label={t('widgets.upscale.scheduler')}>- <Combobox- aria-label={t('widgets.upscale.scheduler')}- options={schedulerOptions}- value={scheduler}- onValueChange={set.scheduler}- />- </Field>- ) : null}- <Separator borderColor="border.subtle" />- <SeedField- batchCount={values.batchCount}- error={errors.seed}- label={t('widgets.upscale.seed')}- seed={values.seed}- seedMode={values.seedMode}- onCommit={patch}+ {isRefine ? (+ <GenerationSettingsSection badges={sharedBadge} label={t('widgets.upscale.detailGuidance')}>+ <UpscalePromptFields+ loras={values.loras}+ model={values.model}+ negativePromptHeightPx={values.negativePromptHeightPx}+ positivePromptHeightPx={values.positivePromptHeightPx}+ promptDraft={promptDraft}+ projectId={projectId}+ showSyntaxHighlighting={selection.showPromptSyntaxHighlighting}+ onPatchPromptDraft={patchPromptDraft}+ onPatchValues={patch}/>- <Separator borderColor="border.subtle" />- <Field hint="concepts" label={t('widgets.upscale.concepts')}>- <ModelSelect- excludeKeys={selectedLoraKeys}- filter={loraFilter}- modelTypes={LORA_MODEL_TYPES}- placeholder={t('widgets.upscale.searchCompatibleConcepts')}- scopeLabel={t('models.scopeConcepts')}- value={null}- onChange={addLora}- />- </Field>- {values.loras.length > 0 ? (- <Box mx={-1}>- <ConceptList label={t('widgets.upscale.concepts')} projectId={projectId}>- {values.loras.map((lora) => (- <ConceptRow- key={lora.model.key}- models={conceptModels}- lora={lora}- onRemove={removeLora}- onUpdate={updateLora}- />- ))}- </ConceptList>- </Box>- ) : null}- </Stack>- </GenerationSettingsSection>+ </GenerationSettingsSection>+ ) : null}- <GenerationSettingsSection label={t('widgets.upscale.advanced')}>- <Stack gap="3" p="2">- {tileControlNet?.required && (+ {isRefine ? (+ <GenerationSettingsSection label={t('widgets.upscale.generation')}>+ <Stack gap="3" p="2"><Field- error={values.tileControlnetModel ? undefined : t('widgets.upscale.tileControlNetRequired')}- helpText={values.tileControlnetModel ? t('widgets.upscale.tileControlNetHelp') : undefined}- hint="tileControlNet"- label={t('widgets.upscale.tileControlNet')}+ error={values.model ? undefined : t('widgets.upscale.mainModelRequired')}+ hint="model"+ label={t('widgets.upscale.mainModel')}><ModelSelect- filter={tileControlNetFilter}- invalid={!values.tileControlnetModel}- modelTypes={CONTROLNET_MODEL_TYPES}- placeholder={t('widgets.upscale.selectTileControlNet')}- value={values.tileControlnetModel?.key ?? null}- onChange={setTileControlNet}+ filter={isSelectableMainModel}+ invalid={!values.model}+ modelTypes={MAIN_MODEL_TYPES}+ placeholder={t('widgets.upscale.selectMainModel')}+ value={values.model?.key ?? null}+ onChange={selectMainModel}/></Field>- )}- {tileControlNet && !tileControlNet.required && (- <Field- helpText={t('widgets.upscale.tileControlNetOptionalHelp')}- hint="tileControlNet"- label={t('widgets.upscale.tileControlNet')}- >- <ModelSelect- filter={tileControlNetFilter}- isClearable- modelTypes={CONTROLNET_MODEL_TYPES}- placeholder={t('widgets.upscale.selectOptionalTileControlNet')}- value={values.tileControlnetModel?.key ?? null}- onChange={setTileControlNet}- />- </Field>- )}- {components.slots.map((slot) => (- <UpscaleComponentPicker key={slot.field} slot={slot} value={values[slot.field]} onPatch={patch} />- ))}- <ScrubberField- error={errors.tileSize}- helpText={t('widgets.upscale.tileSizeHelp')}- hint="tileSize"- label={t('widgets.upscale.tileSize')}- marks={TILE_SIZE_MARKS}- max={UPSCALE_TILE_SIZE_MAX}- min={UPSCALE_TILE_SIZE_MIN}- step={64}- value={values.tileSize}- onChange={set.tileSize}- />- <ScrubberField- error={errors.tileOverlap}- helpText={t('widgets.upscale.tileOverlapHelp')}- hint="tileOverlap"- label={t('widgets.upscale.tileOverlap')}- marks={TILE_OVERLAP_MARKS}- max={UPSCALE_TILE_OVERLAP_MAX}- min={UPSCALE_TILE_OVERLAP_MIN}- step={8}- value={values.tileOverlap}- onChange={set.tileOverlap}- />- <SimpleGrid columns={ADVANCED_GRID_COLUMNS} gap="2">- <Field- error={components.vae && !values.vae ? t('widgets.upscale.vaeRequired') : undefined}- hint="vae"- label={t('widgets.upscale.vae')}- >+ <Separator borderColor="border.subtle" />+ {/* Iterations live in the top bar's invoke cluster, which edits this widget's batch count directly. */}+ <ScrubberField+ error={errors.steps}+ hint="steps"+ inputMax={1000}+ label={t('widgets.upscale.steps')}+ max={STEPS_SLIDER_MAX}+ min={upscaleMinSteps(values.model)}+ step={1}+ value={values.steps}+ onChange={set.steps}+ />+ <ScrubberField+ error={errors.cfgScale}+ hint="cfgScale"+ inputMax={cfgScaleMax}+ label={t('widgets.upscale.cfgScale')}+ max={Math.min(CFG_SLIDER_MAX, cfgScaleMax)}+ min={1}+ step={0.5}+ value={values.cfgScale}+ onChange={set.cfgScale}+ />+ {schedulerOptions.length > 1 ? (+ <Field hint="scheduler" label={t('widgets.upscale.scheduler')}>+ <Combobox+ aria-label={t('widgets.upscale.scheduler')}+ options={schedulerOptions}+ value={scheduler}+ onValueChange={set.scheduler}+ />+ </Field>+ ) : null}+ <Separator borderColor="border.subtle" />+ <SeedField+ batchCount={values.batchCount}+ error={errors.seed}+ label={t('widgets.upscale.seed')}+ seed={values.seed}+ seedMode={values.seedMode}+ onCommit={patch}+ />+ <Separator borderColor="border.subtle" />+ <Field hint="concepts" label={t('widgets.upscale.concepts')}><ModelSelect- filter={vaeFilter}- invalid={components.vae && !values.vae}- isClearable={!components.vae}- modelTypes={VAE_MODEL_TYPES}- placeholder={components.vae ? t('widgets.upscale.selectVae') : t('widgets.upscale.bundledVae')}- value={values.vae?.key ?? null}- onChange={set.vae}- />- </Field>- <Field hint="vaePrecision" label={t('widgets.upscale.vaePrecision')}>- <Select- aria-label={t('widgets.upscale.vaePrecision')}- collection={VAE_PRECISION_COLLECTION}- value={vaePrecisionValue}- onValueChange={set.vaePrecision}+ excludeKeys={selectedLoraKeys}+ filter={loraFilter}+ modelTypes={LORA_MODEL_TYPES}+ placeholder={t('widgets.upscale.searchCompatibleConcepts')}+ scopeLabel={t('models.scopeConcepts')}+ value={null}+ onChange={addLora}/></Field>- </SimpleGrid>- {values.model?.base === 'sd-1' ? (+ {values.loras.length > 0 ? (+ <Box mx={-1}>+ <ConceptList label={t('widgets.upscale.concepts')} projectId={projectId}>+ {values.loras.map((lora) => (+ <ConceptRow+ key={lora.model.key}+ models={conceptModels}+ lora={lora}+ onRemove={removeLora}+ onUpdate={updateLora}+ />+ ))}+ </ConceptList>+ </Box>+ ) : null}+ </Stack>+ </GenerationSettingsSection>+ ) : null}++ {isRefine ? (+ <GenerationSettingsSection label={t('widgets.upscale.advanced')}>+ <Stack gap="3" p="2">+ {tileControlNet?.required && (+ <Field+ error={values.tileControlnetModel ? undefined : t('widgets.upscale.tileControlNetRequired')}+ helpText={values.tileControlnetModel ? t('widgets.upscale.tileControlNetHelp') : undefined}+ hint="tileControlNet"+ label={t('widgets.upscale.tileControlNet')}+ >+ <ModelSelect+ filter={tileControlNetFilter}+ invalid={!values.tileControlnetModel}+ modelTypes={CONTROLNET_MODEL_TYPES}+ placeholder={t('widgets.upscale.selectTileControlNet')}+ value={values.tileControlnetModel?.key ?? null}+ onChange={setTileControlNet}+ />+ </Field>+ )}+ {tileControlNet && !tileControlNet.required && (+ <Field+ helpText={t('widgets.upscale.tileControlNetOptionalHelp')}+ hint="tileControlNet"+ label={t('widgets.upscale.tileControlNet')}+ >+ <ModelSelect+ filter={tileControlNetFilter}+ isClearable+ modelTypes={CONTROLNET_MODEL_TYPES}+ placeholder={t('widgets.upscale.selectOptionalTileControlNet')}+ value={values.tileControlnetModel?.key ?? null}+ onChange={setTileControlNet}+ />+ </Field>+ )}+ {components.slots.map((slot) => (+ <UpscaleComponentPicker key={slot.field} slot={slot} value={values[slot.field]} onPatch={patch} />+ ))}<ScrubberField- hint="clipSkip"- label={t('widgets.upscale.clipSkip')}- max={12}- min={0}- step={1}- value={values.clipSkip}- onChange={set.clipSkip}+ error={errors.tileSize}+ helpText={t('widgets.upscale.tileSizeHelp')}+ hint="tileSize"+ label={t('widgets.upscale.tileSize')}+ marks={TILE_SIZE_MARKS}+ max={UPSCALE_TILE_SIZE_MAX}+ min={UPSCALE_TILE_SIZE_MIN}+ step={64}+ value={values.tileSize}+ onChange={set.tileSize}/>- ) : null}- </Stack>- </GenerationSettingsSection>+ <ScrubberField+ error={errors.tileOverlap}+ helpText={t('widgets.upscale.tileOverlapHelp')}+ hint="tileOverlap"+ label={t('widgets.upscale.tileOverlap')}+ marks={TILE_OVERLAP_MARKS}+ max={UPSCALE_TILE_OVERLAP_MAX}+ min={UPSCALE_TILE_OVERLAP_MIN}+ step={8}+ value={values.tileOverlap}+ onChange={set.tileOverlap}+ />+ <SimpleGrid columns={ADVANCED_GRID_COLUMNS} gap="2">+ <Field+ error={components.vae && !values.vae ? t('widgets.upscale.vaeRequired') : undefined}+ hint="vae"+ label={t('widgets.upscale.vae')}+ >+ <ModelSelect+ filter={vaeFilter}+ invalid={components.vae && !values.vae}+ isClearable={!components.vae}+ modelTypes={VAE_MODEL_TYPES}+ placeholder={components.vae ? t('widgets.upscale.selectVae') : t('widgets.upscale.bundledVae')}+ value={values.vae?.key ?? null}+ onChange={set.vae}+ />+ </Field>+ <Field hint="vaePrecision" label={t('widgets.upscale.vaePrecision')}>+ <Select+ aria-label={t('widgets.upscale.vaePrecision')}+ collection={VAE_PRECISION_COLLECTION}+ value={vaePrecisionValue}+ onValueChange={set.vaePrecision}+ />+ </Field>+ </SimpleGrid>+ {values.model?.base === 'sd-1' ? (+ <ScrubberField+ hint="clipSkip"+ label={t('widgets.upscale.clipSkip')}+ max={12}+ min={0}+ step={1}+ value={values.clipSkip}+ onChange={set.clipSkip}+ />+ ) : null}+ </Stack>+ </GenerationSettingsSection>+ ) : null}</Stack>);+ // The mode sits above the gate: Model only reads no main-model capabilities, so it stays reachable and usable while+ // the table is loading or has failed, which holds back only Refine's form.return (- <CapabilitiesGate isReady={hasCapabilities} labels={gateLabels}>- {form}- </CapabilitiesGate>+ <Stack gap={1} minW={0} p="1">+ <Box px="2" pt="2">+ <Field helpText={t('widgets.upscale.modeHelp')} label={t('widgets.upscale.mode')}>+ <SegmentedControl+ ariaLabel={t('widgets.upscale.mode')}+ options={modeOptions}+ value={values.mode}+ onChange={set.mode}+ />+ </Field>+ </Box>+ <CapabilitiesGate isReady={hasCapabilities || !isRefine} labels={gateLabels}>+ {form}+ </CapabilitiesGate>+ </Stack>);};diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.tsindex 5a393857d4..538c5d550e 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts@@ -21,7 +21,6 @@ import {formatReferencePromptLabels,getDefaultReferenceClip,getDefaultReferenceConditioning,- getDefaultReferenceImageDetail,getInitialVideoPatch,getReferencesPatch,isVideoSettings,@@ -488,26 +487,12 @@ describe('getDefaultReferenceClip', () => {});});-describe('getDefaultReferenceImageDetail', () => {- const imageReference = {- detail: 'max',- image: { height: 1080, image_name: 'ref.png', width: 1920 },- kind: 'image',- } as const;- const videoReference = {- clip: SOURCE_VIDEO,- conditioning: 'video_audio',- kind: 'video',- } as const;-- it('starts the first image reference at maximum detail', () => {- expect(getDefaultReferenceImageDetail([])).toBe('max');- expect(getDefaultReferenceImageDetail([videoReference])).toBe('max');- });+describe('stored image reference detail', () => {+ it.each(['max', 'match'] as const)('keeps a stored %s reference through normalization', (detail) => {+ // New references default to match; references saved before that keep the detail they were stored with.+ const reference = { detail, image: { height: 1080, image_name: 'ref.png', width: 1920 }, kind: 'image' } as const;- it('matches the generation size once an image reference is placed', () => {- expect(getDefaultReferenceImageDetail([imageReference])).toBe('match');- expect(getDefaultReferenceImageDetail([videoReference, imageReference])).toBe('match');+ expect(normalizeVideoSettings(createSettings({ references: [reference] }))?.references).toEqual([reference]);});});diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 99349f9129..049da771eb 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -723,11 +723,10 @@ export const createVideoReferenceEntry = (item: {};/**- * Default the first image to max detail and later images to generation-matched detail to limit repeatedly attended- * reference rows; users may override each.+ * New image references match the generation size, which limits the reference rows the model attends to; users may+ * raise each to max. Stored references keep their own detail, and recall restores the recorded one.*/-export const getDefaultReferenceImageDetail = (references: VideoReferenceItem[]): VideoReferenceImageDetail =>- references.some((entry) => entry.kind === 'image') ? 'match' : 'max';+export const DEFAULT_REFERENCE_IMAGE_DETAIL: VideoReferenceImageDetail = 'match';/** The minimum frames a trim must keep — video_concat's crossfade consumes a 2-frame tail. */export const MIN_VIDEO_TRIM_FRAMES = 2;diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex f90d9fb2cf..a9f22e02d4 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -15,6 +15,7 @@ export type {WanTargetResolution,} from './core/types';export {+ DEFAULT_REFERENCE_IMAGE_DETAIL,clearDeletedVideoMedia,cloneVideoWidgetValues,createVideoConditioningClip,@@ -22,7 +23,6 @@ export {createVideoSourceClip,getDefaultConditioningRole,getDefaultReferenceConditioning,- getDefaultReferenceImageDetail,areFrameImagesHeld,createFrameImageSetter,getConditioningClipPatch,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsxindex d1c6b0fb3b..00ef2c9aa1 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx@@ -19,7 +19,7 @@ import {clampReferenceSampleFrames,createVideoReferenceEntry,formatReferencePromptLabels,- getDefaultReferenceImageDetail,+ DEFAULT_REFERENCE_IMAGE_DETAIL,referencePromptLabels,referenceSampleFrames,resizeReferenceSampleWindow,@@ -452,8 +452,7 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({return [...current,{- // Derive defaults from the live list because another image may have arrived during the await.- detail: getDefaultReferenceImageDetail(current),+ detail: DEFAULT_REFERENCE_IMAGE_DETAIL,image: { height: image.height, image_name: image.name, width: image.width },kind: 'image',},diff --git a/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts b/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.tsindex 9868b00ba4..12f0718b2c 100644--- a/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts+++ b/invokeai/frontend/webv2/src/platform/ui/dialogExit.testing.ts@@ -5,15 +5,27 @@ export interface DialogExitFrame {text: string;}+const nextFrame = (): Promise<void> =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });+/*** Close an open dialog and record each `data-state` it passes through, with its text at that moment, until it* unmounts or settles closed. A dialog its host unmounted on close never reaches `closed`, so it cannot have animated* out; the text shows what it displayed while it did. Independent of animation duration and reduced motion.+ *+ * A dialog reads as open before it can be dismissed: its Escape and outside-press handling is set up in the frame+ * after it opens. On a loaded machine an Escape sent right away lands first and is dropped, so the close waits for+ * that frame to have run.*/export const recordDialogExit = async (dialog: Element,close: () => Promise<unknown> | unknown): Promise<DialogExitFrame[]> => {+ await nextFrame();+ await nextFrame();+const frames: DialogExitFrame[] = [];const observer = new MutationObserver(() =>frames.push({ state: dialog.getAttribute('data-state'), text: dialog.textContent ?? '' })diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts b/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.tsindex 0de444a95f..b33b8cca0f 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts@@ -12,9 +12,25 @@ const nextFrame = (): Promise<void> =>});});+let pointerTargets = 0;++/**+ * A momentary 2px target on top of everything: the real pointer can only be moved by hovering an element. Hovering+ * hands the browser a selector, which is positional unless the element has an id; a hint card's portal unmounting+ * between the two would shift a positional one off the target, and the hover would wait on nothing.+ */+const createPointerTarget = (): HTMLDivElement => {+ const target = document.createElement('div');++ pointerTargets += 1;+ target.id = `feature-hint-pointer-target-${pointerTargets}`;++ return target;+};+/** Move the real pointer to the page corner, so the next hover enters its trigger afresh and emits pointerenter. */export const parkPointer = async (): Promise<void> => {- const parking = document.createElement('div');+ const parking = createPointerTarget();parking.style.cssText = 'position:fixed;left:0;top:0;width:2px;height:2px;z-index:2147483647';document.body.append(parking);@@ -90,8 +106,7 @@ export const movePointerAlong = async (for (let step = 0; step <= steps; step += 1) {const x = from.x + ((to.x - from.x) * step) / steps;const y = from.y + ((to.y - from.y) * step) / steps;- // A momentary 2px target under the point: the real pointer can only be moved by hovering an element.- const probe = document.createElement('div');+ const probe = createPointerTarget();probe.style.cssText = `position:fixed;left:${x - 1}px;top:${y - 1}px;width:2px;height:2px;z-index:2147483647`;document.body.append(probe);diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.tsindex 5b32a4d8e9..3772035a0c 100644--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts@@ -32,6 +32,7 @@ const createArgs = (state = createInitialWorkbenchState()) => {return {commands: {} as WorkbenchCommands,formatControlLayerError: ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`,+ formatUpscaleMetadataFailure: (name: string) => name,getModels: () => undefined,queries: {getSnapshot: () => ({diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.tsindex 29dcfb15e3..996cecc960 100644--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts@@ -23,6 +23,7 @@ export interface ActiveInvocationSubmissionArgs {destinationOverride?: ResultDestination;/** Words a control-layer rejection from the locale; its error message is for logs only. */formatControlLayerError: PrepareCanvasInvocationArgs['formatControlLayerError'];+ formatUpscaleMetadataFailure: SubmitResolvedInvocationDeps['formatUpscaleMetadataFailure'];getModels: () => readonly ModelConfig[] | undefined;/** Invoke Front: the backend runs this batch ahead of the user's other pending work. */prepend?: boolean;@@ -68,6 +69,7 @@ export const submitActiveInvocation = async (commands,destinationOverride,formatControlLayerError,+ formatUpscaleMetadataFailure,getModels,prepend,queries,@@ -104,6 +106,7 @@ export const submitActiveInvocation = async (await activeRuntime.submit({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex a64deac581..0f721ed517 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -112,6 +112,7 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])qwen3VLEncoderModel: null,qwen35EncoderModel: null,animaInpaintAdapterModel: null,+ animaInpaintAdapterEnabled: true,animaInpaintAdapterWeight: 1,wanT5EncoderModel: null,wanLowNoiseModel: null,diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.tsindex ef82a4db3b..1e484876b5 100644--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts@@ -19,6 +19,7 @@ import { beginInvocationPreparation, endInvocationPreparation } from './invocati// Production words rejections from the locale; tests only need the structured rejection to reach the notice.const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;+const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;// Seed capabilities to match app boot; submission fails closed without them.seedArchitectureCapabilities();@@ -105,6 +106,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {const submitted = resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -127,6 +129,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {const submitted = resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -153,6 +156,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {const submitted = resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -176,6 +180,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {const submitted = resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -197,6 +202,7 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {const submitted = resolveAndSubmitGraphPreviewInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.tsindex e7868ffb92..656fe26918 100644--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts@@ -4,6 +4,7 @@ import type { AccountScope } from '@platform/state/accountLifecycle';import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';import type { InvocationSourceId } from './invocationContracts';+import type { SubmitResolvedInvocationDeps } from './invocationSubmit';import type { Project } from './projectContracts';import type { prepareCanvasInvocation } from './widgets/canvas/invoke/prepareCanvasInvocation';import type { WorkbenchCommands } from './workbenchStore';@@ -16,6 +17,8 @@ export interface GraphPreviewInvokeDeps {commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;/** Words a blocked canvas preview's control layer for the notice. */formatControlLayerError: Parameters<typeof prepareCanvasInvocation>[0]['formatControlLayerError'];+ /** Words a Model only upscale preview whose input metadata could not be read. */+ formatUpscaleMetadataFailure: SubmitResolvedInvocationDeps['formatUpscaleMetadataFailure'];models: readonly ModelConfig[] | undefined;owner: AccountScope;prepareCanvasInvocation: typeof prepareCanvasInvocation;@@ -30,6 +33,7 @@ export interface GraphPreviewInvokeDeps {export const resolveAndSubmitGraphPreviewInvocation = ({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation: prepareCanvas,@@ -60,6 +64,7 @@ export const resolveAndSubmitGraphPreviewInvocation = ({void submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation: prepareCanvas,diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex e209dfb4bc..ebfe6bafff 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -122,6 +122,7 @@ export const useRegisterFirstPartyCommands = () => {commands,destinationOverride,formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),+ formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),getModels: getAvailableModels,...(prepend ? { prepend } : {}),queries,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex 802e2f2ece..c32649f0fc 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -1,15 +1,21 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop */import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey } from '@features/gallery';import type { GalleryItemContextMenuTarget } from '@features/gallery/react';+import type { ModelsSnapshot } from '@features/models/data/modelsStore';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import { ChakraProvider } from '@chakra-ui/react';+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { getContrastRatio } from '@platform/ui/theme/contrastRatio.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { applyThemeToRoot } from '@theme/applyTheme';import { system } from '@theme/system';+import { DEFAULT_THEME_ID, THEMES } from '@theme/themes';import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';+import type * as ModelOnlyUpscaleModule from './modelOnlyUpscale';import type { ImageActions } from './useImageActions';import { ImageContextMenu, type ImageContextMenuTarget } from './ImageContextMenu';@@ -25,15 +31,54 @@ vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: ()vi.mock('@workbench/projects/library', () => ({useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),}));+const commandsMock = vi.hoisted(() => ({+ generation: { setSource: vi.fn(), submitModelOnlyUpscale: vi.fn() },+ notifications: { add: vi.fn() },+ widgets: { patchValues: vi.fn() },+}));+const galleryMock = vi.hoisted(() => ({+ metadata: vi.fn((): Promise<Record<string, unknown> | null> => Promise.resolve(null)),+}));+vi.mock('@features/gallery', async (importOriginal) => {+ const original = await importOriginal<{ galleryImages: Record<string, unknown> }>();++ return { ...original, galleryImages: { ...original.galleryImages, metadata: galleryMock.metadata } };+});+// The Upscale submenu asks for the model library on mount; tests seed the snapshot instead of fetching it.+const ensureModelsLoaded = vi.hoisted(() => vi.fn(() => Promise.resolve()));+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureModelsLoaded,+}));+vi.mock('@features/gallery/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureGalleryBoardDestinations: () => null,+}));+// The upscale command's chunk loads on pick; `fail` stands in for that load failing.+const modelOnlyLoad = vi.hoisted(() => ({ fail: false }));+vi.mock('./modelOnlyUpscale', async (importOriginal) => {+ const original = await importOriginal<typeof ModelOnlyUpscaleModule>();++ return {+ ...original,+ queueModelOnlyUpscale: (...args: Parameters<typeof original.queueModelOnlyUpscale>) =>+ modelOnlyLoad.fail+ ? Promise.reject(new Error('Failed to fetch dynamically imported module'))+ : original.queueModelOnlyUpscale(...args),+ };+});vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => 'project-1',useActiveProjectName: () => 'Project',- useWorkbenchCommands: () => ({- generation: { setSource: vi.fn() },- widgets: { patchValues: vi.fn() },+ useWorkbenchCommands: () => commandsMock,+}));+// Keys stand in for copy; the one interpolated value a test reads, an upscale factor, is shown as the locale does.+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { scale?: number }) =>+ options?.scale === undefined ? key : `${options.scale}×${key.endsWith('.factorNative') ? ' (native)' : ''}`,}),}));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));const image = (imageName: string): GalleryImage => ({boardId: 'none',@@ -378,7 +423,7 @@ describe('ImageContextMenu canvas destinations', () => {'—',ADD,NEW_PROJECT,- 'Send to Upscale',+ 'widgets.gallery.itemActions.upscale.label',]);});@@ -566,7 +611,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');// Videos carry their own Recall Metadata submenu (parameter recall).expect(document.body.textContent).toContain('Recall Metadata');- expect(document.body.textContent).not.toContain('Send to Upscale');+ expect(document.body.textContent).not.toContain('widgets.gallery.itemActions.upscale.label');expect(document.body.textContent).not.toContain('Select for Compare');expect(document.body.textContent).not.toContain('widgets.canvas.import.addToCurrentCanvas');expect(document.body.textContent).not.toContain('widgets.canvas.import.newProjectFromImage');@@ -772,3 +817,197 @@ describe('ImageContextMenu change-board destinations', () => {expect(document.querySelector('[data-value="board-mine"]')).not.toBeNull();});});++describe('ImageContextMenu Upscale submenu', () => {+ const upscaler = (key: string, name: string, scale: number | null) => ({+ base: 'any' as const,+ file_size: 1,+ format: 'checkpoint' as const,+ hash: `${key}-hash`,+ key,+ name,+ path: key,+ scale,+ source: key,+ source_type: 'path' as const,+ type: 'spandrel_image_to_image' as const,+ });+ const SEND_TO = 'widgets.gallery.itemActions.upscale.sendTo';+ const MODEL_ONLY = 'widgets.gallery.itemActions.upscale.modelOnlyGroup';+ const NO_UPSCALERS = 'widgets.gallery.itemActions.upscale.noUpscalers';+ const NATIVE_SCALE_UNKNOWN = 'widgets.upscale.nativeScaleUnknown';+ const NATIVE_ENTRY = 'widgets.gallery.itemActions.upscale.nativeScaleUnknownFactor';+ const OTHER_FACTORS = 'widgets.gallery.itemActions.upscale.otherFactors';++ const openUpscaleSubMenu = async (+ models: ReturnType<typeof upscaler>[],+ status: ModelsSnapshot['status'] = 'loaded'+ ) => {+ setModelsSnapshotForTests({ models, status });+ await renderMenu(createActions(vi.fn()), [image('source.png')]);+ await hoverItem(getMenuItem('widgets.gallery.itemActions.upscale.label'));+ await settleUntil(() => document.querySelector('[data-value="send-to-upscale"]') !== null, 'the Upscale submenu');++ return document+ .querySelector<HTMLElement>('[data-value="send-to-upscale"]')!+ .closest<HTMLElement>('[role="menu"]')!;+ };+ /** Opens one upscaler's factor submenu; `scaleSuffix` is the native scale its trigger shows. */+ const openFactorSubMenu = async (model: ReturnType<typeof upscaler>, scaleSuffix: string) => {+ await openUpscaleSubMenu([model]);+ await hoverItem(getMenuItem(`${model.name}${scaleSuffix}`));+ await settleUntil(+ () => document.querySelector(`[data-value^="upscale-model-only-${model.key}-"]`) !== null,+ `the factors of ${model.name}`+ );++ return document+ .querySelector<HTMLElement>(`[data-value^="upscale-model-only-${model.key}-"]`)!+ .closest<HTMLElement>('[role="menu"]')!;+ };+ const entries = (menu: HTMLElement) =>+ Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"], [data-part="item-group-label"]')).map(+ (entry) => `${entry.textContent?.trim()}${entry.getAttribute('aria-disabled') === 'true' ? ' (disabled)' : ''}`+ );++ afterEach(() => {+ setModelsSnapshotForTests({ models: [], status: 'idle' });+ ensureModelsLoaded.mockClear();+ commandsMock.generation.submitModelOnlyUpscale.mockReset();+ commandsMock.notifications.add.mockReset();+ galleryMock.metadata.mockReset();+ });++ it('lists every installed upscaler by name, with its native scale where it is recorded', async () => {+ const menu = await openUpscaleSubMenu([+ upscaler('ultra', '4x-UltraSharp', 4),+ upscaler('anime', '2x-AnimeSharp', 2),+ upscaler('legacy', 'Legacy restorer', null),+ ]);++ expect(entries(menu)).toEqual([SEND_TO, MODEL_ONLY, '2x-AnimeSharp2×', '4x-UltraSharp4×', 'Legacy restorer']);+ });++ it('still runs an upscaler of unknown native scale once at it, and says how to unlock the other factors', async () => {+ const legacy = upscaler('legacy', 'Legacy restorer', null);+ const factorMenu = await openFactorSubMenu(legacy, '');+ const otherFactors = factorMenu.querySelector<HTMLElement>('[data-value="upscale-model-only-legacy-other"]')!;++ expect(entries(factorMenu)).toEqual([NATIVE_ENTRY, `${OTHER_FACTORS}${NATIVE_SCALE_UNKNOWN} (disabled)`]);+ expect(document.getElementById(otherFactors.getAttribute('aria-describedby')!)?.textContent).toBe(+ NATIVE_SCALE_UNKNOWN+ );++ await interact(() => getMenuItem(NATIVE_ENTRY).click());+ await settleUntil(+ () => commandsMock.generation.submitModelOnlyUpscale.mock.calls.length > 0,+ 'the upscale to queue'+ );++ expect(commandsMock.generation.submitModelOnlyUpscale).toHaveBeenCalledTimes(1);+ expect(commandsMock.generation.submitModelOnlyUpscale).toHaveBeenCalledWith(+ expect.objectContaining({ scale: 'native', upscaleModel: legacy })+ );+ });++ it.each([+ [4, ['1.5×', '2×', '4× (native)']],+ // A 2x model's native scale is one of the presets: it is offered once, as native.+ [2, ['1.5×', '2× (native)']],+ // A 1x model enlarges nothing, so it offers its own scale alone.+ [1, ['1× (native)']],+ ])('offers a %sx upscaler its factors, smallest first', async (scale, factors) => {+ const factorMenu = await openFactorSubMenu(upscaler('model', 'Model', scale), `${scale}×`);++ expect(entries(factorMenu)).toEqual(factors);+ });+ it.each(THEMES.map(({ id }) => id))('shows the scale suffix at AA contrast on the %s menu', async (themeId) => {+ applyThemeToRoot(themeId);++ try {+ const menu = await openUpscaleSubMenu([upscaler('ultra', '4x-UltraSharp', 4)]);+ const suffix = [...menu.querySelectorAll<HTMLElement>('[role="menuitem"] *')].find(+ (element) => element.childElementCount === 0 && element.textContent === '4×'+ )!;++ expect(+ getContrastRatio(getComputedStyle(suffix).color, getComputedStyle(menu).backgroundColor, 1)+ ).toBeGreaterThanOrEqual(4.5);+ } finally {+ applyThemeToRoot(DEFAULT_THEME_ID);+ }+ });++ it.each([+ ['none are installed', 'loaded', NO_UPSCALERS],+ ['the library is loading', 'loading', 'models.loadingModels'],+ ['the library has not been asked for yet', 'idle', 'models.loadingModels'],+ ['the library could not load', 'error', 'models.couldNotLoad'],+ ] as const)(+ 'offers Send to Upscale and one unavailable model-only entry that says why when %s',+ async (_case, status, reason) => {+ const menu = await openUpscaleSubMenu([], status);+ const modelOnly = menu.querySelector<HTMLElement>('[data-value="upscale-model-only"]')!;++ expect(ensureModelsLoaded).toHaveBeenCalled();+ expect(entries(menu)).toEqual([SEND_TO, `${MODEL_ONLY}${reason} (disabled)`]);+ expect(document.getElementById(modelOnly.getAttribute('aria-describedby')!)?.textContent).toBe(reason);+ }+ );++ it.each([+ ['its native scale', '4× (native)', 'native'],+ ['another factor', '1.5×', 1.5],+ ])("queues the chosen upscaler at %s on the image with the image's metadata", async (_case, label, scale) => {+ const ultra = upscaler('ultra', '4x-UltraSharp', 4);+ galleryMock.metadata.mockResolvedValue({ positive_prompt: 'a lighthouse' });+ await openFactorSubMenu(ultra, '4×');++ await interact(() => getMenuItem(label).click());+ await settleUntil(+ () => commandsMock.generation.submitModelOnlyUpscale.mock.calls.length > 0,+ 'the upscale to queue'+ );++ expect(galleryMock.metadata).toHaveBeenCalledWith('source.png', expect.any(AbortSignal));+ expect(commandsMock.generation.submitModelOnlyUpscale).toHaveBeenCalledWith({+ backendSupportsCancellation: true,+ image: { height: 512, image_name: 'source.png', width: 512 },+ projectId: 'project-1',+ scale,+ sourceMetadata: { positive_prompt: 'a lighthouse' },+ upscaleModel: ultra,+ });+ });++ it('says the upscale could not start when its code fails to load', async () => {+ modelOnlyLoad.fail = true;++ try {+ await openFactorSubMenu(upscaler('ultra', '4x-UltraSharp', 4), '4×');+ await interact(() => getMenuItem('4× (native)').click());+ await settleUntil(() => commandsMock.notifications.add.mock.calls.length > 0, 'the load failure notice');+ } finally {+ modelOnlyLoad.fail = false;+ }++ expect(commandsMock.notifications.add).toHaveBeenCalledWith({+ kind: 'error',+ title: 'widgets.gallery.itemActions.upscale.loadFailed',+ });+ expect(commandsMock.generation.submitModelOnlyUpscale).not.toHaveBeenCalled();+ });++ it('queues nothing and names the image when its metadata cannot be read', async () => {+ galleryMock.metadata.mockRejectedValue(new Error('offline'));+ await openFactorSubMenu(upscaler('ultra', '4x-UltraSharp', 4), '4×');++ await interact(() => getMenuItem('4× (native)').click());+ await settleUntil(() => commandsMock.notifications.add.mock.calls.length > 0, 'the failure notice');++ expect(commandsMock.generation.submitModelOnlyUpscale).not.toHaveBeenCalled();+ expect(commandsMock.notifications.add).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'error', title: 'widgets.gallery.itemActions.upscale.metadataFailed' })+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex f176cc8b52..a21af6291b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -1,5 +1,7 @@import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';import type { GalleryItemContextMenuTarget } from '@features/gallery/react';+import type { ModelsSnapshot } from '@features/models';+import type { SpandrelModelConfig } from '@features/upscale';import type { VideoConditioningRole } from '@features/video';import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';@@ -11,14 +13,17 @@ import {toGalleryItemKey,} from '@features/gallery';import { galleryKeys } from '@features/gallery/queries';+import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { getModelOnlyUpscaleFactors, getSpandrelNativeScale } from '@features/upscale';import { canCopyImage } from '@platform/browser/clipboard';-import { captureAccountScope } from '@platform/state/accountLifecycle';+import { useMountEffect } from '@platform/react/useMountEffect';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { MenuContent, MenuIconItem } from '@platform/ui';import { MenuItem } from '@platform/ui/Menu';import { useQuery } from '@tanstack/react-query';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useActiveProjectId, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ClapperboardIcon,AsteriskIcon,@@ -849,7 +854,7 @@ const SingleImageMenuItems = ({</ContextSubMenu><Menu.Separator borderColor="border.subtle" /><CanvasDestinationMenuItems actions={actions} images={images} isBulk={false} />- <ContextMenuItem icon={ScanIcon} label="Send to Upscale" value="send-to-upscale" onClick={handleSendToUpscale} />+ <UpscaleSubMenu image={image} onSendToUpscale={handleSendToUpscale} /><ContextMenuItemicon={ClapperboardIcon}label="Send to Video"@@ -1107,24 +1112,194 @@ const ChangeBoardSubMenu = ({);};+/** Every installed upscaler, by name; a shallow-equal list keeps the menu from rerendering on unrelated model edits. */+const selectInstalledUpscalers = (snapshot: ModelsSnapshot): SpandrelModelConfig[] =>+ snapshot.models+ .filter((model) => model.type === 'spandrel_image_to_image')+ .map((model) => model as SpandrelModelConfig)+ .sort((a, b) => a.name.localeCompare(b.name));++const selectModelsStatus = (snapshot: ModelsSnapshot): ModelsSnapshot['status'] => snapshot.status;++/**+ * Send to Upscale opens the widget on the image; the items below it upscale the image at once with one upscaler alone,+ * at a factor picked from its submenu, into the gallery, leaving the widget as it is.+ */+const UpscaleSubMenu = ({ image, onSendToUpscale }: { image: GalleryImage; onSendToUpscale: () => void }) => {+ const { t } = useTranslation();+ const upscalers = useModelsSelector(selectInstalledUpscalers);+ const modelsStatus = useModelsSelector(selectModelsStatus);++ useMountEffect(() => {+ void ensureModelsLoaded();+ });++ return (+ <ContextSubMenu icon={ScanIcon} label={t('widgets.gallery.itemActions.upscale.label')}>+ <ContextMenuItem+ icon={ScanIcon}+ label={t('widgets.gallery.itemActions.upscale.sendTo')}+ value="send-to-upscale"+ onClick={onSendToUpscale}+ />+ {upscalers.length === 0 ? (+ // "None installed" only once the library has loaded; until then the list is merely not known yet.+ <MenuItem+ unavailableReason={+ modelsStatus === 'loaded'+ ? t('widgets.gallery.itemActions.upscale.noUpscalers')+ : modelsStatus === 'error'+ ? t('models.couldNotLoad')+ : t('models.loadingModels')+ }+ value="upscale-model-only"+ >+ <Text fontSize="md">{t('widgets.gallery.itemActions.upscale.modelOnlyGroup')}</Text>+ </MenuItem>+ ) : (+ <>+ <Menu.Separator borderColor="border.subtle" />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('widgets.gallery.itemActions.upscale.modelOnlyGroup')}</Menu.ItemGroupLabel>+ {upscalers.map((upscaler) => (+ <ModelOnlyUpscalerSubMenu key={upscaler.key} image={image} upscaler={upscaler} />+ ))}+ </Menu.ItemGroup>+ </>+ )}+ </ContextSubMenu>+ );+};++/**+ * One upscaler's one-click targets: 1.5×, 2× and its native scale, as far as its plan reaches them. An upscaler whose+ * native scale was never recorded can still run once at it, but no other factor can be planned, so those say how to+ * record it.+ */+const ModelOnlyUpscalerSubMenu = ({ image, upscaler }: { image: GalleryImage; upscaler: SpandrelModelConfig }) => {+ const { t } = useTranslation();+ const factors = getModelOnlyUpscaleFactors(upscaler);+ const nativeScale = getSpandrelNativeScale(upscaler);++ return (+ <ContextSubMenu+ detail={+ nativeScale === null ? undefined : t('widgets.gallery.itemActions.upscale.scaleSuffix', { scale: nativeScale })+ }+ label={upscaler.name}+ >+ {factors ? (+ factors.map((factor) => (+ <ModelOnlyUpscaleFactorItem+ key={factor}+ image={image}+ label={t(+ factor === nativeScale+ ? 'widgets.gallery.itemActions.upscale.factorNative'+ : 'widgets.gallery.itemActions.upscale.scaleSuffix',+ { scale: factor }+ )}+ scale={factor === nativeScale ? 'native' : factor}+ upscaler={upscaler}+ />+ ))+ ) : (+ <>+ <ModelOnlyUpscaleFactorItem+ image={image}+ label={t('widgets.gallery.itemActions.upscale.nativeScaleUnknownFactor')}+ scale="native"+ upscaler={upscaler}+ />+ <MenuItem+ unavailableReason={t('widgets.upscale.nativeScaleUnknown')}+ value={`upscale-model-only-${upscaler.key}-other`}+ >+ <Text fontSize="md">{t('widgets.gallery.itemActions.upscale.otherFactors')}</Text>+ </MenuItem>+ </>+ )}+ </ContextSubMenu>+ );+};++const ModelOnlyUpscaleFactorItem = ({+ image,+ label,+ scale,+ upscaler,+}: {+ image: GalleryImage;+ label: string;+ /** `'native'` runs the upscaler once, whether or not its native scale is recorded. */+ scale: number | 'native';+ upscaler: SpandrelModelConfig;+}) => {+ const { t } = useTranslation();+ const commands = useWorkbenchCommands();+ const projectId = useActiveProjectId();+ const handleClick = useCallback(() => {+ // The account the pick was made under, before the command loads.+ const owner = captureAccountScope();++ // Loaded on pick, as Invoke's upscale submission loads it: the menu is part of the editor's startup graph.+ void import('./modelOnlyUpscale')+ .then(({ queueModelOnlyUpscale }) =>+ queueModelOnlyUpscale({+ commands,+ image: { height: image.height, image_name: image.imageName, width: image.width },+ owner,+ projectId,+ scale,+ t,+ upscaleModel: upscaler,+ })+ )+ // The command reports its own failures, so this is its chunk failing to load (a deploy replaced it, the+ // connection dropped): the pick must not go unanswered.+ .catch(() => {+ if (isAccountScopeCurrent(owner)) {+ commands.notifications.add({ kind: 'error', title: t('widgets.gallery.itemActions.upscale.loadFailed') });+ }+ });+ }, [commands, image.height, image.imageName, image.width, projectId, scale, t, upscaler]);++ return (+ <Menu.Item value={`upscale-model-only-${upscaler.key}-${scale}`} onClick={handleClick}>+ <Text fontSize="md" fontVariantNumeric="tabular-nums">+ {label}+ </Text>+ </Menu.Item>+ );+};+const ContextSubMenu = ({children,+ detail,icon,label,scrollArea,}: {children: ReactNode;- icon: LucideIcon;+ /** A short value after the label, such as an upscaler's native scale. */+ detail?: string;+ icon?: LucideIcon;label: string;scrollArea?: boolean;}) => (<Menu.Root positioning={MENU_POSITIONING_PROPS}><Menu.TriggerItem><HStack gap="2" minW="0" w="full">- <Icon as={icon} boxSize="3.5" color="fg.subtle" flexShrink={0} />- <Text flex="1" fontSize="md">+ {icon ? <Icon as={icon} boxSize="3.5" color="fg.subtle" flexShrink={0} /> : null}+ <Text flex="1" fontSize="md" minW="0" truncate>{label}</Text>+ {detail ? (+ // Secondary to the label, but at the menu's secondary-text contrast: fg.subtle is too faint on dark menus.+ <Text color="fg.muted" flexShrink={0} fontFamily="mono" fontSize="sm">+ {detail}+ </Text>+ ) : null}<Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} /></HStack></Menu.TriggerItem>diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.tsindex 9599e48d22..2893b7d66a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts@@ -283,7 +283,7 @@ describe('placeVideoImage', () => {expect(referenceNames(placement)).toEqual(['dance.mp4', 'new.png']);});- it('appends after the held references, with the detail a later image defaults to', () => {+ it('appends after the held references, matching the generation size', () => {const placement = placeVideoImage({append: true,image: still('new.png'),@@ -295,7 +295,7 @@ describe('placeVideoImage', () => {expect(placement.status === 'placed' && placement.patch.references?.at(-1)).toMatchObject({ detail: 'match' });});- it('gives the first reference image max detail', () => {+ it('gives the first reference image the generation-matched detail too', () => {const placement = placeVideoImage({append: false,image: still('new.png'),@@ -303,7 +303,8 @@ describe('placeVideoImage', () => {videoValues: panel(REF2VA, { references: held }),});- expect(placement.status === 'placed' && placement.patch.references?.at(-1)).toMatchObject({ detail: 'max' });+ expect(referenceNames(placement)).toEqual(['dance.mp4', 'new.png']);+ expect(placement.status === 'placed' && placement.patch.references?.at(-1)).toMatchObject({ detail: 'match' });});it('keeps a reference-extend continuity anchor last', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.tsindex 9a2e6cda90..f9c9199597 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts@@ -19,7 +19,7 @@ import {createVideoSourceClip,getConditioningClipPatch,getDefaultReferenceConditioning,- getDefaultReferenceImageDetail,+ DEFAULT_REFERENCE_IMAGE_DETAIL,getFrameImagePatch,getInitialVideoPatch,getReferencesPatch,@@ -664,7 +664,7 @@ export const placeVideoImage = ({displaced: Boolean(values.conditioningClip || (values.sourceVideo && !referenceExtend)),patch: getReferencesPatch({referenceExtend,- references: [...kept, { detail: getDefaultReferenceImageDetail(kept), image, kind: 'image' }],+ references: [...kept, { detail: DEFAULT_REFERENCE_IMAGE_DETAIL, image, kind: 'image' }],}),slot: 'reference',status: 'placed',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex f73f392294..800ef1f7e9 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -143,6 +143,7 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWiqwen3VLEncoderModel: null,qwen35EncoderModel: null,animaInpaintAdapterModel: null,+ animaInpaintAdapterEnabled: true,animaInpaintAdapterWeight: 1,wanT5EncoderModel: null,wanLowNoiseModel: null,@@ -1546,7 +1547,7 @@ describe('anima inpaint adapter', () => {expect(result?.fields).toContain('animaInpaintAdapterWeight');});- it('clears a stale adapter from an Anima inpaint record that lacks the key, which the backend persists for none', () => {+ it('switches the adapter off but keeps the pick for an Anima inpaint record that lacks the key, which the backend persists for none', () => {const currentValues = createValues({ animaInpaintAdapterModel: inpaintAdapter, animaInpaintAdapterWeight: 0.5 });const {anima_inpaint_adapter: _adapter,@@ -1565,26 +1566,57 @@ describe('anima inpaint adapter', () => {});for (const generation_mode of ['anima_inpaint', 'anima_outpaint']) {- const cleared = recall({ ...withoutAdapter, generation_mode });- expect(cleared?.values.animaInpaintAdapterModel).toBeNull();- expect(cleared?.values.animaInpaintAdapterWeight).toBe(0.5);- expect(cleared?.fields).toContain('components');- expect(cleared?.fields).not.toContain('animaInpaintAdapterWeight');+ const switchedOff = recall({ ...withoutAdapter, generation_mode });+ expect(switchedOff?.values.animaInpaintAdapterEnabled).toBe(false);+ expect(switchedOff?.values.animaInpaintAdapterModel).toEqual(inpaintAdapter);+ expect(switchedOff?.values.animaInpaintAdapterWeight).toBe(0.5);+ expect(switchedOff?.fields).toContain('components');+ expect(switchedOff?.fields).not.toContain('animaInpaintAdapterWeight');}// A record from a mode that never writes the key, or none at all, says nothing about the adapter.- expect(recall(withoutAdapter)?.values.animaInpaintAdapterModel).toEqual(inpaintAdapter);- expect(recall({ ...withoutAdapter, generation_mode: 'anima_img2img' })?.values.animaInpaintAdapterModel).toEqual(- inpaintAdapter- );+ for (const metadata of [withoutAdapter, { ...withoutAdapter, generation_mode: 'anima_img2img' }]) {+ const untouched = recall(metadata);+ expect(untouched?.values.animaInpaintAdapterModel).toEqual(inpaintAdapter);+ expect(untouched?.values.animaInpaintAdapterEnabled).toBe(true);+ }const notAnima = recall({ generation_mode: 'inpaint', model: { key: sd1Model.key } }, [sd1Model, animaModel]);expect(notAnima?.values.model).toBe(sd1Model);+ expect(notAnima?.values.animaInpaintAdapterEnabled).toBe(true);expect(notAnima?.fields).not.toContain('components');+ });++ it('switches the adapter back on with the recorded pick when an inpaint record has the key', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({ animaInpaintAdapterEnabled: false, animaInpaintAdapterModel: null }),+ image,+ kind: 'all',+ metadata: { ...canvasInpaintMetadata, generation_mode: 'anima_inpaint' },+ models,+ supportedModels: [animaModel],+ vaeModels: [qwenImageVae],+ });- // The key present on such a record still sets the adapter.- const restored = recall({ ...canvasInpaintMetadata, generation_mode: 'anima_inpaint' });- expect(restored?.values.animaInpaintAdapterModel).toBe(inpaintAdapter);- expect(restored?.values.animaInpaintAdapterWeight).toBe(0.7);+ expect(result?.values.animaInpaintAdapterEnabled).toBe(true);+ expect(result?.values.animaInpaintAdapterModel).toBe(inpaintAdapter);+ expect(result?.values.animaInpaintAdapterWeight).toBe(0.7);+ expect(result?.fields).toContain('components');+ });++ it('reports a switch-only change and offers Recall All for it', () => {+ const currentValues = createValues({+ animaInpaintAdapterModel: inpaintAdapter,+ model: animaModel,+ modelKey: animaModel.key,+ });+ const metadata = { generation_mode: 'anima_outpaint' };+ const input = { currentValues, image, metadata, models, supportedModels: [animaModel], vaeModels: [qwenImageVae] };++ expect(getImageRecallCapabilities(input).all).toBe(true);+ const result = buildImageRecallSettings({ ...input, kind: 'all' });+ expect(result?.values.animaInpaintAdapterEnabled).toBe(false);+ expect(result?.values.animaInpaintAdapterModel).toEqual(inpaintAdapter);+ expect(result?.fields).toEqual(['components']);});it.each([diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex 969b347fb3..8d42e3fd3d 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -569,25 +569,40 @@ const getMetadataModelTuning = (const hasModelTuning = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>Object.keys(getMetadataModelTuning(metadata, model)).length > 0;+/** The canvas inpaint and outpaint graphs record the adapter key whenever the adapter ran. */+const ANIMA_INPAINT_ADAPTER_MODES: readonly string[] = ['anima_inpaint', 'anima_outpaint'];+/**- * The canvas records the adapter's weight beside the adapter; only an Anima image can carry it. An out-of-range- * weight is clamped rather than applied, which would block every inpaint until the user edits it.+ * The adapter switch and weight; only an Anima image can carry them. A recorded adapter means it ran, so the switch+ * turns on. `core_metadata` drops `null` on write, so an inpaint or outpaint record without the key ran without one:+ * the switch turns off and the current pick stays for the next time it is wanted. Other records say nothing about+ * it. An out-of-range weight is clamped rather than applied, which would block every inpaint until the user edits it.*/-const getMetadataAnimaInpaintAdapterWeight = (+const getMetadataAnimaInpaintAdapter = (metadata: unknown,model: GenerateModelConfig | undefined-): Partial<GenerateWidgetValues> => {- if (model?.base !== 'anima') {+): Partial<Pick<GenerateWidgetValues, 'animaInpaintAdapterEnabled' | 'animaInpaintAdapterWeight'>> => {+ if (model?.base !== 'anima' || !isRecord(metadata)) {return {};}const weight = getNumber(metadata, 'anima_inpaint_adapter_weight');+ const mode = getString(metadata, 'generation_mode');+ const enabled =+ 'anima_inpaint_adapter' in metadata+ ? true+ : mode !== null && ANIMA_INPAINT_ADAPTER_MODES.includes(mode)+ ? false+ : null;- return weight === null ? {} : { animaInpaintAdapterWeight: clampAnimaInpaintAdapterWeight(weight) };+ return {+ ...(enabled === null ? {} : { animaInpaintAdapterEnabled: enabled }),+ ...(weight === null ? {} : { animaInpaintAdapterWeight: clampAnimaInpaintAdapterWeight(weight) }),+ };};-const hasAnimaInpaintAdapterWeight = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>- Object.keys(getMetadataAnimaInpaintAdapterWeight(metadata, model)).length > 0;+const hasAnimaInpaintAdapterSettings = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>+ Object.keys(getMetadataAnimaInpaintAdapter(metadata, model)).length > 0;type RecalledComponentSetting = keyof Pick<GenerateWidgetValues,@@ -612,12 +627,6 @@ interface RecalledComponent {setting: RecalledComponentSetting;/** The setting holds a main model (a component source or second transformer), not an encoder. */isMainModel?: true;- /**- * The `generation_mode` values whose graphs record the key whenever the component ran. `core_metadata` drops- * `null` on write, so on these records an absent key means "none" and clears the slot; elsewhere it means- * "unknown" and keeps the current pick.- */- absentMeansNoneIn?: readonly string[];}/**@@ -630,11 +639,7 @@ const RECALLED_COMPONENTS: readonly RecalledComponent[] = [{ isMainModel: true, metadataKey: 'wan_component_source', setting: 'componentSourceModel' },{ isMainModel: true, metadataKey: 'ideogram4_unconditional_model', setting: 'ideogram4UnconditionalModel' },{ isMainModel: true, metadataKey: 'wan_transformer_low_noise', setting: 'wanLowNoiseModel' },- {- absentMeansNoneIn: ['anima_inpaint', 'anima_outpaint'],- metadataKey: 'anima_inpaint_adapter',- setting: 'animaInpaintAdapterModel',- },+ { metadataKey: 'anima_inpaint_adapter', setting: 'animaInpaintAdapterModel' },{ metadataKey: 'clip_embed_model', setting: 'clipEmbedModel' },{ metadataKey: 'gemma2_encoder', setting: 'gemma2EncoderModel' },{ metadataKey: 'mistral_encoder', setting: 'mistralEncoderModel' },@@ -651,17 +656,10 @@ const getRecalledComponent = (metadata: unknown,component: RecalledComponent,models: readonly ComponentModelConfig[]-): ComponentModelConfig | null | undefined => {- if (isRecord(metadata) && !(component.metadataKey in metadata) && component.absentMeansNoneIn) {- const mode = getString(metadata, 'generation_mode');-- return mode !== null && component.absentMeansNoneIn.includes(mode) ? null : undefined;- }-- return component.isMainModel+): ComponentModelConfig | null | undefined =>+ component.isMainModel? getMetadataMainModel(metadata, component.metadataKey, models): getMetadataComponent(metadata, component.metadataKey, models);-};/** Recorded components that resolve to installed models; `null` clears a slot the image left empty. */const getComponentPatch = (@@ -1066,7 +1064,7 @@ export const getImageRecallCapabilities = ({const hasTuning = hasModelTuning(metadata, clipSkipModel);const hasRefiner =Object.keys(getRefinerRecall(metadata, clipSkipModel, models, supportedMetadataModel).patch).length > 0;- const hasAdapterWeight = hasAnimaInpaintAdapterWeight(metadata, clipSkipModel);+ const hasAdapterSettings = hasAnimaInpaintAdapterSettings(metadata, clipSkipModel);const hasConcepts =(getMetadataConcepts(metadata, models, clipSkipModel, supportedMetadataModel).loras?.length ?? 0) > 0;const hasAnyMetadata =@@ -1084,7 +1082,7 @@ export const getImageRecallCapabilities = ({hasRebalance ||hasRefiner ||hasTuning ||- hasAdapterWeight;+ hasAdapterSettings;const hasNonSeedMetadata =hasModel ||hasVae ||@@ -1099,7 +1097,7 @@ export const getImageRecallCapabilities = ({hasRebalance ||hasRefiner ||hasTuning ||- hasAdapterWeight;+ hasAdapterSettings;return {all: hasAnyMetadata && isImageRecallKindAvailable('all'),@@ -1184,10 +1182,10 @@ export const buildImageRecallSettings = ({fields.push('modelTuning');}- const adapterWeightPatch = getMetadataAnimaInpaintAdapterWeight(metadata, values.model);+ const adapterPatch = getMetadataAnimaInpaintAdapter(metadata, values.model);+ values = { ...values, ...adapterPatch };- if (Object.keys(adapterWeightPatch).length > 0) {- values = { ...values, ...adapterWeightPatch };+ if (adapterPatch.animaInpaintAdapterWeight !== undefined) {fields.push('animaInpaintAdapterWeight');}@@ -1205,8 +1203,12 @@ export const buildImageRecallSettings = ({values = { ...values, ...settings };}- // Judged after the transition, which can complete or undo a recorded pick.- if (recordedSettings.some((setting) => values[setting]?.key !== currentValues[setting]?.key)) {+ // Judged after the transition, which can complete or undo a recorded pick. The adapter switch is a component+ // change too: a record can turn it off without touching the pick.+ if (+ recordedSettings.some((setting) => values[setting]?.key !== currentValues[setting]?.key) ||+ values.animaInpaintAdapterEnabled !== currentValues.animaInpaintAdapterEnabled+ ) {fields.push('components');}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/modelOnlyUpscale.ts b/invokeai/frontend/webv2/src/workbench/image-actions/modelOnlyUpscale.tsnew file mode 100644index 0000000000..f1a8197d7b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/modelOnlyUpscale.ts@@ -0,0 +1,65 @@+import type { ImageWithDims } from '@features/generation/contracts';+import type { SpandrelModelConfig } from '@features/upscale';+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { WorkbenchCommands } from '@workbench/workbenchStore';+import type { TFunction } from 'i18next';++import { ensureGalleryBoardDestinations } from '@features/gallery/queries';+import { readUpscaleSourceMetadata } from '@features/upscale/sourceMetadata';+import { queryClient } from '@platform/query/client';+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';++/**+ * The image menu's one-click upscale: read the image's metadata, then queue the upscaler alone on it at `scale` (`'native'`,+ * or another of `getModelOnlyUpscaleFactors`). Results go to the gallery's auto-add board, so its listing is read alongside when none+ * is cached, as an Invoke to the gallery does.+ */+export const queueModelOnlyUpscale = async ({+ commands,+ image,+ owner,+ projectId,+ scale,+ t,+ upscaleModel,+}: {+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;+ image: ImageWithDims;+ owner: AccountScope;+ projectId: string;+ scale: number | 'native';+ t: TFunction;+ upscaleModel: SpandrelModelConfig;+}): Promise<void> => {+ let sourceMetadata: Record<string, unknown> | null;++ try {+ [sourceMetadata] = await Promise.all([+ readUpscaleSourceMetadata(image.image_name, owner.signal),+ ensureGalleryBoardDestinations(queryClient),+ ]);+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ commands.notifications.add({+ kind: 'error',+ message: getApiErrorMessage(error, String(error)),+ title: t('widgets.gallery.itemActions.upscale.metadataFailed', { name: image.image_name }),+ });+ }+ return;+ }++ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ commands.generation.submitModelOnlyUpscale({+ backendSupportsCancellation: true,+ image,+ projectId,+ scale,+ sourceMetadata,+ upscaleModel,+ });+};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.tsindex 9032a5f512..a47690057a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts@@ -520,7 +520,7 @@ describe('createVideoRecallRuntime', () => {await flush();expect(videoValues().references).toEqual([- { detail: 'max', image: { height: 512, image_name: 'a.png', width: 512 }, kind: 'image' },+ { detail: 'match', image: { height: 512, image_name: 'a.png', width: 512 }, kind: 'image' },{ detail: 'match', image: { height: 512, image_name: 'b.png', width: 512 }, kind: 'image' },]);expect(lastNotice()).toMatchObject({ kind: 'success', title: 'widgets.video.placement.referenceImageAdded' });diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.tsindex adb067e843..b3ecc0d792 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts@@ -36,6 +36,7 @@ import { createWorkbenchStore } from './workbenchStore';// Production words rejections from the locale; tests only need the structured rejection to reach the notice.const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;+const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };@@ -432,6 +433,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner,prepareCanvasInvocation,@@ -466,6 +468,7 @@ describe('submitResolvedInvocation', () => {const submission = submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -496,6 +499,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -525,6 +529,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -550,6 +555,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -572,6 +578,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands: store.commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -623,6 +630,7 @@ describe('submitResolvedInvocation', () => {submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner,prepareCanvasInvocation,diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.tsindex 5c50de2aad..090d619835 100644--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts@@ -14,6 +14,13 @@ export interface ExpandedPositivePrompts {positivePromptsSampleSeed: number | null;}+/** The metadata a Model only upscale copies, with the image it was read from, so a changed input is never mislabelled. */+export interface UpscaleSourceMetadata {+ imageName: string;+ /** Null when the image has none. */+ metadata: Record<string, unknown> | null;+}+export interface InvocationRoute {sourceId: InvocationSourceId;destination: ResultDestination;diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsxindex b8c00d4311..42e11f84bb 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.browser.test.tsx@@ -107,6 +107,7 @@ const submitGenerate = () => {const submission = submitResolvedInvocation({commands,formatControlLayerError: ({ code, layerName }) => `${layerName}: ${code}`,+ formatUpscaleMetadataFailure: (name) => name,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.tsindex d904fdfb18..8be6c11953 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts@@ -4,8 +4,10 @@ import type { InvocationRoute } from '@workbench/invocationContracts';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { dynamicPromptsKeys } from '@features/generation/prompts';import { getDefaultGenerateSettings } from '@features/generation/settings';+import { createDefaultUpscaleWidgetValues } from '@features/upscale';import { queryClient } from '@platform/query/client';import { captureAccountScope } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';import { beforeEach, describe, expect, it, vi } from 'vitest';const templatesMock = vi.hoisted(() => ({@@ -20,6 +22,16 @@ const generatorsMock = vi.hoisted(() => ({ resolveWorkflowGenerators: vi.fn() })const galleryQueriesMock = vi.hoisted(() => ({ensureGalleryBoardDestinations: vi.fn((): Promise<void> | null => null),}));+const galleryMock = vi.hoisted(() => ({+ metadata: vi.fn((_imageName: string, _signal?: AbortSignal): Promise<Record<string, unknown> | null> =>+ Promise.resolve(null)+ ),+}));+vi.mock('@features/gallery', async (importOriginal) => {+ const original = await importOriginal<{ galleryImages: Record<string, unknown> }>();++ return { ...original, galleryImages: { ...original.galleryImages, metadata: galleryMock.metadata } };+});vi.mock('@features/gallery/queries', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),ensureGalleryBoardDestinations: galleryQueriesMock.ensureGalleryBoardDestinations,@@ -51,6 +63,7 @@ import { createWorkbenchStore } from './workbenchStore';// Production words rejections from the locale; tests only need the structured rejection to reach the notice.const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;+const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;const field = (name: string, typeName: string, overrides: Record<string, unknown> = {}) => ({default: undefined,@@ -187,6 +200,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -230,6 +244,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {const submission = submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -297,6 +312,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -316,6 +332,7 @@ describe('submitResolvedInvocation with a workflow generator', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -409,6 +426,7 @@ describe('submitResolvedInvocation with a random dynamic prompt', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation,@@ -468,6 +486,7 @@ describe('submitResolvedInvocation without dynamic prompts', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -505,6 +524,7 @@ describe('submitResolvedInvocation without dynamic prompts', () => {await submitResolvedInvocation({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models: undefined,owner: captureAccountScope(),prepareCanvasInvocation: vi.fn(),@@ -517,3 +537,100 @@ describe('submitResolvedInvocation without dynamic prompts', () => {expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ prepend: true });});});++describe('submitResolvedInvocation for Upscale', () => {+ const upscaler = {+ base: 'any',+ file_size: 1,+ format: 'checkpoint',+ hash: 'ultrasharp-hash',+ key: 'ultrasharp',+ name: '4x-UltraSharp',+ path: 'ultrasharp',+ scale: 4,+ source: 'ultrasharp',+ source_type: 'path',+ type: 'spandrel_image_to_image',+ } as const;+ const upscaleRoute: InvocationRoute = {+ destination: 'gallery',+ destinationLocked: false,+ sourceId: 'upscale',+ sourceLocked: false,+ };++ beforeEach(() => {+ galleryMock.metadata.mockReset();+ });++ const submit = async (mode: 'refine' | 'model-only') => {+ const state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: {+ ...createDefaultUpscaleWidgetValues([upscaler]),+ inputImage: { height: 64, image_name: 'input.png', width: 64 },+ mode,+ },+ widgetId: 'upscale',+ });+ const project = getActiveProject(state);+ const commands = createWorkbenchStore().commands;+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');+ const notify = vi.spyOn(commands.notifications, 'add');++ await submitResolvedInvocation({+ commands,+ formatControlLayerError,+ formatUpscaleMetadataFailure,+ models: [upscaler],+ owner: captureAccountScope(),+ prepareCanvasInvocation: vi.fn(),+ project,+ route: resolveInvocationRoute(project, 'global', upscaleRoute, [upscaler]),+ });++ return { notify, submitResolved };+ };++ it("reads a Model only input's metadata once and dispatches it with the image it was read for", async () => {+ galleryMock.metadata.mockResolvedValue({ positive_prompt: 'a lighthouse' });++ const { notify, submitResolved } = await submit('model-only');++ expect(galleryMock.metadata).toHaveBeenCalledTimes(1);+ expect(galleryMock.metadata.mock.calls[0]?.[0]).toBe('input.png');+ expect(notify).not.toHaveBeenCalled();+ expect(submitResolved).toHaveBeenCalledTimes(1);+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({+ upscaleSourceMetadata: { imageName: 'input.png', metadata: { positive_prompt: 'a lighthouse' } },+ });+ });++ it('dispatches an image the server has no metadata for with none to copy', async () => {+ galleryMock.metadata.mockRejectedValue(new ApiError('{"detail":"Image not found"}', 404));++ const { submitResolved } = await submit('model-only');++ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({+ upscaleSourceMetadata: { imageName: 'input.png', metadata: null },+ });+ });++ it('queues nothing and names the image when the metadata read fails', async () => {+ galleryMock.metadata.mockRejectedValue(new ApiError('{"detail":"Database is locked"}', 500));++ const { notify, submitResolved } = await submit('model-only');++ expect(submitResolved).not.toHaveBeenCalled();+ expect(notify).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'error', message: 'Database is locked', title: 'metadataFailed: input.png' })+ );+ });++ it('reads no metadata for Refine, which records its own', async () => {+ const { submitResolved } = await submit('refine');++ expect(galleryMock.metadata).not.toHaveBeenCalled();+ expect(submitResolved.mock.calls[0]?.[0]).not.toHaveProperty('upscaleSourceMetadata');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.tsindex 194509ceb9..4f5322e4a4 100644--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts@@ -9,7 +9,11 @@ import type { ModelConfig } from '@features/models';import type { ProjectGraphState } from '@features/workflow/contracts';import type { WorkflowGeneratorResolutions, WorkflowPendingGenerator } from '@features/workflow/utility';import type { AccountScope } from '@platform/state/accountLifecycle';-import type { ExpandedPositivePrompts, ResolvedInvocationRoute } from '@workbench/invocationContracts';+import type {+ ExpandedPositivePrompts,+ ResolvedInvocationRoute,+ UpscaleSourceMetadata,+} from '@workbench/invocationContracts';import type { Project } from '@workbench/projectContracts';import { ensureGalleryBoardDestinations } from '@features/gallery/queries';@@ -20,11 +24,13 @@ import {normalizeGenerateSettings,sanitizeBatchCount,} from '@features/generation/settings';+import { normalizeUpscaleWidgetValues } from '@features/upscale';import { getWorkflowBatchCapReason } from '@features/workflow/graph';import { getInvocationTemplatesSnapshot } from '@features/workflow/react';import { planWorkflowBatch } from '@features/workflow/utility';import { queryClient } from '@platform/query/client';import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';import type { WorkbenchCommands } from './workbenchStore';@@ -39,6 +45,33 @@ const EXPANSION_FAILED_TITLE = 'The prompt could not be expanded';const GENERATOR_FAILED_TITLE = 'The batch generator could not be resolved';const BATCH_NOT_READY_TITLE = 'The batch is not ready';+/** Settled, never rejected: it may fail while the board listing is still awaited, before anything awaits it. */+type UpscaleSourceMetadataRead = UpscaleSourceMetadata | { error: unknown; imageName: string };++/** Upscale in Model only mode copies its input's metadata into the result, so it is read before dispatch. */+const readModelOnlyUpscaleSourceMetadata = (+ project: Project,+ route: ResolvedInvocationRoute,+ owner: AccountScope+): Promise<UpscaleSourceMetadataRead> | null => {+ if (route.sourceId !== 'upscale') {+ return null;+ }++ const values = normalizeUpscaleWidgetValues(getProjectWidgetValues(project, 'upscale'));+ const imageName = values?.mode === 'model-only' ? values.inputImage?.image_name : undefined;++ // Loaded on demand: the reader's gallery transport stays out of the editor's startup graph.+ return imageName+ ? import('@features/upscale/sourceMetadata')+ .then(({ readUpscaleSourceMetadata }) => readUpscaleSourceMetadata(imageName, owner.signal))+ .then(+ (metadata) => ({ imageName, metadata }),+ (error: unknown) => ({ error, imageName })+ )+ : null;+};+export interface SubmitResolvedInvocationDeps {/** The resolved route to submit — the caller has already checked it is valid. */route: ResolvedInvocationRoute;@@ -63,6 +96,8 @@ export interface SubmitResolvedInvocationDeps {prepareCanvasInvocation: (args: PrepareCanvasInvocationArgs) => Promise<void> | void;/** Words a control-layer rejection from the locale; its error message is for logs only. */formatControlLayerError: PrepareCanvasInvocationArgs['formatControlLayerError'];+ /** Words, from the locale, a Model only upscale whose input image's metadata could not be read. */+ formatUpscaleMetadataFailure: (imageName: string) => string;}/**@@ -178,6 +213,7 @@ const resolveWorkflowGeneratorsForRoute = async (export const submitResolvedInvocation = async ({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation,@@ -206,6 +242,8 @@ export const submitResolvedInvocation = async ({route.destination === 'gallery' || route.sourceId === 'workflow'? ensureGalleryBoardDestinations(queryClient): null;+ // Upscale routes have no other asynchronous step, so this is awaited at dispatch, alongside the board listing.+ const pendingUpscaleMetadata = readModelOnlyUpscaleSourceMetadata(project, route, owner);// Only a workflow with unresolved generators needs this round trip; every other route dispatches synchronously.const pendingGenerators = getPendingWorkflowGenerators(workflowDocument, route);@@ -254,6 +292,7 @@ export const submitResolvedInvocation = async ({{commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation,@@ -267,17 +306,30 @@ export const submitResolvedInvocation = async ({: undefined,workflowGenerators,workflowDocument?.id,- pendingBoards+ pendingBoards,+ pendingUpscaleMetadata);return;}await dispatchResolvedInvocation(- { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, prepend, project, route, workflowId },+ {+ commands,+ formatControlLayerError,+ formatUpscaleMetadataFailure,+ models,+ owner,+ prepareCanvasInvocation,+ prepend,+ project,+ route,+ workflowId,+ },undefined,workflowGenerators,workflowDocument?.id,- pendingBoards+ pendingBoards,+ pendingUpscaleMetadata);};@@ -285,6 +337,7 @@ const dispatchResolvedInvocation = async ({commands,formatControlLayerError,+ formatUpscaleMetadataFailure,models,owner,prepareCanvasInvocation,@@ -295,7 +348,8 @@ const dispatchResolvedInvocation = async (expansion: ExpandedPositivePrompts | undefined,workflowGenerators: WorkflowGeneratorResolutions | undefined,workflowId: string | undefined,- pendingBoards: Promise<void> | null+ pendingBoards: Promise<void> | null,+ pendingUpscaleMetadata: Promise<UpscaleSourceMetadataRead> | null = null): Promise<void> => {// The board listing the destination is judged from, read while the rest was resolved when none was cached;// nothing to wait for keeps the dispatch synchronous.@@ -306,6 +360,25 @@ const dispatchResolvedInvocation = async (}}+ let upscaleSourceMetadata: UpscaleSourceMetadata | undefined;++ if (pendingUpscaleMetadata) {+ const read = await pendingUpscaleMetadata;++ if (!isAccountScopeCurrent(owner)) {+ return;+ }+ if ('error' in read) {+ commands.notifications.add({+ kind: 'error',+ message: getApiErrorMessage(read.error, String(read.error)),+ title: formatUpscaleMetadataFailure(read.imageName),+ });+ return;+ }+ upscaleSourceMetadata = read;+ }+if (route.sourceId === 'canvas') {// Await Canvas preparation to retain the submission guard until completion; pass the resolved destination so// Canvas can output to Gallery.@@ -334,6 +407,7 @@ const dispatchResolvedInvocation = async (...(prepend ? { prepend } : {}),projectId: project.id,route,+ ...(upscaleSourceMetadata ? { upscaleSourceMetadata } : {}),...(workflowGenerators ? { workflowGenerators } : {}),...(workflowId ? { workflowId } : {}),});diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex f17c801f54..e9081b2859 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -75,6 +75,8 @@ export interface WorkbenchPreferences {notifyOnEnqueue: boolean;/** Project export carries the exporter's workspace (layout, generation settings, prompt history); the last choice. */exportIncludesWorkspace: boolean;+ /** Add Models installs local files where they are instead of moving them into the models folder; the last choice. */+ installInPlace: boolean;/** Write numeric attention weights (`(word)1.1`) when the attention hotkeys insert them. */preferNumericAttentionStyle: boolean;/** Color prompt syntax in prompt fields; changes rendering only. */diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex a52fae11db..818d006975 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -411,6 +411,24 @@ describe('normalizeWorkbenchPreferences appearance', () => {});});+describe('installInPlace preference', () => {+ it('installs in place unless the account stored the box unticked', () => {+ expect(store.normalizeWorkbenchPreferences({}).installInPlace).toBe(true);+ expect(store.normalizeWorkbenchPreferences({ installInPlace: 'false' as never }).installInPlace).toBe(true);+ expect(store.normalizeWorkbenchPreferences({ installInPlace: false }).installInPlace).toBe(false);+ });++ it('keeps an unticked box across a reload of the account settings', async () => {+ await store.loadWorkbenchSettings();+ await store.patchWorkbenchPreferences({ installInPlace: false });++ vi.resetModules();+ store = await import('./store');++ expect((await store.loadWorkbenchSettings()).installInPlace).toBe(false);+ });+});+describe('normalizeWorkbenchPreferences workflow editor', () => {it('keeps connections above nodes unless the preference is explicitly on', () => {expect(store.normalizeWorkbenchPreferences({}).workflowEdgesBehindNodes).toBe(false);diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 28b1b2093e..d5637800b2 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -61,6 +61,7 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {generatePresets: [],generateSectionsOpen: {},highContrast: false,+ installInPlace: true,krea2RebalancePresets: [],language: 'en',launchpadPinnedProjectIds: [],@@ -325,6 +326,8 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferences: DEFAULT_PREFERENCES.exportIncludesWorkspace,generatePresets: normalizeGeneratePresets(preferences?.generatePresets),generateSectionsOpen: normalizeGenerateSectionsOpen(preferences?.generateSectionsOpen),+ installInPlace:+ typeof preferences?.installInPlace === 'boolean' ? preferences.installInPlace : DEFAULT_PREFERENCES.installInPlace,krea2RebalancePresets: normalizeRebalancePresets(preferences?.krea2RebalancePresets),language: normalizeWorkbenchLanguage(preferences?.language) ?? DEFAULT_PREFERENCES.language,launchpadPinnedProjectIds: normalizePinnedProjectIds(preferences?.launchpadPinnedProjectIds),diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsxnew file mode 100644index 0000000000..9b1976b42d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsx@@ -0,0 +1,96 @@+import type { Project } from '@workbench/projectContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({ patchValues: vi.fn(), project: null as unknown }));++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project as Project),+ useWorkbenchCommands: () => ({+ generation: { setBatchCount: vi.fn() },+ widgets: { patchValues: harness.patchValues },+ }),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';++import { IterationsField } from './IterationsField';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ harness.patchValues.mockReset();+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++const renderForUpscale = async (mode: 'refine' | 'model-only') => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: { batchCount: 3, mode },+ widgetId: 'upscale',+ });+ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });+ harness.project = state.projects.find((project) => project.id === state.activeProjectId);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <IterationsField />+ </ChakraProvider>+ );+ });++ return host.querySelector<HTMLInputElement>('input[aria-label="topbar.iterations.label"]')!;+};++const stepUp = async (input: HTMLInputElement) => {+ await act(() => {+ input.focus();+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowUp' }));+ });+};++describe('IterationsField for Upscale', () => {+ it("edits Refine's iterations", async () => {+ const input = await renderForUpscale('refine');++ expect(input.value).toBe('3');+ expect(input.getAttribute('aria-describedby')).toBeNull();++ await stepUp(input);++ expect(harness.patchValues).toHaveBeenCalledWith('upscale', { batchCount: 4 });+ });++ it('holds Model only at one run and says why, keeping the field focusable', async () => {+ const input = await renderForUpscale('model-only');++ expect(input.value).toBe('1');+ expect(input.disabled).toBe(false);+ expect(input.getAttribute('aria-disabled')).toBe('true');+ expect(document.getElementById(input.getAttribute('aria-describedby') ?? '')?.textContent).toBe(+ 'topbar.iterations.fixedModelOnly'+ );++ await stepUp(input);++ expect(document.activeElement).toBe(input);+ expect(input.value).toBe('1');+ expect(harness.patchValues).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsxindex 5fe2cea561..418ea7c3e3 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx@@ -1,12 +1,12 @@-import { NumberInput } from '@chakra-ui/react';+import { NumberInput, VisuallyHidden } from '@chakra-ui/react';import { MIN_BATCH_COUNT } from '@features/generation/settings';import { Tooltip } from '@platform/ui/Tooltip';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { useCallback } from 'react';+import { useCallback, useId } from 'react';import { useTranslation } from 'react-i18next';-import { getBatchCount } from './useInvocationState';+import { getBatchCount, isBatchCountFixed } from './useInvocationState';/*** Invoke's rounded corners overlap this field, so its edge facing Invoke is hidden and a tail continues the frame@@ -29,17 +29,24 @@ const TAIL_UNDER_INVOKE_AFTER_CSS = {export const IterationsField = () => {const { t } = useTranslation();- const { batchCount, sourceId } = useActiveProjectSelector(+ const { batchCount, isFixed, sourceId } = useActiveProjectSelector((project) => {const sourceId = project.invocation.sourceId;const typeId = sourceId === 'upscale' || sourceId === 'video' || sourceId === 'workflow' ? sourceId : 'generate';-// The same resolution the patch command writes through, so reader and writer agree on the instance.- return { batchCount: getBatchCount(getProjectWidgetValues(project, typeId)), sourceId };+ const values = getProjectWidgetValues(project, typeId);++ return {+ batchCount: getBatchCount(sourceId, values),+ isFixed: isBatchCountFixed(sourceId, values),+ sourceId,+ };},- (left, right) => left.batchCount === right.batchCount && left.sourceId === right.sourceId+ (left, right) =>+ left.batchCount === right.batchCount && left.isFixed === right.isFixed && left.sourceId === right.sourceId);const { generation, widgets } = useWorkbenchCommands();+ const fixedReasonId = useId();const handleValueChange = useCallback(({ valueAsNumber }: { valueAsNumber: number }) => {if (!Number.isFinite(valueAsNumber)) {@@ -56,11 +63,19 @@ export const IterationsField = () => {);return (- <Tooltip content={t('topbar.iterations.tooltip', { count: batchCount })} showArrow>+ <Tooltip+ content={isFixed ? t('topbar.iterations.fixedModelOnly') : t('topbar.iterations.tooltip', { count: batchCount })}+ showArrow+ >+ {/* Read-only rather than disabled while the count is fixed: the field keeps its focus and its tooltip, which+ say why it cannot change. */}<NumberInput.RootallowMouseWheelcss={TAIL_UNDER_INVOKE_AFTER_CSS}+ cursor={isFixed ? 'not-allowed' : undefined}flexShrink={0}+ opacity={isFixed ? 0.55 : undefined}+ readOnly={isFixed}min={MIN_BATCH_COUNT}rounded="control"size="lg"@@ -71,7 +86,14 @@ export const IterationsField = () => {<NumberInput.Control />{/* The visible surface is the inner control, so it inherits the root'sradius — that is the corner an attached `Group` adjusts. */}- <NumberInput.Input aria-label={t('topbar.iterations.label')} paddingStart="2" rounded="inherit" />+ <NumberInput.Input+ aria-describedby={isFixed ? fixedReasonId : undefined}+ aria-disabled={isFixed || undefined}+ aria-label={t('topbar.iterations.label')}+ paddingStart="2"+ rounded="inherit"+ />+ {isFixed ? <VisuallyHidden id={fixedReasonId}>{t('topbar.iterations.fixedModelOnly')}</VisuallyHidden> : null}</NumberInput.Root></Tooltip>);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex 15f743ee10..67bc74097f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -12,6 +12,7 @@ import {sanitizeDynamicPromptsConfig,} from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { isUpscaleBatchCountFixed } from '@features/upscale';import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';import { useExternalStoreSelector } from '@platform/state/selectors';@@ -84,7 +85,11 @@ const readEffectivePositivePrompt = (values: Record<string, unknown>): string =>return settings ? getEffectivePrompts(settings).positivePrompt : '';};-export const getBatchCount = (values: Record<string, unknown>): number => sanitizeBatchCount(values.batchCount);+export const isBatchCountFixed = (sourceId: InvocationRoute['sourceId'], values: Record<string, unknown>): boolean =>+ sourceId === 'upscale' && isUpscaleBatchCountFixed(values);++export const getBatchCount = (sourceId: InvocationRoute['sourceId'], values: Record<string, unknown>): number =>+ isBatchCountFixed(sourceId, values) ? 1 : sanitizeBatchCount(values.batchCount);export interface InvocationState {batchCount: number;@@ -175,6 +180,7 @@ export const useInvocationState = (): InvocationState => {destinationOverride,prepend,formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),+ formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),getModels: () => availabilityModels,queries,}),@@ -182,7 +188,7 @@ export const useInvocationState = (): InvocationState => {);return {- batchCount: getBatchCount(sourceValues),+ batchCount: getBatchCount(invocation.sourceId, sourceValues),blockingReasons,invocation,invoke,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsxindex f6e411e86e..fc5047aa9e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx@@ -183,10 +183,18 @@ const textOf = (role: 'alert' | 'status') =>[...host!.querySelectorAll(`[role="${role}"]`)].map((element) => element.textContent).join(' ');const retryButton = () => [...host!.querySelectorAll('button')].find((button) => button.textContent === 'common.retry');/** The model Select's hidden native options, as the kind ones are read. */-const offeredModels = () =>+const modelOptions = () =>[...host!.querySelectorAll('select')]- .flatMap((select) => [...select.options].map((option) => option.value))- .filter((value) => catalog.models.some((model) => model.key === value));+ .flatMap((select) => [...select.options])+ .filter((option) => catalog.models.some((model) => model.key === option.value));+const offeredModels = () =>+ modelOptions()+ .filter((option) => !option.disabled)+ .map((option) => option.value);+const reidentifyPendingModels = () =>+ modelOptions()+ .filter((option) => option.disabled)+ .map((option) => option.value);/** Renders `layers.at(-1)` as the selected layer of a document holding all of them, each with content. */const renderWith = async (@@ -384,6 +392,56 @@ describe('ControlLayerSettings on an Anima main model', () => {expect(textOf('alert')).toBe('');});+ it('lists adapters that need re-identifying as disabled entries after the usable ones', async () => {+ const models = [...ANIMA_MODELS, lllite('unidentified-2', 'Anima LLLite (older install)', null)];+ await renderWith(ANIMA_MAIN, models, animaLayer('anima_lllite', 'sketch'));++ expect(offeredModels()).toEqual(['sketch']);+ expect(reidentifyPendingModels()).toEqual(['unidentified', 'unidentified-2']);++ await act(() => page.getByRole('combobox', { name: 'widgets.layers.control.model' }).click());+ const options = [...document.querySelectorAll<HTMLElement>('[role="option"]')];+ // The suffix is text in the option's name, not only a muted color.+ expect(options.map((option) => option.textContent)).toEqual([+ 'Anima LLLite Sketch',+ 'Anima LLLite (old install) (widgets.layers.control.needsReidentify)',+ 'Anima LLLite (older install) (widgets.layers.control.needsReidentify)',+ ]);+ expect(options.map((option) => option.getAttribute('aria-disabled'))).toEqual([null, 'true', 'true']);++ // Neither a click nor Enter on a disabled entry chooses it.+ await act(() => options[1]!.click());+ await act(() => userEvent.keyboard('{ArrowDown}{ArrowDown}{Enter}'));+ await settle();+ expect(commits).toEqual([]);+ });++ it('turns an entry usable once the store holds its re-identified record', async () => {+ const layerWithoutModel = animaLayer('anima_lllite', null);+ await renderWith(ANIMA_MAIN, [ANIMA_MODELS[2]!], layerWithoutModel);+ expect(offeredModels()).toEqual([]);+ expect(reidentifyPendingModels()).toEqual(['unidentified']);++ // The models store replaced the record; the mocked selector reads the catalog on the next render.+ catalog.models = [{ ...ANIMA_MODELS[2]!, cond_in_channels: 3 }];+ await settle(() =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <ControlLayerSettings+ engine={engineWith([layerWithoutModel])}+ layer={layerWithoutModel}+ onOperationStarted={ignoreOperationStarted}+ />+ </ChakraProvider>+ </I18nextProvider>+ )+ );++ expect(reidentifyPendingModels()).toEqual([]);+ expect(offeredModels()).toEqual(['unidentified']);+ });+it('flags a second layer applying the same LLLite model, but not the first', async () => {const first = animaLayer('anima_lllite', 'sketch', 'first');const second = animaLayer('anima_lllite', 'sketch', 'second');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex dcd9f4b195..ce8e15db79 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -35,7 +35,11 @@ import { baselineConfig, useStructuralPreview } from '@workbench/widgets/canvas/import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { getCompatibleControlModels, switchControlAdapterKind } from './controlModelOptions';+import {+ getCompatibleControlModels,+ getReidentifyPendingControlModels,+ switchControlAdapterKind,+} from './controlModelOptions';import { LayerFilterOperationButton } from './LayerFilterOperationButton';import { CONTROL_WEIGHT_BOUNDS } from './layerOps';import { runLayerFilterOperation } from './layerPropertiesOperation';@@ -58,6 +62,13 @@ const formatWeight = (value: number): string => value.toFixed(2);/** Quiet warning tint for the model select while no control model is chosen. */const MISSING_MODEL_VALUE_TEXT_PROPS = { color: 'fg.warning' } as const;+interface ControlModelItem {+ /** Listed but not selectable: the model needs re-identifying before a control layer can use it. */+ disabled?: boolean;+ label: string;+ value: string;+}+interface ControlLayerSettingsProps {engine:| (CanvasStructuralEngine & LayerFilterOperationEngine & { readonly document: CanvasDocumentCapability })@@ -163,9 +174,34 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont.filter((reason) => reason === 'lllite_inpaint_adapter' || reason === 'lllite_channels_unknown');return [...new Set(reasons)].sort();}, [adapter.kind, base, modelOptions.length, models]);+ // Listed after the usable models, disabled, whatever the hints setting: the entry is the only place users see them.+ const reidentifyPendingModels = useMemo(+ () => (suggestedKind ? [] : getReidentifyPendingControlModels(models, base, adapter.kind)),+ [adapter.kind, base, models, suggestedKind]+ );const modelCollection = useMemo(- () => createListCollection({ items: modelOptions.map((model) => ({ label: model.name, value: model.key })) }),- [modelOptions]+ () =>+ createListCollection<ControlModelItem>({+ items: [+ ...modelOptions.map((model) => ({ label: model.name, value: model.key })),+ ...reidentifyPendingModels.map((model) => ({ disabled: true, label: model.name, value: model.key })),+ ],+ }),+ [modelOptions, reidentifyPendingModels]+ );+ const renderModelItem = useCallback(+ (item: ControlModelItem) =>+ item.disabled ? (+ <>+ {item.label}{' '}+ <Text as="span" color="fg.muted">+ ({t('widgets.layers.control.needsReidentify')})+ </Text>+ </>+ ) : (+ item.label+ ),+ [t]);const switchKind = useCallback(@@ -364,6 +400,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contaria-label={t('widgets.layers.control.model')}collection={modelCollection}positioning={SELECT_POSITIONING}+ renderItem={renderModelItem}value={modelValue}valueText={adapterModel?.name ?? t('widgets.layers.control.selectModel')}valueTextProps={adapter.model ? undefined : MISSING_MODEL_VALUE_TEXT_PROPS}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.tsindex 35425adaf0..08ad765c51 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.test.ts@@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest';import {getCompatibleControlModels,+ getReidentifyPendingControlModels,resolveDefaultControlModel,resolveDefaultControlModelForBase,switchControlAdapterKind,@@ -87,6 +88,26 @@ describe('getCompatibleControlModels — Anima ControlNet-LLLite', () => {it('defaults a new Anima control layer to an LLLite model', () => {expect(resolveDefaultControlModelForBase(models, 'anima')).toBe('sketch');});++ it('lists only Anima adapters of unknown type as needing re-identify, for the LLLite kind', () => {+ const others = [+ ...models,+ { ...model('sdxl-unknown', 'sdxl', 'controlnet'), cond_in_channels: null } as ModelConfig,+ { ...model('anima-lora', 'anima', 'lora'), cond_in_channels: null } as ModelConfig,+ ];++ expect(+ getReidentifyPendingControlModels(others, 'anima', 'anima_lllite').map((candidate) => candidate.key)+ ).toEqual(['unidentified']);+ expect(getReidentifyPendingControlModels(others, 'anima', 'controlnet')).toEqual([]);+ expect(getReidentifyPendingControlModels(others, 'sdxl', 'anima_lllite')).toEqual([]);+ });++ it('never defaults a layer to an adapter that needs re-identifying', () => {+ expect(+ resolveDefaultControlModelForBase([anima('unidentified', null), anima('inpainting', 4)], 'anima')+ ).toBeNull();+ });});describe('switchControlAdapterKind', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.tsindex 89c08c4195..b2acddc05a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/controlModelOptions.ts@@ -3,6 +3,7 @@ import type { CanvasControlAdapterContract } from '@workbench/canvas-engine/api'import {areControlAdapterValuesValid,+ getControlModelUnusableReason,isControlModelUsableForKind,type ControlAdapterKind,} from '@features/generation/graph';@@ -20,6 +21,23 @@ export const getCompatibleControlModels = (return models.filter((model) => isControlModelUsableForKind(model, kind) && (!base || model.base === base));};+/**+ * Anima ControlNet-LLLite models installed before `cond_in_channels` was recorded. The picker lists them disabled, so+ * users learn they exist and need re-identifying; they never count as usable models.+ */+export const getReidentifyPendingControlModels = (+ models: readonly ModelConfig[],+ base: string | null,+ kind: ControlAdapterKind+): ModelConfig[] => {+ if (kind !== 'anima_lllite' || base !== CONTROL_KIND_BASE[kind]) {+ return [];+ }+ return models.filter(+ (model) => model.base === base && getControlModelUnusableReason(model, kind) === 'lllite_channels_unknown'+ );+};+/*** The adapter after the user picks another kind. The model survives when the new kind can use it — so an Anima layer* saved as ControlNet with an LLLite model keeps it — and so do the weight and step range when they are valid fordiff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 4abf6dc11a..7014f1b0f3 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -251,6 +251,7 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): Geqwen3VLEncoderModel: null,qwen35EncoderModel: null,animaInpaintAdapterModel: null,+ animaInpaintAdapterEnabled: true,animaInpaintAdapterWeight: 1,wanT5EncoderModel: null,wanLowNoiseModel: null,@@ -644,6 +645,174 @@ describe('generation-device orchestration metadata', () => {});});+describe('model-only upscale submissions', () => {+ const upscaler = {+ ...createUpscaleModel('ultrasharp', 'spandrel_image_to_image', 'any', '4x-UltraSharp'),+ scale: 4,+ type: 'spandrel_image_to_image' as const,+ };+ const input = { height: 64, image_name: 'input.png', width: 48 };+ const sourceMetadata = { height: 512, positive_prompt: 'a lighthouse', seed: 42, width: 384 };+ const getQueued = (state: WorkbenchState) => {+ const snapshot = getActiveProject(state).queue.items[0]?.snapshot;+ const submission = snapshot?.backendSubmission;++ return { nodes: submission?.kind === 'invalid' ? {} : (submission?.graph.nodes ?? {}), snapshot, submission };+ };+ const primeModelOnly = () => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: {+ ...createDefaultUpscaleWidgetValues([upscaler]),+ // Iterations would repeat one image: Model only runs once.+ batchCount: 3,+ inputImage: input,+ mode: 'model-only',+ seed: 10,+ seedMode: 'increment',+ },+ widgetId: 'upscale',+ });++ // The shared prompt draft is not this run's: nothing reads a prompt.+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { positivePrompt: 'the Generate draft' },+ widgetId: 'generate',+ });++ return state;+ };+ const submitRoute = (state: WorkbenchState, imageName = input.image_name) =>+ workbenchReducer(state, {+ backendSupportsCancellation: true,+ models: [upscaler],+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },+ projectId: state.activeProjectId,+ type: 'submitResolvedInvocationSnapshot',+ upscaleSourceMetadata: { imageName, metadata: sourceMetadata },+ });++ it('queues the upscaler alone, once, with the input metadata, no main model, and leaves the Refine seed', () => {+ const state = submitRoute(primeModelOnly());+ const { nodes, snapshot, submission } = getQueued(state);++ expect(Object.values(nodes).map((node) => node.type)).toEqual([+ 'string',+ 'string',+ 'integer',+ 'spandrel_image_to_image_autoscale',+ ]);+ expect(nodes.upscale_output).toMatchObject({+ is_intermediate: false,+ metadata: { ...sourceMetadata, upscale_scale: 4 },+ scale: 4,+ });+ expect(submission).toMatchObject({+ batchCount: 1,+ kind: 'generate',+ negativePrompt: '',+ positivePrompt: '',+ seedStep: 0,+ });+ expect(snapshot?.presentation).toEqual({ batchCount: 1, height: 256, width: 192 });+ expect(getProjectWidgetValues(getActiveProject(state), 'upscale').seed).toBe(10);+ });++ it('queues nothing, and says why, with metadata read for an image that is no longer the input', () => {+ const state = submitRoute(primeModelOnly(), 'earlier.png');++ expect(getActiveProject(state).queue.items).toEqual([]);+ expect(state.notifications[0]).toMatchObject({ kind: 'error', titleKey: 'widgets.upscale.inputChanged' });+ });++ it("queues the image menu's upscale to the gallery without touching the widget or the route", () => {+ listGalleryBoardsInCache('auto-board');+ let state = workbenchReducer(primeModelOnly(), {+ settings: { autoAddBoardId: 'auto-board' },+ type: 'updateGallerySettings',+ });+ state = workbenchReducer(state, { destination: 'canvas', type: 'setInvocationDestination' });+ const before = getActiveProject(state);++ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ // Odd sizes: 4x gives 404 x 324, which the result floors to multiples of 8 as the Upscale widget's does.+ image: { height: 101, image_name: 'menu.png', width: 81 },+ projectId: state.activeProjectId,+ scale: 'native',+ sourceMetadata,+ type: 'submitModelOnlyUpscale',+ upscaleModel: upscaler,+ });++ const after = getActiveProject(state);+ const { nodes, snapshot, submission } = getQueued(state);++ expect(after.queue.items).toHaveLength(1);+ expect(snapshot).toMatchObject({ destination: 'gallery', galleryBoardId: 'auto-board', sourceId: 'upscale' });+ expect(snapshot?.presentation).toEqual({ batchCount: 1, height: 400, width: 320 });+ expect(submission).toMatchObject({ batchCount: 1, kind: 'generate', positivePrompt: '' });+ expect(nodes.upscale_output).toMatchObject({+ fit_to_multiple_of_8: true,+ image: { image_name: 'menu.png' },+ metadata: {+ ...sourceMetadata,+ upscale_initial_image: { height: 101, image_name: 'menu.png', width: 81 },+ upscale_scale: 4,+ },+ scale: 4,+ type: 'spandrel_image_to_image_autoscale',+ });+ expect(after.invocation).toEqual({ ...before.invocation, lastSubmittedRunId: after.queue.items[0]?.id });+ expect(after.widgetInstances).toEqual(before.widgetInstances);+ expect(after.widgetGraphs).toEqual(before.widgetGraphs);+ });++ it("runs the image menu's native entry for an upscaler of unknown native scale once, as a plain pass", () => {+ const primed = primeModelOnly();+ const { scale: _scale, ...legacy } = upscaler;+ const state = workbenchReducer(primed, {+ backendSupportsCancellation: true,+ image: { height: 101, image_name: 'menu.png', width: 81 },+ projectId: primed.activeProjectId,+ scale: 'native',+ sourceMetadata: null,+ type: 'submitModelOnlyUpscale',+ upscaleModel: legacy,+ });+ const { nodes } = getQueued(state);++ expect(nodes.upscale_output).toMatchObject({ type: 'spandrel_image_to_image' });+ expect(nodes.upscale_output).not.toHaveProperty('scale');+ expect(nodes.upscale_output).not.toHaveProperty('fit_to_multiple_of_8');+ expect(nodes.upscale_output?.metadata).not.toHaveProperty('upscale_scale');+ });++ it("runs the image menu's other factors as Model only plans them and sizes the result to that factor", () => {+ const primed = primeModelOnly();+ const state = workbenchReducer(primed, {+ backendSupportsCancellation: true,+ image: { height: 100, image_name: 'menu.png', width: 80 },+ projectId: primed.activeProjectId,+ scale: 1.5,+ sourceMetadata: null,+ type: 'submitModelOnlyUpscale',+ upscaleModel: upscaler,+ });+ const { nodes, snapshot } = getQueued(state);++ // One 4x pass, then the node resizes to 1.5x, floored to a multiple of 8: 150 x 120 becomes 144 x 120.+ expect(snapshot?.presentation).toEqual({ batchCount: 1, height: 144, width: 120 });+ expect(nodes.upscale_output).toMatchObject({+ fit_to_multiple_of_8: true,+ metadata: { upscale_scale: 1.5 },+ scale: 1.5,+ type: 'spandrel_image_to_image_autoscale',+ });+ });+});+describe('workbench hydration invariants', () => {it('preserves saved status placements and does not re-enable a removed shortcuts widget on hydration', () => {const initial = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 134072012d..28024163ea 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1,4 +1,4 @@-import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { GenerateWidgetValues, ImageWithDims } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';import type { ProjectGraphState, ProjectWorkflowSource } from '@features/workflow/contracts';@@ -16,6 +16,7 @@ import type {InvocationRoute,InvocationSourceId,ResultDestination,+ UpscaleSourceMetadata,} from '@workbench/invocationContracts';import type {BuiltInLayoutPresetId,@@ -159,12 +160,18 @@ import { getGenerationDevicesSnapshot, resolveRandDeviceMetadata } from '@featurimport {clearDeletedUpscaleInput,cloneUpscaleWidgetValues,+ compileModelOnlyUpscaleGraph,compileUpscaleGraph,+ createDefaultUpscaleWidgetValues,+ getSpandrelNativeScale,getUpscaleOutputDimensions,getUpscaleValidationReasons,+ isUpscaleSourceMetadataCurrent,normalizeUpscaleWidgetValues,resolveUpscaleSeed,+ resolveUpscaleSubmissionValues,syncUpscaleWidgetValuesWithModels,+ type SpandrelModelConfig,type UpscaleWidgetValues,} from '@features/upscale';import {@@ -409,7 +416,24 @@ type WorkbenchReducerAction =projectId: string;/** The workflow the submission was prepared from; required for workflow routes. */workflowId?: string;+ /** Upscale in Model only mode: the input image's metadata, read before dispatch. */+ upscaleSourceMetadata?: UpscaleSourceMetadata;} & Partial<ExpandedPositivePrompts>)+ | {+ /** The image menu's one-click upscale: queued at once, leaving the Upscale widget and the route as they are. */+ type: 'submitModelOnlyUpscale';+ projectId: string;+ image: ImageWithDims;+ upscaleModel: SpandrelModelConfig;+ /**+ * `'native'` runs the upscaler once, which needs no recorded scale; any other of `getModelOnlyUpscaleFactors` runs+ * the passes Model only plans and resizes to it. A recorded native scale is sized like any other factor.+ */+ scale: number | 'native';+ /** The image's metadata, read before dispatch; null when it has none. */+ sourceMetadata: Record<string, unknown> | null;+ backendSupportsCancellation: boolean;+ }| {type: 'markQueueItemBackendSubmitted';projectId: string;@@ -2729,7 +2753,8 @@ const compileInvocationSnapshot = (route: InvocationRoute,models?: readonly ModelConfig[],workflowGenerators?: WorkflowGeneratorResolutions,- workflowDocument: ProjectGraphState = getActiveProjectGraph(project)+ workflowDocument: ProjectGraphState = getActiveProjectGraph(project),+ upscaleSourceMetadata?: UpscaleSourceMetadata): {graph: GraphContract;widgetStates: WidgetStateMap;@@ -2782,17 +2807,23 @@ const compileInvocationSnapshot = (}const syncedValues = models ? syncUpscaleWidgetValuesWithModels(values, models) : values;- const currentValues: UpscaleWidgetValues = {- ...syncedValues,- ...getPromptDraftFromValues(getProjectWidgetValues(project, 'generate')),- };+ const currentValues = resolveUpscaleSubmissionValues(syncedValues, {+ promptDraft: getPromptDraftFromValues(getProjectWidgetValues(project, 'generate')),+ sourceImageName: upscaleSourceMetadata?.imageName,+ });- if (getUpscaleValidationReasons(currentValues, models).length > 0) {+ if (!currentValues || getUpscaleValidationReasons(currentValues, models).length > 0) {return null;}const resolvedValues: UpscaleWidgetValues = { ...currentValues, seed: resolveUpscaleSeed(currentValues) };- const compiledGraph = compileUpscaleGraph(resolvedValues, route.destination, project.settings, randDevice).graph;+ const compiledGraph = compileUpscaleGraph(+ resolvedValues,+ route.destination,+ project.settings,+ randDevice,+ upscaleSourceMetadata?.metadata ?? null+ ).graph;widgetStates.upscale = {...widgetStates.upscale,@@ -3539,7 +3570,9 @@ const enqueueCompiledSnapshot = (},backendSupportsCancellation: boolean,canvasSnapshot?: CanvasStateContractV3,- prepend = false+ prepend = false,+ /** A one-off run from outside the route (the image menu's upscale): the invocation route and widget graphs stay. */+ keepInvocationRoute = false): Project => {const submittedAt = now();const queueItemId = createId('queue-item');@@ -3639,7 +3672,7 @@ const enqueueCompiledSnapshot = (route.sourceId === 'video' && videoSettings?.model ? getVideoDimensions(videoSettings.model, videoSettings) : null;const presentationDimensions =route.sourceId === 'upscale' && upscaleSettings?.inputImage- ? getUpscaleOutputDimensions(upscaleSettings.inputImage, upscaleSettings.scale, upscaleSettings.model)+ ? getUpscaleOutputDimensions(upscaleSettings.inputImage, upscaleSettings): videoPresentationDimensions? videoPresentationDimensions: {@@ -3759,20 +3792,77 @@ const enqueueCompiledSnapshot = (positivePrompt: videoSettings.positivePrompt,}): project.promptHistory,- invocation: {- ...project.invocation,- destination: route.destination,- lastSubmittedRunId: queueItemId,- sourceId: route.sourceId,- },+ invocation: keepInvocationRoute+ ? { ...project.invocation, lastSubmittedRunId: queueItemId }+ : {+ ...project.invocation,+ destination: route.destination,+ lastSubmittedRunId: queueItemId,+ sourceId: route.sourceId,+ },queue: { items: [queueItem, ...project.queue.items] },widgetGraphs:- route.sourceId === 'generate' || route.sourceId === 'upscale' || route.sourceId === 'video'+ !keepInvocationRoute &&+ (route.sourceId === 'generate' || route.sourceId === 'upscale' || route.sourceId === 'video')? { ...project.widgetGraphs, [route.sourceId]: cloneGraph(graph) }: project.widgetGraphs,};};+const hasUpscaleInputChanged = (project: Project, metadata: UpscaleSourceMetadata | undefined): boolean => {+ const values = normalizeUpscaleWidgetValues(getWidgetValues(project, 'upscale'));++ return values !== null && !isUpscaleSourceMetadataCurrent(values, metadata?.imageName);+};++/**+ * The image menu's one-click upscale: the upscaler alone, results to the gallery, run and sized as the Upscale widget's+ * Model only mode runs that factor. An upscaler of unknown native scale runs once at it, unsized. The queue reads+ * the submission from the Upscale values it is handed, so these describe this run alone; the project's own Upscale+ * values, route and locks stay as they are.+ */+const submitModelOnlyUpscale = (+ project: Project,+ {+ backendSupportsCancellation,+ image,+ scale,+ sourceMetadata,+ upscaleModel,+ }: Extract<WorkbenchReducerAction, { type: 'submitModelOnlyUpscale' }>+): Project => {+ const route: InvocationRoute = { ...project.invocation, destination: 'gallery', sourceId: 'upscale' };+ const compiled = compileModelOnlyUpscaleGraph({+ destination: route.destination,+ image,+ scale,+ sourceMetadata,+ upscaleModel,+ });+ const widgetStates = getWidgetStatesSnapshot(project.widgetInstances);+ const values: UpscaleWidgetValues = {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: image,+ mode: 'model-only',+ // Sizes the queue's placeholder; an unknown scale shows the input's size until the backend's item replaces it.+ scale: scale === 'native' ? (getSpandrelNativeScale(upscaleModel) ?? 1) : scale,+ seedMode: 'fixed',+ upscaleModel,+ };++ widgetStates.upscale = { ...getWidgetState(project, 'upscale'), graphId: compiled.graph.id, values: { ...values } };++ return enqueueCompiledSnapshot(+ project,+ route,+ { graph: compiled.graph, widgetStates },+ backendSupportsCancellation,+ undefined,+ false,+ true+ );+};+const submitInvocationSnapshot = (project: Project,backendSupportsCancellation: boolean,@@ -3781,13 +3871,21 @@ const submitInvocationSnapshot = (expansion: Partial<ExpandedPositivePrompts> = {},workflowGenerators?: WorkflowGeneratorResolutions,workflowDocument?: ProjectGraphState,- prepend = false+ prepend = false,+ upscaleSourceMetadata?: UpscaleSourceMetadata): Project => {if (!isInvocationRouteValid(route)) {return project;}- const compiledSnapshot = compileInvocationSnapshot(project, route, models, workflowGenerators, workflowDocument);+ const compiledSnapshot = compileInvocationSnapshot(+ project,+ route,+ models,+ workflowGenerators,+ workflowDocument,+ upscaleSourceMetadata+ );if (!compiledSnapshot) {return project;@@ -4920,6 +5018,24 @@ export const __workbenchReducerInternal = ();}+ // The input image changed while Model only read its metadata: say so rather than queue nothing in silence.+ if (+ target &&+ action.route.sourceId === 'upscale' &&+ hasUpscaleInputChanged(target, action.upscaleSourceMetadata)+ ) {+ return addNotification(+ state,+ createNotification({+ category: 'enqueue',+ kind: 'error',+ projectId: target.id,+ title: 'The input image changed while the upscale was being prepared, so nothing was queued. Invoke again.',+ titleKey: 'widgets.upscale.inputChanged',+ })+ );+ }+return withEnqueueNotification(state,updateProjectById(state, action.projectId, (project) =>@@ -4931,12 +5047,20 @@ export const __workbenchReducerInternal = ({ positivePrompts: action.positivePrompts, positivePromptsSampleSeed: action.positivePromptsSampleSeed },action.workflowGenerators,workflow?.document,- action.prepend === true+ action.prepend === true,+ action.upscaleSourceMetadata)),action.projectId);}+ case 'submitModelOnlyUpscale': {+ return withEnqueueNotification(+ state,+ updateProjectById(state, action.projectId, (project) => submitModelOnlyUpscale(project, action)),+ action.projectId+ );+ }case 'markQueueItemBackendSubmitted': {return updateProjectById(state, action.projectId, (project) => {const previousSelectedSlot = getSelectedCanvasStagingSlot(project);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 6b1b25c643..4ae2838361 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -293,6 +293,7 @@ const createCommands = (sourceId,})),submitCanvas: command('submitCanvasInvocationSnapshot'),+ submitModelOnlyUpscale: command('submitModelOnlyUpscale'),submitResolved: command('submitResolvedInvocationSnapshot'),toggleDestinationLock: command('toggleDestinationLock'),toggleRoutingLock: command('toggleRoutingLock'),diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex 90dbed3968..2ce2b5942b 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -1074,6 +1074,56 @@ def test_reidentify_keeps_a_backbone_only_the_install_source_names(assert edits_at_replace == [[installed.key]]+def test_reidentify_records_the_scale_of_an_upscaler_installed_before_it_was_recorded(+ monkeypatch: Any, mm2_record_store: Any, mm2_app_config: Any+) -> None:+ from types import SimpleNamespace++ from invokeai.app.api.routers.model_manager import _reidentify_model+ from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+ from tests.fixtures.spandrel_models import write_compact_upscaler++ path = mm2_app_config.models_path / "4x-compact.safetensors"+ write_compact_upscaler(path, 4)+ installed = ModelConfigFactory.from_model_on_disk(path, {}, allow_unknown=False).config+ assert installed is not None+ installed.scale = None+ mm2_record_store.add_model(installed)+ assert mm2_record_store.get_model(installed.key).scale is None++ # The recorded scale is part of the record, so the rewrite counts as load-affecting: in-flight loads+ # re-check, and a cached instance built from the scale-less record is dropped.+ edits: list[tuple[str, RecordEdit]] = []+ dropped: list[str] = []++ @contextlib.contextmanager+ def record_edit(key: str) -> Iterator[RecordEdit]:+ edit = RecordEdit()+ edits.append((key, edit))+ yield edit++ class Cache:+ def drop_model(self, key: str) -> int:+ dropped.append(key)+ return 1++ services = SimpleNamespace(+ logger=logging.getLogger(__name__),+ model_manager=SimpleNamespace(+ store=mm2_record_store, load=SimpleNamespace(record_edit=record_edit, ram_caches={"cpu": Cache()})+ ),+ configuration=mm2_app_config,+ )+ monkeypatch.setattr(+ "invokeai.app.api.routers.model_manager.ApiDependencies", MockApiDependencies(DummyInvoker(services))+ )++ assert _reidentify_model(installed.key).scale == 4+ assert mm2_record_store.get_model(installed.key).scale == 4+ assert [(key, edit.load_affecting) for key, edit in edits] == [(installed.key, True)]+ assert dropped == [installed.key]++@pytest.mark.anyioasync def test_update_model_record_is_refused_while_the_same_model_is_being_converted(conversion_in_flight,diff --git a/tests/backend/model_manager/configs/test_spandrel_config.py b/tests/backend/model_manager/configs/test_spandrel_config.pynew file mode 100644index 0000000000..79a11f3b25--- /dev/null+++ b/tests/backend/model_manager/configs/test_spandrel_config.py@@ -0,0 +1,62 @@+"""Spandrel upscaler configs record the model's native scale from the model the probe already loads.++The fixtures are tiny real Compact (Real-ESRGAN SRVGG) models, so identification runs through the whole config factory+and Spandrel's own architecture detection, as an install or a re-identify does.+"""++from pathlib import Path+from typing import Any++import pytest+import torch+from pydantic import TypeAdapter+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory+from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError+from invokeai.backend.model_manager.configs.spandrel import Spandrel_Checkpoint_Config+from invokeai.backend.model_manager.model_on_disk import ModelOnDisk+from tests.fixtures.spandrel_models import write_compact_upscaler++_OVERRIDE_FIELDS: dict[str, object] = {+ "hash": "blake3:fakehash",+ "path": "/fake/models/upscaler.safetensors",+ "file_size": 1000,+ "name": "upscaler",+ "description": "test",+ "source": "test",+ "source_type": "path",+ "key": "test-key",+}+++def _identify(path: Path, overrides: dict[str, Any] | None = None) -> Any:+ return ModelConfigFactory.from_model_on_disk(path, {**_OVERRIDE_FIELDS, **(overrides or {})}, allow_unknown=False)++[email protected]("scale", [1, 2, 4])+def test_identification_records_the_upscalers_native_scale(tmp_path: Path, scale: int) -> None:+ path = write_compact_upscaler(tmp_path / f"{scale}x.safetensors", scale)++ result = _identify(path)++ assert type(result.config) is Spandrel_Checkpoint_Config+ assert result.config.scale == scale+++def test_a_record_stored_before_scale_was_recorded_reads_back_with_no_scale(tmp_path: Path) -> None:+ stored = _identify(write_compact_upscaler(tmp_path / "4x.safetensors", 4)).config.model_dump(mode="json")+ del stored["scale"]++ restored = TypeAdapter(AnyModelConfig).validate_python(stored)++ assert type(restored) is Spandrel_Checkpoint_Config+ assert restored.scale is None+++def test_a_file_spandrel_cannot_load_is_not_an_upscaler(tmp_path: Path) -> None:+ path = tmp_path / "not-an-upscaler.safetensors"+ save_file({"some.weight": torch.zeros(8, 3, 3, 3)}, path)++ with pytest.raises(NotAMatchError):+ Spandrel_Checkpoint_Config.from_model_on_disk(ModelOnDisk(path), dict(_OVERRIDE_FIELDS))diff --git a/tests/fixtures/spandrel_models.py b/tests/fixtures/spandrel_models.pynew file mode 100644index 0000000000..732d3e1639--- /dev/null+++ b/tests/fixtures/spandrel_models.py@@ -0,0 +1,13 @@+"""Tiny real Spandrel upscalers, for tests that identify or re-identify one from disk."""++from pathlib import Path++from safetensors.torch import save_file+from spandrel.architectures.Compact import Compact+++def write_compact_upscaler(path: Path, scale: int) -> Path:+ """Save a minimal Compact (Real-ESRGAN SRVGG) model with the given native scale to `path`."""+ model = Compact(num_in_ch=3, num_out_ch=3, num_feat=8, num_conv=2, upscale=scale)+ save_file(model.state_dict(), path)+ return path