Skip to content

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.

fix(ui): preserve concept edits and recover missing encoders

Josh Corbette2a48b583a01
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 687f7e515e..09a788366d 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -96,6 +96,8 @@ The frame is not a mask: everything inside it can change in image-to-image. To r
The frame is the final footprint of the generation on the canvas. With **Scale before processing** (in the Generate panel's canvas sections) set to **Auto** or **Manual**, InvokeAI generates at a different resolution, such as the model's optimal size, and then resizes the result to fit the frame. Choose a frame large enough to include the context the model needs, while keeping it within a size the model and your GPU memory handle well.
+**Auto** is the default, including for older projects that never saved a scale method. Those projects previously used **None**. Processing at a different resolution can change the result for the same seed, generation time, and GPU memory use. To generate at the frame's exact size, choose **None**; saved scale-method choices are preserved.
+
## Transforming layers
Choose **Transform** from a layer's menu, or press **Ctrl+T**, to scale and rotate the selected layer:
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index 30f3e8acc0..550eef80d7 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -3,7 +3,7 @@ import threading
import time
from collections import OrderedDict
from datetime import date
-from typing import AbstractSet, Literal, Optional
+from typing import AbstractSet, Any, Callable, Literal, Optional, TypeVar
import numpy as np
from fastapi import File, HTTPException, Query, UploadFile, status
@@ -24,7 +24,11 @@ from invokeai.app.services.image_index.cluster_labels import (
MAX_CUSTOM_VOCAB_TERMS,
normalize_custom_vocab_terms,
)
-from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError, VocabBuildState
+from invokeai.app.services.image_index.image_index_base import (
+ ImageIndexServiceBase,
+ TextSearchUnavailableError,
+ VocabBuildState,
+)
from invokeai.app.services.image_index.image_index_common import (
ImageIndexStatus,
IndexedItem,
@@ -66,6 +70,9 @@ class ImageMapPointsResponse(BaseModel):
description="disabled: indexing is off; model_missing: indexing is enabled but the configured embedding "
"model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"
)
+ model_id: Optional[str] = Field(
+ default=None, description="Active encoder fingerprint; clients must discard cached labels when it changes"
+ )
model_name: Optional[str] = Field(
default=None,
description="The configured embedding model's name; only set when state is model_missing, so the client "
@@ -101,6 +108,9 @@ class ImageMapStatusResponse(BaseModel):
"""Combined index + projection status for the current user."""
enabled: bool = Field(description="Whether the embedding index is running")
+ model_id: Optional[str] = Field(
+ default=None, description="Active encoder fingerprint; clients must discard cached labels when it changes"
+ )
model_name: Optional[str] = Field(
default=None,
description="The configured embedding model's name; only set when the projection state is model_missing",
@@ -270,19 +280,24 @@ def _log_cluster_diagnostics(services, user_id: str, diagnostics: ClusterDiagnos
def _active_model_id(services) -> Optional[str]:
- """The running indexer's model id, activating it if the encoder was installed since startup.
-
- The encoder is often installed *after* the server came up — the image map's
- own message links the starter install — and `start()` resolved the model
- only once. Retrying here (throttled by the service) means opening or
- refreshing the map picks the model up, rather than reporting
- `model_missing` until the next restart.
- """
- model_id = services.image_index.model_id
- if model_id is None and services.configuration.image_index_enabled:
+ """Reconcile encoder deletion/reinstallation through the service's throttled lifecycle."""
+ if services.configuration.image_index_enabled:
services.image_index.try_activate()
- model_id = services.image_index.model_id
- return model_id
+ return services.image_index.model_id
+
+
+_T = TypeVar("_T")
+
+
+def _with_model(indexer: ImageIndexServiceBase, model_id: str, operation: Callable[..., _T], *args: Any) -> _T:
+ """Fence each executor step against the model that supplied its inputs."""
+ with indexer.use_model():
+ if indexer.model_id != model_id:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="The embedding model changed during this request; try again",
+ )
+ return operation(*args)
# Videos are indexed whether or not a client can render them, so serving them is opt-in: a
@@ -411,13 +426,13 @@ async def get_image_map_points(
if record is None:
if not current_items:
- return ImageMapPointsResponse(points=[], state="empty", stale=False, point_count=0)
+ return ImageMapPointsResponse(points=[], state="empty", model_id=model_id, stale=False, point_count=0)
enqueued = services.image_index.request_projection(user_id, all_images=is_admin)
# stale means "a recompute is pending"; when nothing could be enqueued
# (the indexer is not running) nothing is pending, and a client that
# polls on stale would wait forever.
return ImageMapPointsResponse(
- points=[], state="computing" if enqueued else "empty", stale=enqueued, point_count=0
+ points=[], state="computing" if enqueued else "empty", model_id=model_id, stale=enqueued, point_count=0
)
current_hash = scope_hash(model_id, current_items)
@@ -537,6 +552,7 @@ async def get_image_map_points(
return ImageMapPointsResponse(
points=points,
state=state,
+ model_id=model_id,
stale=stale,
point_count=len(points),
cluster_eps=resolved_eps,
@@ -603,7 +619,9 @@ async def search_image_map(
if q is not None:
try:
- query_embedding = await asyncio.to_thread(services.image_index.embed_text, q)
+ query_embedding = await asyncio.to_thread(
+ _with_model, services.image_index, model_id, services.image_index.embed_text, q
+ )
except TextSearchUnavailableError as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
else:
@@ -633,7 +651,7 @@ async def search_image_map(
return services.image_index.embed_image(pil)
try:
- query_embedding = await asyncio.to_thread(embed_from_file)
+ query_embedding = await asyncio.to_thread(_with_model, services.image_index, model_id, embed_from_file)
except HTTPException:
raise
except (ImageFileNotFoundException, ImageRecordNotFoundException, VideoRecordNotFoundException, OSError):
@@ -660,6 +678,9 @@ async def search_image_map(
)
results = await asyncio.to_thread(
+ _with_model,
+ services.image_index,
+ model_id,
services.image_index.search_similar,
scope_user,
query_embedding,
@@ -851,7 +872,7 @@ async def search_image_map_by_image(
return services.image_index.embed_image(pil)
try:
- query_embedding = await asyncio.to_thread(embed_bytes)
+ query_embedding = await asyncio.to_thread(_with_model, services.image_index, model_id, embed_bytes)
except HTTPException:
raise
except Exception:
@@ -862,6 +883,9 @@ async def search_image_map_by_image(
)
results = await asyncio.to_thread(
+ _with_model,
+ services.image_index,
+ model_id,
services.image_index.search_similar,
scope_user,
query_embedding,
@@ -931,7 +955,9 @@ async def get_image_map_cluster_labels(
return ImageMapClusterLabelsResponse(labels={})
try:
- vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)
+ vocabulary, vocab_embeddings = await asyncio.to_thread(
+ _with_model, services.image_index, model_id, services.image_index.get_vocab_embeddings
+ )
except TextSearchUnavailableError as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
@@ -1000,7 +1026,7 @@ async def get_image_map_cluster_labels(
aligned = np.fromiter((cluster_by_item[item] for item in found_items), dtype=np.int64, count=len(found_items))
return label_clusters(aligned, embeddings, vocabulary, vocab_embeddings, top_k=top_k), visible_hash
- labels, visible_hash = await asyncio.to_thread(build)
+ labels, visible_hash = await asyncio.to_thread(_with_model, services.image_index, model_id, build)
return ImageMapClusterLabelsResponse(
labels={
str(cluster_id): ImageMapClusterLabel(
@@ -1049,7 +1075,9 @@ async def get_image_map_image_labels(
assert_image_read_access(item.name, current_user)
try:
- vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)
+ vocabulary, vocab_embeddings = await asyncio.to_thread(
+ _with_model, services.image_index, model_id, services.image_index.get_vocab_embeddings
+ )
except TextSearchUnavailableError as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
if not vocabulary:
@@ -1249,4 +1277,4 @@ def get_image_map_status(
)
# Index counts aggregate over all users' images; expose them to admins only.
index = services.image_index.get_status() if is_admin else None
- return ImageMapStatusResponse(enabled=True, index=index, projection=projection)
+ return ImageMapStatusResponse(enabled=True, model_id=model_id, index=index, projection=projection)
diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.py
index d003cf5314..a363c42c70 100644
--- a/invokeai/app/services/image_index/image_index_base.py
+++ b/invokeai/app/services/image_index/image_index_base.py
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
-from typing import AbstractSet, Literal, Optional
+from contextlib import contextmanager
+from typing import AbstractSet, Iterator, Literal, Optional
import numpy as np
from PIL import Image
@@ -38,17 +39,27 @@ class ImageIndexServiceBase(ABC):
pass
def try_activate(self) -> bool:
- """Start indexing if the configured embedding model has since been installed.
+ """Reconcile whether the configured embedding model is still installed.
Concrete when the base's other methods are abstract because the answer
for an inert implementation is simply "whatever it already was": only
the real service can pick a model up mid-run. Callers use this on
- request paths that would otherwise report `model_missing` for the rest
- of the process. Returns True if the indexer is running on return; may
- touch the model store, so call it off the event loop.
+ request paths to detect deletion and installation during a server
+ session. Returns True if the indexer is running on return; may touch
+ the model store, so call it off the event loop.
"""
return self.model_id is not None
+ @contextmanager
+ def use_model(self) -> Iterator[None]:
+ """Keep one model's resources stable for a synchronous operation.
+
+ Call off the event loop. Live implementations defer replacement until
+ callers leave; retirement may still make model_id unavailable. A
+ multi-step caller checks its captured model_id inside each use.
+ """
+ yield
+
@abstractmethod
def get_status(self) -> ImageIndexStatus | None:
"""Get index progress counts, or None if the indexer is not running."""
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index d5ec9cea90..b3c57f8056 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -1,9 +1,10 @@
import os
import threading
import time
+from contextlib import contextmanager
from pathlib import Path
from queue import Empty, Queue
-from typing import TYPE_CHECKING, AbstractSet, Any, Callable, Optional
+from typing import TYPE_CHECKING, AbstractSet, Any, Callable, Iterator, Optional
import numpy as np
import torch
@@ -211,7 +212,7 @@ def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:
logger.warning("Attention warm-up failed", exc_info=True)
-# Minimum gap between re-resolutions of a missing embedding model. The map's
+# Minimum gap between re-resolutions of the configured embedding model. The map's
# status endpoint is polled, and each attempt is a model-store query, so the
# retry is throttled rather than run per request.
_ACTIVATION_RETRY_INTERVAL_S = 5.0
@@ -284,6 +285,11 @@ class ImageIndexService(ImageIndexServiceBase):
# it registers image callbacks and starts the worker, and two concurrent
# map requests must not do either twice.
self._activation_lock = threading.Lock()
+ # Request threads may still be using an encoder after it is removed.
+ # Retirement publishes unavailability immediately; replacement waits
+ # for these users and the worker without blocking a polling request.
+ self._model_users = 0
+ self._callbacks_registered = False
self._last_activation_attempt: float = 0.0
# Set by stop() so a request that raced shutdown cannot start a worker
# the invoker will never join.
@@ -343,52 +349,67 @@ class ImageIndexService(ImageIndexServiceBase):
@property
def model_id(self) -> str | None:
- return self._model_id
+ return None if self._stop_event.is_set() else self._model_id
+
+ @contextmanager
+ def use_model(self) -> Iterator[None]:
+ with self._activation_lock:
+ self._model_users += 1
+ try:
+ yield
+ finally:
+ with self._activation_lock:
+ self._model_users -= 1
def get_status(self) -> ImageIndexStatus | None:
- if self._invoker is None or self._model_id is None:
+ model_id = self.model_id
+ if self._invoker is None or model_id is None:
return None
- status = self._invoker.services.image_index_records.count_index_status(self._model_id)
+ status = self._invoker.services.image_index_records.count_index_status(model_id)
return status.model_copy(update={"failed": len(self._failed)})
def embed_image(self, image: Image.Image) -> np.ndarray:
- if self._encode_fn is None:
- raise RuntimeError("The image index is not running")
- rgb = image.convert("RGB")
- try:
- matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)
- except Exception:
- # The model cache deletes an entry whose load failed precisely so
- # the next attempt rebuilds it from disk (e.g. an entry left in a
- # bad state by VRAM contention with a concurrent generation).
- # One retry is the cache's designed recovery; the worker gets the
- # same effect from its batch retry loop.
- if self._invoker is not None:
- self._invoker.services.logger.warning(
- "Image embed failed; retrying with a fresh model load", exc_info=True
- )
- matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)
- if matrix.ndim != 2 or matrix.shape[0] != 1:
- raise RuntimeError(f"Encoder returned shape {matrix.shape}; expected (1, D)")
- return _normalize_query_vector(matrix[0])
+ with self.use_model():
+ if self.model_id is None or self._encode_fn is None:
+ raise RuntimeError("The image index is not running")
+ rgb = image.convert("RGB")
+ try:
+ matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)
+ except Exception:
+ # The model cache deletes an entry whose load failed precisely so
+ # the next attempt rebuilds it from disk (e.g. an entry left in a
+ # bad state by VRAM contention with a concurrent generation).
+ # One retry is the cache's designed recovery; the worker gets the
+ # same effect from its batch retry loop.
+ if self._invoker is not None:
+ self._invoker.services.logger.warning(
+ "Image embed failed; retrying with a fresh model load", exc_info=True
+ )
+ matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)
+ if matrix.ndim != 2 or matrix.shape[0] != 1:
+ raise RuntimeError(f"Encoder returned shape {matrix.shape}; expected (1, D)")
+ return _normalize_query_vector(matrix[0])
def embed_text(self, text: str) -> np.ndarray:
return self._embed_texts([text])[0]
def _embed_texts(self, texts: list[str]) -> np.ndarray:
"""Batched text embedding, (N, D) L2-normalized."""
- if self._model_id is None:
- raise TextSearchUnavailableError("The image index is not running")
+ with self.use_model():
+ if self.model_id is None:
+ raise TextSearchUnavailableError("The image index is not running")
- tokenizer, model, is_siglip = self._get_text_encoder()
- with torch.no_grad():
- # SigLIP was trained with pad-to-max-length; pad-to-longest degrades
- # its text embeddings. CLIP uses ordinary longest-padding.
- inputs = tokenizer(texts, padding="max_length" if is_siglip else True, return_tensors="pt", truncation=True)
- outputs = model(**inputs)
- embeddings = outputs.pooler_output if is_siglip else outputs.text_embeds
- matrix = embeddings.float().cpu().numpy()
- return _normalize_batch(matrix)
+ tokenizer, model, is_siglip = self._get_text_encoder()
+ with torch.no_grad():
+ # SigLIP was trained with pad-to-max-length; pad-to-longest degrades
+ # its text embeddings. CLIP uses ordinary longest-padding.
+ inputs = tokenizer(
+ texts, padding="max_length" if is_siglip else True, return_tensors="pt", truncation=True
+ )
+ outputs = model(**inputs)
+ embeddings = outputs.pooler_output if is_siglip else outputs.text_embeds
+ matrix = embeddings.float().cpu().numpy()
+ return _normalize_batch(matrix)
def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:
"""The phrase-embedding matrix for cluster labelling.
@@ -401,7 +422,7 @@ class ImageIndexService(ImageIndexServiceBase):
worker instead and this raises until it lands.
"""
with self._vocab_lock:
- if self._vocab_cache is not None:
+ if self._vocab_cache is not None and self.model_id is not None:
return self._vocab_cache
if self._vocab_failure is not None:
# Aged past the retry window: drop the memo and fall through to
@@ -427,7 +448,7 @@ class ImageIndexService(ImageIndexServiceBase):
raise self._vocab_failure.with_traceback(None)
self._vocab_failure = None
self._vocab_failed_at = None
- if self._invoker is None or self._model_id is None:
+ if self._invoker is None or self.model_id is None:
raise TextSearchUnavailableError("The image index is not running")
self._vocab_build_requested.set()
@@ -448,7 +469,7 @@ class ImageIndexService(ImageIndexServiceBase):
self._vocab_build_requested.set()
def get_vocab_build_state(self) -> tuple[VocabBuildState, Optional[str]]:
- if self._invoker is None or self._model_id is None:
+ if self._invoker is None or self.model_id is None:
return "unavailable", None
# Flags first: a pending invalidation means the current cache (or
# failure) is about to be discarded, so reporting it would be a lie.
@@ -660,36 +681,37 @@ class ImageIndexService(ImageIndexServiceBase):
return self._text_encoder
def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[IndexedItem], np.ndarray]:
- if self._invoker is None or self._model_id is None:
- return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)
- records = self._invoker.services.image_index_records
-
- items = records.list_accessible_embedded_items(user_id, self._model_id)
- if not items:
- return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)
-
- # Memory math: one entry is N x dim float32 (~300 MB at 100k x 768),
- # so the LRU holds two entries and evicts oldest-first rather than
- # clearing wholesale. Keys self-invalidate: any change to the
- # accessible set changes the scope hash.
- cache_key = scope_hash(self._model_id, items)
- with self._search_cache_lock:
- cached = self._search_cache.get(cache_key)
- if cached is not None:
- # LRU touch.
- del self._search_cache[cache_key]
- self._search_cache[cache_key] = cached
- if cached is None:
- # Built outside the lock: a concurrent miss for the same scope
- # transiently builds a duplicate, which beats serializing every
- # search behind a multi-second BLOB read.
- cached = records.get_embeddings(items, self._model_id)
+ with self.use_model():
+ if self._invoker is None or self.model_id is None:
+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)
+ records = self._invoker.services.image_index_records
+
+ items = records.list_accessible_embedded_items(user_id, self._model_id)
+ if not items:
+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)
+
+ # Memory math: one entry is N x dim float32 (~300 MB at 100k x 768),
+ # so the LRU holds two entries and evicts oldest-first rather than
+ # clearing wholesale. Keys self-invalidate: any change to the
+ # accessible set changes the scope hash.
+ cache_key = scope_hash(self._model_id, items)
with self._search_cache_lock:
- while len(self._search_cache) >= 2:
- self._search_cache.pop(next(iter(self._search_cache)))
- self._search_cache[cache_key] = cached
-
- return cached
+ cached = self._search_cache.get(cache_key)
+ if cached is not None:
+ # LRU touch.
+ del self._search_cache[cache_key]
+ self._search_cache[cache_key] = cached
+ if cached is None:
+ # Built outside the lock: a concurrent miss for the same scope
+ # transiently builds a duplicate, which beats serializing every
+ # search behind a multi-second BLOB read.
+ cached = records.get_embeddings(items, self._model_id)
+ with self._search_cache_lock:
+ while len(self._search_cache) >= 2:
+ self._search_cache.pop(next(iter(self._search_cache)))
+ self._search_cache[cache_key] = cached
+
+ return cached
def search_similar(
self,
@@ -731,7 +753,7 @@ class ImageIndexService(ImageIndexServiceBase):
failed_scope: Optional[str] = None,
user_initiated: bool = False,
) -> bool:
- if self._model_id is None or self._worker is None or not self._worker.is_alive():
+ if self.model_id is None or self._worker is None or not self._worker.is_alive():
return False
if failed_scope is not None and not self._failed_scope_retry_available(user_id, failed_scope):
# The caller is asking on behalf of a cached failure whose one retry
@@ -819,46 +841,59 @@ class ImageIndexService(ImageIndexServiceBase):
self._launch_worker(invoker)
def try_activate(self) -> bool:
- """Resolve the configured encoder again and start indexing if it is now installed.
-
- `start()` resolves the model once, at server start, and leaves the
- service inert when it is missing — so a model installed afterwards (the
- image map's own message offers that install) would not be indexed until
- the next restart. The image map endpoints call this, so opening the
- panel is enough to pick the model up. Throttled, because those
- endpoints are polled.
+ """Reconcile encoder installation, draining retired work before replacement.
+
+ Called off the event loop by map reads and by the worker. Rechecks
+ are throttled in both the running and missing states. No join or
+ encoder lock is taken here: a deleted model becomes unavailable at
+ once, while its in-flight users keep their stable resources until a
+ later poll can safely replace them.
"""
- # Fast path, unlocked: the overwhelmingly common case is a running
- # indexer, and every map request would otherwise queue on the lock.
- if self._model_id is not None:
- return True
invoker = self._invoker
if invoker is None or not invoker.services.configuration.image_index_enabled:
return False
with self._activation_lock:
- if self._model_id is not None:
- return True
- if self._stopped or (self._worker is not None and self._worker.is_alive()):
+ if self._stopped:
return False
+ if self._encode_fn_override is not None:
+ return self.model_id is not None
now = time.monotonic()
if now - self._last_activation_attempt < _ACTIVATION_RETRY_INTERVAL_S:
- return False
+ return self.model_id is not None
self._last_activation_attempt = now
config = invoker.services.configuration
try:
model_config = self._resolve_model_config(config.image_index_model)
except Exception:
- # Unlike start(), this runs on a request thread: a model-store
- # failure must degrade the map to `model_missing`, which is
- # what these endpoints reported before they resolved anything,
- # rather than turning three read endpoints into 500s.
+ # Request-driven reconciliation must not turn reads into 500s.
invoker.services.logger.warning("Image index: could not resolve the embedding model", exc_info=True)
+ # A failed catalog read is not evidence that a running model
+ # was deleted. Keep its current availability and retry later.
+ return self.model_id is not None
+ if model_config is not None and self._model_config is not None and self.model_id is not None:
+ # Catalog metadata does not change loaded resources. Include
+ # cache identity, loader selection, and placement/sizing config
+ # for CLIP/SigLIP, but leave name/description/cover edits alone.
+ resource_fields = {"key", "hash", "base", "type", "format", "repo_variant", "cpu_only"}
+ if (
+ model_config.model_dump(include=resource_fields)
+ == self._model_config.model_dump(include=resource_fields)
+ # The shared loader normalizes config.path in place.
+ and (config.models_path / model_config.path).resolve()
+ == (config.models_path / self._model_config.path).resolve()
+ ):
+ return True
+ self._stop_event.set()
+ if self._model_users or (self._worker is not None and self._worker.is_alive()):
return False
+
+ self._reset_model_resources()
+ self._model_config = None
+ self._encode_fn = None
+ self._model_id = None
if model_config is None:
- # Silent: start() already logged the diagnosis once, and this
- # runs on a polled endpoint.
return False
invoker.services.logger.info(
@@ -875,6 +910,7 @@ class ImageIndexService(ImageIndexServiceBase):
try:
self._launch_worker(invoker)
except Exception:
+ self._stop_event.set()
self._model_config = None
self._encode_fn = None
self._model_id = None
@@ -886,16 +922,45 @@ class ImageIndexService(ImageIndexServiceBase):
return False
return True
+ def _reset_model_resources(self) -> None:
+ """Retire caches only after the worker and request users have drained.
+
+ Called under _activation_lock. Same-hash reinstalls must also discard
+ lazy encoders and load failures: their path or installation may have
+ changed even though stored image embeddings remain valid.
+ """
+ self._processor = None
+ self._cpu_model = None
+ self._text_encoder = None
+ self._text_encoder_failure = None
+ with self._vocab_lock:
+ self._vocab_cache = None
+ self._vocab_failure = None
+ self._vocab_failed_at = None
+ self._vocab_build_requested.clear()
+ self._vocab_invalidate_requested.clear()
+ with self._search_cache_lock:
+ self._search_cache.clear()
+ with self._projection_lock:
+ self._projection_requests.clear()
+ self._failed_projection_scopes.clear()
+ self._attempts.clear()
+ self._failed.clear()
+ self._pending_pokes.clear()
+ self._systemic_failures = 0
+
def _launch_worker(self, invoker: "Invoker") -> None:
- """Wire the image callbacks and start the worker thread. Runs once per active model."""
+ """Start one worker, keeping callback registration scoped to the service."""
discarded = invoker.services.image_index_records.delete_embeddings_for_other_models(self._model_id)
if discarded:
invoker.services.logger.info(f"Discarded {discarded} embeddings computed by a previously-configured model")
- invoker.services.images.on_changed(self._on_image_changed)
- invoker.services.images.on_deleted(self._on_image_deleted)
- invoker.services.videos.on_changed(self._on_video_changed)
- invoker.services.videos.on_deleted(self._on_video_deleted)
+ if not self._callbacks_registered:
+ invoker.services.images.on_changed(self._on_image_changed)
+ invoker.services.images.on_deleted(self._on_image_deleted)
+ invoker.services.videos.on_changed(self._on_video_changed)
+ invoker.services.videos.on_deleted(self._on_video_deleted)
+ self._callbacks_registered = True
self._backfill_pending.set()
# A previous run stopped mid-pass leaves this set; this run's pass announces itself.
@@ -953,6 +1018,10 @@ class ImageIndexService(ImageIndexServiceBase):
self._attempts.pop(item, None)
self._status_dirty.set()
return
+ if self._stop_event.is_set():
+ # Reinstallation backfills from the records. Retaining callbacks'
+ # items while no worker can consume them would grow without bound.
+ return
with self._pending_lock:
if item in self._pending:
return
@@ -984,6 +1053,8 @@ class ImageIndexService(ImageIndexServiceBase):
logger = self._invoker.services.logger
while not self._stop_event.is_set():
try:
+ if not self.try_activate():
+ break
batch = self._next_batch()
if self._status_dirty.is_set():
# The worker is the only emitter, so events are totally
@@ -1009,8 +1080,11 @@ class ImageIndexService(ImageIndexServiceBase):
# symptom it was added to fix.
self._wait_for_idle_generation()
if self._stop_event.is_set():
+ self._forget_pending(batch)
break
ok = self._process_batch(batch)
+ if self._stop_event.is_set():
+ break
self._emit_status()
if ok:
continue
@@ -1221,6 +1295,8 @@ class ImageIndexService(ImageIndexServiceBase):
try:
embeddings = np.asarray(self._encode_fn(images), dtype=EMBEDDING_DTYPE)
except Exception:
+ if self._stop_event.is_set():
+ return False
logger.exception(f"Image index: failed to embed a batch of {len(loaded)} items")
self._attribute_batch_failure("the encoder raised", loaded)
return False
@@ -1257,17 +1333,20 @@ class ImageIndexService(ImageIndexServiceBase):
stored: list[IndexedItem] = []
try:
- for item, embedding in zip(loaded, embeddings, strict=True):
- # Deliberately not caught per-item: any exception from here must reach the
- # handler below, which fails every unstored item and returns False to re-arm
- # the backfill. Swallowing one item's error here would leave it unembedded
- # with no retry ever scheduled, wedging `pending` above zero.
- self._invoker.services.image_index_records.upsert_embedding(item, self._model_id, embedding)
- stored.append(item)
- self._attempts.pop(item, None)
- # An item that recovers (e.g. re-embedded after an
- # update) must stop counting against the failed total.
- self._failed.discard(item)
+ with self._activation_lock:
+ if self._stop_event.is_set():
+ return False
+ for item, embedding in zip(loaded, embeddings, strict=True):
+ # Deliberately not caught per-item: any exception from here must reach the
+ # handler below, which fails every unstored item and returns False to re-arm
+ # the backfill. Swallowing one item's error here would leave it unembedded
+ # with no retry ever scheduled, wedging `pending` above zero.
+ self._invoker.services.image_index_records.upsert_embedding(item, self._model_id, embedding)
+ stored.append(item)
+ self._attempts.pop(item, None)
+ # An item that recovers (e.g. re-embedded after an
+ # update) must stop counting against the failed total.
+ self._failed.discard(item)
except Exception:
# A raise here (e.g. "database is locked") is a property of the database, not of
# any item, so it is systemic: the unstored items stay pending and are retried
@@ -1504,14 +1583,17 @@ class ImageIndexService(ImageIndexServiceBase):
# empty cache still claims the current scope, so staleness detection —
# not client polling — decides when to retry).
try:
- records.set_projection(
- user_id,
- self._model_id,
- current_hash,
- projection_params(n_points=len(found_items)),
- found_items,
- coords,
- )
+ with self._activation_lock:
+ if self._stop_event.is_set():
+ return
+ records.set_projection(
+ user_id,
+ self._model_id,
+ current_hash,
+ projection_params(n_points=len(found_items)),
+ found_items,
+ coords,
+ )
except Exception:
# Same reasoning as the read above: the fit is done but unsaved, so
# re-queue rather than drop it and leave /refresh's promise unmet.
@@ -1670,7 +1752,7 @@ class ImageIndexService(ImageIndexServiceBase):
# changes the model hash, and `start()` then discards every embedding computed under
# the old one. Order by key instead: stable across reinstalls of the same set.
chosen = min(configs, key=lambda config: config.key)
- if len(configs) > 1:
+ if len(configs) > 1 and (self._model_config is None or chosen.key != self._model_config.key):
self._invoker.services.logger.warning(
f"Multiple {model_type.value} models named '{model_name}' are installed; "
f"using '{chosen.key}' for the image index"
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 6a3c8162b4..b62a1cb2d0 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -47344,6 +47344,18 @@
"title": "State",
"description": "disabled: indexing is off; model_missing: indexing is enabled but the configured embedding model is not installed; empty: nothing to show; computing: a projection is being built; ready: points are served"
},
+ "model_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model Id",
+ "description": "Active encoder fingerprint; clients must discard cached labels when it changes"
+ },
"model_name": {
"anyOf": [
{
@@ -47527,6 +47539,18 @@
"title": "Enabled",
"description": "Whether the embedding index is running"
},
+ "model_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model Id",
+ "description": "Active encoder fingerprint; clients must discard cached labels when it changes"
+ },
"model_name": {
"anyOf": [
{
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index fddf71a271..a6e6ba18ec 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -19285,6 +19285,11 @@ export type components = {
* @enum {string}
*/
state: "disabled" | "model_missing" | "empty" | "computing" | "ready";
+ /**
+ * Model Id
+ * @description Active encoder fingerprint; clients must discard cached labels when it changes
+ */
+ model_id?: string | null;
/**
* Model Name
* @description The configured embedding model's name; only set when state is model_missing, so the client can tell the user which model to install
@@ -19418,6 +19423,11 @@ export type components = {
* @description Whether the embedding index is running
*/
enabled: boolean;
+ /**
+ * Model Id
+ * @description Active encoder fingerprint; clients must discard cached labels when it changes
+ */
+ model_id?: string | null;
/**
* Model Name
* @description The configured embedding model's name; only set when the projection state is model_missing
diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.md
index 0991b56f37..8372215dfd 100644
--- a/invokeai/frontend/webv2/AGENTS.md
+++ b/invokeai/frontend/webv2/AGENTS.md
@@ -20,6 +20,7 @@ Shared generated API contracts and their CI gates belong to [../api/AGENTS.md](.
- `@platform/react/useMountEffect` is only for mount/unmount registration with stable dependencies and complete cleanup. No changing-dependency refs, wrapper aliases, or layout-effect evasions; layout effects require pre-paint DOM measurement.
- Migrate effects when changing their behavior, without unrelated sweeps. Identity changes use store/runtime lifecycles or deliberate keyed remounts without accidental state loss.
- Reuse Platform controls, Chakra/theme tokens, icons, and interactions; no second styling system or generic Next.js/SWR patterns.
+- Typography uses the workbench scale: `xs` is 10px and `sm` is 11px. `architecture:check` (also in `lint`) rejects retired `2xs` literals in `fontSize`/`textStyle` JSX and style/recipe properties, including conditional and responsive values. Chakra permits arbitrary CSS strings, so typegen cannot enforce this. The syntax guard does not resolve variables or calls; `sm` remains valid, so review must catch uses that still intend its old 14px size (`lg`). Stock-name mapping data is allowed.
- Include disabled states; preserve keyboard operation, visible/restored focus, accessible names, and pointer alternatives.
- Icon-only controls carry the platform `Tooltip`, including menu and popover triggers (share `useTooltipTriggerIds` between the root and the Tooltip); never a native `title`.
- Keep dense layouts usable across window sizes/zoom. Check overflow, long/localized text, selected/hover/active states, and themes; follow localization conventions.
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 9c6a2311a9..1f3116e37a 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -7,7 +7,7 @@
"#architecture/source-analysis": "./src/architecture/tsSourceAnalysis.ts"
},
"scripts": {
- "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/architectureWorkflow.test.ts src/architecture/canvasSeamOwnership.test.ts src/architecture/tsSourceAnalysis.test.ts src/architecture/secureContextApis.test.ts src/architecture/axeAudits.test.ts && node --experimental-strip-types scripts/write-workbench-ownership-inventory.mjs && node --experimental-strip-types scripts/write-contract-caller-matrix.mjs && node --experimental-strip-types scripts/write-canvas-import-matrix.mjs",
+ "architecture:check": "vitest run --config vitest.config.mts src/architecture/dependencyPolicy.test.ts src/architecture/workbenchOwnership.test.ts src/architecture/architectureWorkflow.test.ts src/architecture/canvasSeamOwnership.test.ts src/architecture/tsSourceAnalysis.test.ts src/architecture/secureContextApis.test.ts src/architecture/axeAudits.test.ts src/architecture/typographyPolicy.test.ts && node --experimental-strip-types scripts/write-workbench-ownership-inventory.mjs && node --experimental-strip-types scripts/write-contract-caller-matrix.mjs && node --experimental-strip-types scripts/write-canvas-import-matrix.mjs",
"build": "pnpm run lint && vite build",
"check:architecture": "pnpm run lint && pnpm run test:all && pnpm run test:performance:architecture && pnpm run test:project-files:browser",
"check:release": "pnpm run check:architecture && pnpm run test:accessibility:browser",
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 12c13be55e..10cb7b155c 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -224,8 +224,8 @@ const surfaces = [
await waitForWorkbench(page);
await selectLayoutPreset(page, 'Compose', 'Preview');
await selectCenterView(page, 'Preview', 'Gallery');
- // The default project board is empty; scan the populated fixture gallery.
- await centerRegion(page).getByRole('button').filter({ hasText: 'Uncategorized' }).click();
+ // Choose the populated board row; the disclosure also names the currently selected board.
+ await centerRegion(page).locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
await centerRegion(page).getByRole('list', { exact: true, name: 'Gallery items' }).waitFor();
},
},
@@ -668,7 +668,7 @@ const runVideoPreviewJourney = async (browser) => {
await selectLayoutPreset(page, 'Compose', 'Preview');
const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });
- await rightPanel.getByRole('button').filter({ hasText: 'Uncategorized' }).click();
+ await rightPanel.locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
const gallery = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });
const selectVideo = rightPanel.getByRole('button', {
exact: true,
@@ -774,7 +774,7 @@ const runKeepAliveStateJourney = async (browser) => {
await selectLayoutPreset(page, 'Compose', 'Preview');
const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });
- await rightPanel.getByRole('button').filter({ hasText: 'Uncategorized' }).click();
+ await rightPanel.locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();
const galleryItems = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });
await galleryItems.waitFor();
diff --git a/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx b/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx
new file mode 100644
index 0000000000..94e2374581
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx
@@ -0,0 +1,228 @@
+import type { GenerateLora } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+import type { Project } from '@workbench/projectContracts';
+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { GenerationUiProvider, type GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';
+import { createDefaultUpscaleWidgetValues } from '@features/upscale';
+import { useUpscaleUi, type UpscaleUiAdapter } from '@features/upscale/ui/UpscaleUiContext';
+import { UpscaleWidgetView } from '@features/upscale/ui/UpscaleWidgetView';
+import { createDefaultVideoWidgetValues } from '@features/video';
+import { useVideoUi, type VideoUiAdapter } from '@features/video/ui/VideoUiContext';
+import { VideoWidgetView } from '@features/video/ui/VideoWidgetView';
+import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { act, useSyncExternalStore } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';
+import { VideoUiAdapterProvider } from './VideoUiAdapter';
+
+const model = (key: string, base: string, type: string, name = key): ModelConfig => ({
+ base,
+ file_size: 1,
+ format: 'diffusers',
+ hash: key,
+ key,
+ name,
+ path: key,
+ source: key,
+ source_type: 'path',
+ type,
+});
+const models = [
+ { ...model('video-main', 'minimax-h3', 'main'), variant: 'fl2va' },
+ model('video-first', 'minimax-h3', 'lora', 'MiniMax H3 Turbo LoRA'),
+ model('video-second', 'minimax-h3', 'lora', 'Video Ink Wash'),
+ model('upscale-main', 'sdxl', 'main'),
+ model('upscale-first', 'sdxl', 'lora', 'Upscale Ink Wash'),
+ model('upscale-second', 'sdxl', 'lora', 'Upscale Detail'),
+];
+const modelSnapshot = { models, status: 'loaded' };
+const { notify } = vi.hoisted(() => ({ notify: vi.fn() }));
+const noop = () => undefined;
+const generationAdapter = {
+ sectionPreferences: { sectionsOpen: {}, setSectionOpen: noop },
+} as unknown as GenerationUiAdapter;
+
+let store: WorkbenchInternalStore;
+let host: HTMLDivElement;
+let root: Root;
+const captureAdapters = vi.fn<(adapters: { upscale: UpscaleUiAdapter; video: VideoUiAdapter }) => void>();
+
+const CaptureAdapters = () => {
+ captureAdapters({ upscale: useUpscaleUi(), video: useVideoUi() });
+ return null;
+};
+
+vi.mock('react-i18next', () => {
+ const t = (key: string) => key;
+ return { useTranslation: () => ({ i18n: { resolvedLanguage: 'en' }, t }) };
+});
+vi.mock('@features/models', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ensureModelsLoaded: () => Promise.resolve(),
+ getModelImageUrl: () => '',
+ useModelsSelector: (selector: (snapshot: typeof modelSnapshot) => unknown) => selector(modelSnapshot),
+ useOpenModelInManager: () => undefined,
+}));
+// Picker transport and prompt suggestions are unrelated to concept commits; retain the real list, rows, and controls.
+vi.mock('@features/models/react', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ModelSelect: () => null,
+}));
+vi.mock('@features/gallery/mediaSlot', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ GalleryMediaSlot: () => null,
+}));
+vi.mock('@features/generation/components', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ NegativePromptField: () => null,
+ PositivePromptField: () => null,
+}));
+vi.mock('@platform/ui/toaster', () => ({ toaster: { create: notify } }));
+vi.mock('@workbench/settings/store', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useWorkbenchPreferenceSelector: () => false,
+}));
+vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => noop }));
+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) =>
+ selector(useSyncExternalStore(store.subscribe, store.getSnapshot).activeProject),
+ useWorkbenchCommands: () => store.commands,
+}));
+
+seedArchitectureCapabilities();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+type Widget = 'upscale' | 'video';
+
+const currentLoras = (widget: Widget): GenerateLora[] =>
+ getProjectWidgetValues(store.getSnapshot().activeProject, widget).loras as GenerateLora[];
+
+const render = async (widget: Widget) => {
+ const loras = models
+ .filter((candidate) => candidate.type === 'lora' && candidate.key.startsWith(widget))
+ .map((candidate, index) => ({ isEnabled: true, model: candidate, weight: index === 0 ? 0.75 : 0.5 }));
+ const defaults =
+ widget === 'video' ? createDefaultVideoWidgetValues(models) : createDefaultUpscaleWidgetValues(models);
+ store.commands.widgets.patchValues(widget, { ...defaults, loras, steps: 17 });
+ const queryClient = new QueryClient();
+ await act(() =>
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={generationAdapter}>
+ <VideoUiAdapterProvider>
+ <UpscaleUiAdapterProvider>
+ <CaptureAdapters />
+ {widget === 'video' ? <VideoWidgetView /> : <UpscaleWidgetView />}
+ </UpscaleUiAdapterProvider>
+ </VideoUiAdapterProvider>
+ </GenerationUiProvider>
+ </ChakraProvider>
+ </QueryClientProvider>
+ )
+ );
+ if (widget === 'upscale') {
+ await act(() => {
+ [...host.querySelectorAll<HTMLButtonElement>('button')]
+ .find((button) => button.textContent === 'widgets.upscale.generation')
+ ?.click();
+ });
+ }
+
+ const rows = [...host.querySelectorAll<HTMLElement>('[role="listitem"]')];
+ expect(rows).toHaveLength(2);
+ return rows;
+};
+
+const step = (row: HTMLElement) =>
+ row
+ .querySelector('[role="slider"]')
+ ?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' }));
+
+beforeEach(() => {
+ store = createWorkbenchStore();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ notify.mockClear();
+ captureAdapters.mockClear();
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('concept drafts through widget adapters', () => {
+ it.each(['upscale', 'video'] as const)(
+ 'flushes sibling %s drafts without losing same-turn settings changes',
+ async (widget) => {
+ const rows = await render(widget);
+ await act(() => rows.forEach(step));
+ expect(currentLoras(widget).map((lora) => lora.weight)).toEqual([0.75, 0.5]);
+
+ await act(() => {
+ store.commands.widgets.patchValues(widget, { steps: 23 });
+ flushWorkbenchDrafts();
+ });
+
+ expect(currentLoras(widget).map((lora) => lora.weight)).toEqual([0.8, 0.55]);
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, widget).steps).toBe(23);
+ }
+ );
+
+ it.each(['upscale', 'video'] as const)(
+ 'keeps stale %s callbacks fenced to their originating project',
+ async (widget) => {
+ await render(widget);
+ const patch = captureAdapters.mock.calls.at(-1)![0][widget].patchValues;
+ const projectId = store.getSnapshot().activeProject.id;
+ await act(() => store.commands.projects.create());
+ const nextProjectValues = getProjectWidgetValues(store.getSnapshot().activeProject, widget);
+
+ await act(() => patch((current: { steps: number }) => ({ steps: current.steps + 1 })));
+
+ const originalProject = store.getSnapshot().projects.find((project) => project.id === projectId)!;
+ expect(getProjectWidgetValues(originalProject, widget).steps).toBe(18);
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, widget)).toBe(nextProjectValues);
+ }
+ );
+
+ it.each(['upscale', 'video'] as const)(
+ 'does not restore a removed %s concept when another draft flushes',
+ async (widget) => {
+ const rows = await render(widget);
+ await act(() => step(rows[1]!));
+ await act(() => {
+ rows[0]!.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.removeConceptNamed"]')?.click();
+ flushWorkbenchDrafts();
+ });
+
+ expect(currentLoras(widget).map((lora) => ({ key: lora.model.key, weight: lora.weight }))).toEqual([
+ { key: `${widget}-second`, weight: 0.55 },
+ ]);
+ if (widget === 'video') {
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, widget)).toMatchObject({
+ acceleratorEnabled: false,
+ acceleratorLoraKeys: [],
+ steps: 50,
+ });
+ expect(notify).toHaveBeenCalledExactlyOnceWith({
+ description: 'widgets.video.acceleratorBrokenDescription',
+ title: 'widgets.video.acceleratorBroken',
+ type: 'info',
+ });
+ }
+ }
+ );
+});
diff --git a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
index c0ecb64292..793b0b142f 100644
--- a/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/UpscaleUiAdapter.tsx
@@ -2,7 +2,7 @@ import type { UpscaleUiAdapter } from '@features/upscale';
import type { ReactNode } from 'react';
import { areProjectPromptDraftsEqual, getPromptDraftFromValues } from '@features/generation/settings';
-import { UpscaleUiProvider } from '@features/upscale';
+import { createDefaultUpscaleWidgetValues, normalizeUpscaleWidgetValues, UpscaleUiProvider } from '@features/upscale';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
@@ -36,7 +36,15 @@ export const UpscaleUiAdapterProvider = ({ children }: { children: ReactNode })
[commands, projectId]
);
const patchValues = useCallback<UpscaleUiAdapter['patchValues']>(
- (values, origin) => commands.widgets.patchValues('upscale', values, projectId, origin),
+ (values, origin) =>
+ commands.widgets.patchValues(
+ 'upscale',
+ typeof values === 'function'
+ ? (current) => values(normalizeUpscaleWidgetValues(current) ?? createDefaultUpscaleWidgetValues())
+ : values,
+ projectId,
+ origin
+ ),
[commands, projectId]
);
const reportError = useCallback<UpscaleUiAdapter['reportError']>(
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
index c876190f72..5d94fa0e1c 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.browser.test.tsx
@@ -35,7 +35,8 @@ const revealGalleryItem = vi.fn(
/** The regions the project's single gallery instance occupies. */
let galleryRegions: string[] = ['right'];
-vi.mock('@features/video', () => ({
+vi.mock('@features/video', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
VideoUiProvider: ({ adapter: next, children }: { adapter: VideoUiAdapter; children: ReactNode }) => {
adapter = next;
return children;
diff --git a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
index 2a79609357..55be54c56e 100644
--- a/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/VideoUiAdapter.tsx
@@ -3,7 +3,7 @@ import type { ReactNode } from 'react';
import { getGalleryAutoAddBoardId, toGalleryItemKey } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
-import { VideoUiProvider } from '@features/video';
+import { createDefaultVideoWidgetValues, normalizeVideoWidgetValues, VideoUiProvider } from '@features/video';
import { useQueryClient } from '@tanstack/react-query';
import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
@@ -51,7 +51,15 @@ export const VideoUiAdapterProvider = ({ children }: { children: ReactNode }) =>
// Key actions by project, not values, to preserve callback identity while typing.
const { projectId } = project;
const patchValues = useCallback<VideoUiAdapter['patchValues']>(
- (values, origin) => commands.widgets.patchValues('video', values, projectId, origin),
+ (values, origin) =>
+ commands.widgets.patchValues(
+ 'video',
+ typeof values === 'function'
+ ? (current) => values(normalizeVideoWidgetValues(current) ?? createDefaultVideoWidgetValues())
+ : values,
+ projectId,
+ origin
+ ),
[commands, projectId]
);
const reportError = useCallback<VideoUiAdapter['reportError']>(
diff --git a/invokeai/frontend/webv2/src/architecture/tsSourceAnalysis.ts b/invokeai/frontend/webv2/src/architecture/tsSourceAnalysis.ts
index aa957d4bc9..171b136382 100644
--- a/invokeai/frontend/webv2/src/architecture/tsSourceAnalysis.ts
+++ b/invokeai/frontend/webv2/src/architecture/tsSourceAnalysis.ts
@@ -1,8 +1,13 @@
import type { Node, SourceFile, Statement } from 'typescript/unstable/ast';
import {
+ isArrayLiteralExpression,
+ isAsExpression,
+ isBinaryExpression,
isCallExpression,
isClassDeclaration,
+ isComputedPropertyName,
+ isConditionalExpression,
isEmptyStatement,
isEnumDeclaration,
isExportAssignment,
@@ -13,14 +18,24 @@ import {
isImportEqualsDeclaration,
isImportTypeNode,
isInterfaceDeclaration,
+ isJsxAttribute,
+ isJsxExpression,
isLiteralTypeNode,
isModuleDeclaration,
isNamedExports,
isNamedImports,
isNamespaceExport,
isNamespaceImport,
+ isNonNullExpression,
+ isObjectLiteralExpression,
+ isParenthesizedExpression,
+ isPropertyAssignment,
+ isSatisfiesExpression,
+ isSpreadAssignment,
+ isSpreadElement,
isStringLiteralLikeNode,
isTypeAliasDeclaration,
+ isTypeAssertion,
isVariableStatement,
ModifierFlags,
SyntaxKind,
@@ -51,6 +66,13 @@ export interface SourceAnalysis {
typeOnly: boolean;
}
+export interface SourceTypographyLiteral {
+ column: number;
+ line: number;
+ property: 'fontSize' | 'textStyle';
+ value: string;
+}
+
const PARSE_ROOT = '/architecture-sources';
const CONFIG_PATH = `${PARSE_ROOT}/tsconfig.json`;
const SEED_PATH = `${PARSE_ROOT}/seed.tsx`;
@@ -128,6 +150,12 @@ const read = (virtualPath: string, fileName: string): SourceFile => {
return sourceFile;
};
+const parseSource = (fileName: string, text: string, { jsx }: SourceAnalysisOptions): SourceFile => {
+ const virtualPath = stage(fileName, text, resolveJsx(fileName, jsx));
+ flush();
+ return read(virtualPath, fileName);
+};
+
const hasExportModifier = (statement: Statement): boolean => {
const { modifierFlags } = statement as { modifierFlags?: ModifierFlags };
return modifierFlags !== undefined && (modifierFlags & ModifierFlags.Export) !== 0;
@@ -279,10 +307,8 @@ export const primeSourceAnalysis = (
flush();
};
-export const analyzeSource = (fileName: string, text: string, { jsx }: SourceAnalysisOptions = {}): SourceAnalysis => {
- const virtualPath = stage(fileName, text, resolveJsx(fileName, jsx));
- flush();
- const sourceFile = read(virtualPath, fileName);
+export const analyzeSource = (fileName: string, text: string, options: SourceAnalysisOptions = {}): SourceAnalysis => {
+ const sourceFile = parseSource(fileName, text, options);
return {
moduleReferences: collectModuleReferences(sourceFile),
@@ -291,6 +317,78 @@ export const analyzeSource = (fileName: string, text: string, { jsx }: SourceAna
};
};
+/** Collects literal typography values without interpreting identifiers, calls, or condition tests as CSS values. */
+export const collectTypographyLiterals = (
+ fileName: string,
+ text: string,
+ options: SourceAnalysisOptions = {}
+): SourceTypographyLiteral[] => {
+ const sourceFile = parseSource(fileName, text, options);
+ const literals: SourceTypographyLiteral[] = [];
+
+ const collectValue = (node: Node, property: SourceTypographyLiteral['property']): void => {
+ if (isStringLiteralLikeNode(node)) {
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
+ literals.push({ column: character + 1, line: line + 1, property, value: node.text });
+ } else if (
+ isParenthesizedExpression(node) ||
+ isAsExpression(node) ||
+ isSatisfiesExpression(node) ||
+ isTypeAssertion(node) ||
+ isNonNullExpression(node) ||
+ isSpreadElement(node) ||
+ isSpreadAssignment(node)
+ ) {
+ collectValue(node.expression, property);
+ } else if (isJsxExpression(node) && node.expression) {
+ collectValue(node.expression, property);
+ } else if (isConditionalExpression(node)) {
+ collectValue(node.whenTrue, property);
+ collectValue(node.whenFalse, property);
+ } else if (isBinaryExpression(node)) {
+ if (
+ node.operatorToken.kind === SyntaxKind.BarBarToken ||
+ node.operatorToken.kind === SyntaxKind.QuestionQuestionToken
+ ) {
+ collectValue(node.left, property);
+ collectValue(node.right, property);
+ } else if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
+ collectValue(node.right, property);
+ }
+ } else if (isArrayLiteralExpression(node)) {
+ node.elements.forEach((element) => collectValue(element, property));
+ } else if (isObjectLiteralExpression(node)) {
+ for (const entry of node.properties) {
+ if (isPropertyAssignment(entry)) {
+ collectValue(entry.initializer, property);
+ } else if (isSpreadAssignment(entry)) {
+ collectValue(entry.expression, property);
+ }
+ }
+ }
+ };
+
+ const visit = (node: Node): void => {
+ if ((isJsxAttribute(node) || isPropertyAssignment(node)) && node.initializer) {
+ const name = node.name;
+ const property =
+ isComputedPropertyName(name) && isStringLiteralLikeNode(name.expression)
+ ? name.expression.text
+ : isIdentifier(name) || isStringLiteralLikeNode(name)
+ ? name.text
+ : undefined;
+ if (property === 'fontSize' || property === 'textStyle') {
+ collectValue(node.initializer, property);
+ return;
+ }
+ }
+ node.forEachChild(visit);
+ };
+
+ visit(sourceFile);
+ return literals;
+};
+
export const closeSourceAnalysis = (): void => {
snapshot?.dispose();
api?.close();
diff --git a/invokeai/frontend/webv2/src/architecture/typographyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/typographyPolicy.test.ts
new file mode 100644
index 0000000000..3721b7da10
--- /dev/null
+++ b/invokeai/frontend/webv2/src/architecture/typographyPolicy.test.ts
@@ -0,0 +1,82 @@
+import { afterAll, describe, expect, it } from 'vitest';
+
+import { isProductionSourcePath } from './dependencyPolicy';
+import { closeSourceAnalysis, primeSourceAnalysis } from './tsSourceAnalysis';
+import { checkTypographySource } from './typographyPolicy';
+
+const sources = import.meta.glob('../**/*.{ts,tsx}', {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+}) as Record<string, string>;
+
+afterAll(closeSourceAnalysis);
+
+describe('retired typography tokens', () => {
+ it('reports both typography properties with source positions and the replacement', () => {
+ expect(checkTypographySource('View.tsx', '<Text fontSize="2xs" />;\nconst recipe = { textStyle: "2xs" };')).toEqual(
+ [
+ 'View.tsx:1:16: fontSize uses retired typography token "2xs"; use "xs" for 10px type.',
+ 'View.tsx:2:29: textStyle uses retired typography token "2xs"; use "xs" for 10px type.',
+ ]
+ );
+ });
+
+ it.each([
+ ['JSX expression', '<Text fontSize={"2xs"} />'],
+ ['template literal', '<Text textStyle={`2xs`} />'],
+ ['escaped string', '<Text fontSize={"\\u0032xs"} />'],
+ ['conditional branch', '<Text fontSize={compact ? "2xs" : "md"} />'],
+ ['logical fallback', '<Text fontSize={size ?? "2xs"} />'],
+ ['logical alternative', '<Text fontSize={size || "2xs"} />'],
+ ['conditional value', '<Text textStyle={compact && "2xs"} />'],
+ ['responsive array', '<Text fontSize={["md", null, "2xs"]} />'],
+ ['responsive object', '<Text textStyle={{ base: "xs", md: { _dark: "2xs" } }} />'],
+ ['type assertion', '<Text fontSize={("2xs" as string)} />'],
+ ['satisfies expression', '<Text fontSize={"2xs" satisfies string} />'],
+ ['recipe condition', 'defineRecipe({ base: { _hover: { fontSize: "2xs" } } })'],
+ ['style prop', '<Text css={{ fontSize: { base: "md", lg: "2xs" } }} />'],
+ ['quoted property', '({ "textStyle": compact ? "xs" : "2xs" })'],
+ ['computed property', '({ ["fontSize"]: "2xs" })'],
+ ['responsive spread', '({ fontSize: { ...{ base: "2xs" } } })'],
+ ])('rejects a retired %s value', (_, expression) => {
+ const violations = checkTypographySource('example.tsx', `const example = ${expression};`);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]).toContain('uses retired typography token "2xs"');
+ });
+
+ it('allows current tokens, custom CSS, unrelated literals, and deliberate stock-name mapping data', () => {
+ expect(
+ checkTypographySource(
+ 'allowed.tsx',
+ `
+ // The stock fontSize="2xs" is now xs.
+ const example = <Text
+ fontSize={{ base: 'xs', sm: 'sm', md: 'md', lg: '1.25rem' }}
+ textStyle={mode === '2xs' ? 'xs' : 'sm'}
+ data-size="2xs"
+ size="2xs"
+ />;
+ const styles = { fontSize: 'var(--custom-font-size)', nested: { textStyle: 'label' } };
+ const computed = <Text fontSize={renameStockSize('2xs')} />;
+ const stockToWorkbench = { '2xs': 'xs', xs: 'md', sm: 'lg' };
+ const stockNames = new Set(['2xs', 'xs', 'sm']);
+ const fontSize = 'stockLabel';
+ const stockLabels = { [fontSize]: '2xs' };
+ const description = 'fontSize: "2xs"';
+ type Stock = { fontSize: '2xs' | 'xs' };
+ `
+ )
+ ).toEqual([]);
+ });
+
+ it('keeps retired typography values out of production JSX and style objects', () => {
+ const entries = Object.entries(sources)
+ .map(([path, source]) => [path.replace(/^\.\.\//, ''), source] as const)
+ .filter(([path]) => isProductionSourcePath(path));
+
+ primeSourceAnalysis(entries);
+ const violations = entries.flatMap(([path, source]) => checkTypographySource(path, source));
+ expect(violations).toEqual([]);
+ }, 30_000);
+});
diff --git a/invokeai/frontend/webv2/src/architecture/typographyPolicy.ts b/invokeai/frontend/webv2/src/architecture/typographyPolicy.ts
new file mode 100644
index 0000000000..021ca6d53b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/architecture/typographyPolicy.ts
@@ -0,0 +1,10 @@
+import { collectTypographyLiterals } from './tsSourceAnalysis';
+
+/** Chakra accepts arbitrary CSS strings, so its generated types cannot reject the retired token. */
+export const checkTypographySource = (sourcePath: string, source: string): string[] =>
+ collectTypographyLiterals(sourcePath, source)
+ .filter(({ value }) => value === '2xs')
+ .map(
+ ({ column, line, property }) =>
+ `${sourcePath}:${line}:${column}: ${property} uses retired typography token "2xs"; use "xs" for 10px type.`
+ );
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx
index 271537bc88..7f4b9d86d1 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx
@@ -96,6 +96,9 @@ describe('GenerateConceptsContent', () => {
it('discards a concept menu when switching projects with the same concept', async () => {
const { onCommit, onCommitImmediate, renderProject, row } = await render();
+ await stepWeight(row);
+ expect(row.querySelector('[role="slider"]')?.getAttribute('aria-valuenow')).toBe('0.8');
+
await act(() => {
row
.querySelector('[data-list-primary]')
@@ -108,6 +111,7 @@ describe('GenerateConceptsContent', () => {
expect(document.querySelector('[role="menu"][data-state="open"]')).toBeNull();
await renderProject('project-1');
expect(document.querySelector('[role="menu"][data-state="open"]')).toBeNull();
+ act(() => flushGenerateDrafts());
expect(onCommit).not.toHaveBeenCalled();
expect(onCommitImmediate).not.toHaveBeenCalled();
});
@@ -161,7 +165,7 @@ describe('GenerateConceptsContent', () => {
});
it('keeps concepts from another model removable when the model cannot use concepts', async () => {
- const { row, onCommitImmediate } = await render(SD3_MODEL);
+ const { row, onCommit } = await render(SD3_MODEL);
expect(row.textContent).toContain('Ink Wash');
expect(row.textContent).toContain('widgets.generate.incompatible');
@@ -173,7 +177,8 @@ describe('GenerateConceptsContent', () => {
remove?.click();
});
- expect(onCommitImmediate).toHaveBeenCalledWith({ loras: [] });
+ expect(onCommit).toHaveBeenCalledTimes(1);
+ expect(applied(onCommit.mock.calls[0]?.[0])).toBeUndefined();
});
it('marks a same-family concept incompatible when the model cannot use concepts', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
index 2ea540dfc7..ca1d317992 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx
@@ -16,15 +16,13 @@ import {
syncGenerateLorasWithModels,
} from '@features/generation/core/settings';
import { Field } from '@platform/ui';
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import type { GenerateSettingsUpdate } from './generateDebounce';
-import { useRegisterGenerateDraftFlusher } from './generateDraftRegistry';
import { GenerationModelSelect as ModelSelect, useGenerationUi } from './GenerationUiContext';
import { ConceptList, ConceptRow, type ConceptUpdate } from './shared/ConceptRow';
-import { useDebouncedDraftValue } from './useDebouncedDraftValue';
interface GenerateConceptsContentProps {
settings: GenerateSettings;
@@ -35,8 +33,6 @@ interface GenerateConceptsContentProps {
onCommitImmediate: (patch: Partial<GenerateSettings>) => void;
}
-const LORA_WEIGHT_DEBOUNCE_MS = 250;
-
/** Whether the selected model's graph will load this concept: its family must take LoRAs and match the LoRA. */
export const isCompatibleLora = (lora: GenerateLora, selectedModel: GenerateModelConfig | undefined): boolean =>
Boolean(selectedModel && isLoraSupported(selectedModel) && isLoraCompatibleWithModel(lora.model, selectedModel));
@@ -50,6 +46,7 @@ export const GenerateConceptsContent = ({
settings,
}: GenerateConceptsContentProps) => {
const { t } = useTranslation();
+ const models = useGenerationUi().models;
const loras = useMemo(() => syncGenerateLorasWithModels(settings.loras, loraModels), [loraModels, settings.loras]);
const selectedLoraKeys = useMemo(() => new Set(loras.map((lora) => lora.model.key)), [loras]);
@@ -63,36 +60,42 @@ export const GenerateConceptsContent = ({
});
};
- const updateLora = (modelKey: string, patch: ConceptUpdate) => {
- onCommit((settings) => {
- const latestLoras = syncGenerateLorasWithModels(settings.loras, loraModels);
- const hasLora = latestLoras.some((lora) => lora.model.key === modelKey);
-
- if (!hasLora) {
- return settings;
- }
-
- return {
- ...settings,
- loras: latestLoras.map((lora) => (lora.model.key === modelKey ? { ...lora, ...patch } : lora)),
- };
- });
- };
+ const updateLora = useCallback(
+ (modelKey: string, patch: ConceptUpdate) => {
+ onCommit((settings) => {
+ const latestLoras = syncGenerateLorasWithModels(settings.loras, loraModels);
+ const hasLora = latestLoras.some((lora) => lora.model.key === modelKey);
+
+ if (!hasLora) {
+ return settings;
+ }
+
+ return {
+ ...settings,
+ loras: latestLoras.map((lora) => (lora.model.key === modelKey ? { ...lora, ...patch } : lora)),
+ };
+ });
+ },
+ [loraModels, onCommit]
+ );
- const removeLora = (modelKey: string) => {
- onCommitImmediate({ loras: loras.filter((lora) => lora.model.key !== modelKey) });
- };
+ const removeLora = useCallback(
+ (modelKey: string) => {
+ onCommit((settings) => ({ ...settings, loras: settings.loras.filter((lora) => lora.model.key !== modelKey) }));
+ },
+ [onCommit]
+ );
const rows =
loras.length > 0 ? (
<Box mx={-1}>
<ConceptList label={t('widgets.generate.concepts')} projectId={projectId}>
{loras.map((lora) => (
- <GenerateConceptRow
+ <ConceptRow
key={lora.model.key}
isCompatible={isCompatibleLora(lora, selectedModel)}
lora={lora}
- projectId={projectId}
+ models={models}
onRemove={removeLora}
onUpdate={updateLora}
/>
@@ -143,42 +146,3 @@ export const GenerateConceptsContent = ({
</Stack>
);
};
-
-/** Holds the weight as a debounced draft so scrubbing does not commit settings per step. */
-const GenerateConceptRow = ({
- isCompatible,
- lora,
- onRemove,
- onUpdate,
- projectId,
-}: {
- isCompatible: boolean;
- lora: GenerateLora;
- onRemove: (key: string) => void;
- onUpdate: (key: string, update: ConceptUpdate) => void;
- projectId: string;
-}) => {
- const models = useGenerationUi().models;
- const {
- draftValue: draftWeight,
- flushDraftValue,
- setDraftValue: setWeight,
- } = useDebouncedDraftValue({
- delayMs: LORA_WEIGHT_DEBOUNCE_MS,
- onCommit: (weight: number) => onUpdate(lora.model.key, { weight }),
- resetKey: projectId,
- value: lora.weight,
- });
-
- useRegisterGenerateDraftFlusher(flushDraftValue);
-
- return (
- <ConceptRow
- models={models}
- isCompatible={isCompatible}
- lora={draftWeight === lora.weight ? lora : { ...lora, weight: draftWeight }}
- onRemove={onRemove}
- onUpdate={(key, update) => (update.weight === undefined ? onUpdate(key, update) : setWeight(update.weight))}
- />
- );
-};
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.tsx
index 9c1c7c2b0d..a43e157155 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
@@ -1,6 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
import type { GenerationModelCatalogItem } from '@features/generation/contracts';
-import type { LoraModelConfig } from '@features/generation/core/types';
+import type { GenerateLora, LoraModelConfig } from '@features/generation/core/types';
import type { ComponentType } from 'react';
import { ChakraProvider } from '@chakra-ui/react';
@@ -17,6 +17,7 @@ import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import { GenerateWidgetView } from './GenerateWidgetView';
import { GenerationUiProvider, type GenerationUiAdapter } from './GenerationUiContext';
@@ -225,6 +226,35 @@ afterEach(async () => {
});
describe('GenerateSettingsForm render isolation', () => {
+ it('preserves a settled weight draft when removing another concept from an already open menu', async () => {
+ const first: LoraModelConfig = { base: 'sdxl', key: 'ink', name: 'Ink', type: 'lora' };
+ const second: LoraModelConfig = { base: 'sdxl', key: 'chalk', name: 'Chalk', type: 'lora' };
+ await settle(() =>
+ storedValues().patchSnapshot({
+ loras: [first, second].map((model) => ({ isEnabled: true, model, weight: 0.75 })),
+ })
+ );
+ const row = (name: string) => host!.querySelector<HTMLElement>(`[role="group"][aria-label="${name}"]`)!;
+
+ // Capture the second row's menu before the first row's 250 ms draft has committed.
+ await settle(() => {
+ row('Ink')
+ .querySelector('[role="slider"]')!
+ .dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' }));
+ row('Chalk')
+ .querySelector('[data-list-primary]')!
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ });
+ await expect.poll(() => (storedValues().getSnapshot().loras as GenerateLora[])[0]?.weight).toBe(0.8);
+ const remove = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (item) => item.textContent === 'widgets.generate.conceptMenu.remove'
+ );
+ expect(remove).toBeDefined();
+ await act(() => userEvent.click(remove!));
+
+ expect(storedValues().getSnapshot().loras).toEqual([{ isEnabled: true, model: first, weight: 0.8 }]);
+ });
+
it('re-renders only the owning section while scrubbing, and nothing when the debounce persists it', async () => {
const scrubber = stepsScrubber();
const rect = scrubber.getBoundingClientRect();
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.browser.test.tsx
index 3961757641..2a7d027005 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.browser.test.tsx
@@ -1,13 +1,23 @@
import type { GenerateLora } from '@features/generation/core/types';
import { ChakraProvider } from '@chakra-ui/react';
+import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { system } from '@theme/system';
-import { act } from 'react';
+import { act, Profiler } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import { ConceptList, type ConceptModelPort, ConceptRow, type ConceptRowProps } from './ConceptRow';
+import { GenerateFieldContextMenu } from './GenerateFieldContextMenu';
+
+const rowCommits = new Map<string, number>();
+const countRowCommit = (id: string) => {
+ rowCommits.set(id, (rowCommits.get(id) ?? 0) + 1);
+};
+
+const STEPS_STYLE = { marginTop: 200 };
+const copySteps = () => '30';
const PIXEL =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAF/gL+XcX1WQAAAABJRU5ErkJggg==';
@@ -32,23 +42,31 @@ const makeLora = (model: Partial<GenerateLora['model']> = {}): GenerateLora => (
type Handlers = Partial<Pick<ConceptRowProps, 'models' | 'onRemove' | 'onUpdate'>>;
const renderList = async (loras: GenerateLora[], handlers: Handlers = {}) => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
+ if (!host) {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ }
await act(() =>
root?.render(
<ChakraProvider value={system}>
<ConceptList label="Concepts" projectId="project-1">
{loras.map((lora) => (
- <ConceptRow
- key={lora.model.key}
- models={handlers.models ?? MODELS}
- lora={lora}
- onRemove={handlers.onRemove ?? vi.fn()}
- onUpdate={handlers.onUpdate ?? vi.fn()}
- />
+ <Profiler key={lora.model.key} id={lora.model.key} onRender={countRowCommit}>
+ <ConceptRow
+ models={handlers.models ?? MODELS}
+ lora={lora}
+ onRemove={handlers.onRemove ?? vi.fn()}
+ onUpdate={handlers.onUpdate ?? vi.fn()}
+ />
+ </Profiler>
))}
</ConceptList>
+ <GenerateFieldContextMenu copyValue={copySteps}>
+ <div data-testid="steps-field" style={STEPS_STYLE}>
+ Steps
+ </div>
+ </GenerateFieldContextMenu>
</ChakraProvider>
)
);
@@ -58,7 +76,8 @@ const renderList = async (loras: GenerateLora[], handlers: Handlers = {}) => {
const render = (lora: GenerateLora, handlers: Handlers = {}) => renderList([lora], handlers);
-const menuLabels = () => [...document.querySelectorAll('[role="menuitem"]')].map((item) => item.textContent);
+const menuLabels = () =>
+ [...document.querySelectorAll('[role="menu"][data-state="open"] [role="menuitem"]')].map((item) => item.textContent);
afterEach(async () => {
await act(() => root?.unmount());
@@ -68,6 +87,91 @@ afterEach(async () => {
});
describe('ConceptRow', () => {
+ it.each(['remove', 'toggle'] as const)(
+ 'uses the current row handler for a menu %s after settings change',
+ async (action) => {
+ const onChange = vi.fn();
+ const first = makeLora();
+ const second = makeLora({ key: 'lora-2', name: 'Chalk' });
+ const renderValues = (loras: GenerateLora[]) =>
+ renderList(loras, {
+ onRemove: (key) => onChange(loras.filter((lora) => lora.model.key !== key)),
+ onUpdate: (key, update) =>
+ onChange(loras.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora))),
+ });
+ const list = await renderValues([first, second]);
+ await act(() =>
+ userEvent.click(list.querySelectorAll<HTMLElement>('[data-list-primary]')[1]!, { button: 'right' })
+ );
+ await expect.poll(() => document.querySelector('[role="menu"]')).not.toBeNull();
+ await renderValues([
+ { ...first, weight: 1.25 },
+ { ...second, isEnabled: false },
+ ]);
+ const label = `widgets.generate.conceptMenu.${action === 'remove' ? 'remove' : 'enable'}`;
+ const menuItem = () =>
+ [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((item) => item.textContent === label);
+ await expect.poll(menuItem).toBeDefined();
+ await act(() => userEvent.click(menuItem()!));
+ expect(onChange).toHaveBeenLastCalledWith(
+ action === 'remove' ? [{ ...first, weight: 1.25 }] : [{ ...first, weight: 1.25 }, second]
+ );
+ }
+ );
+
+ it.each(['weight', 'steps'] as const)(
+ 'hands a right-click between row and %s menus without losing the next menu',
+ async (field) => {
+ const list = await render(makeLora());
+ const primary = list.querySelector<HTMLElement>('[data-list-primary]')!;
+ const control = list.querySelector<HTMLElement>(
+ field === 'weight' ? '[data-scope="scrubber"]' : '[data-testid="steps-field"]'
+ )!;
+ await act(() => userEvent.click(primary, { button: 'right' }));
+ await expect.poll(menuLabels).toContain('widgets.generate.conceptMenu.remove');
+ await act(() => userEvent.click(control, { button: 'right', position: { x: 8, y: 8 } }));
+ await expect.poll(menuLabels).toContain('widgets.generate.copyValue');
+ expect(document.querySelectorAll('[role="menu"][data-state="open"]')).toHaveLength(1);
+ await act(() => userEvent.click(primary, { button: 'right' }));
+ await expect.poll(menuLabels).toContain('widgets.generate.conceptMenu.remove');
+ expect(document.querySelectorAll('[role="menu"][data-state="open"]')).toHaveLength(1);
+ }
+ );
+
+ it('keeps a drag local to its row and commits its final weight once', async () => {
+ const onUpdate = vi.fn();
+ const list = await renderList([makeLora(), makeLora({ key: 'lora-2', name: 'Chalk' })], { onUpdate });
+ const frame = list.querySelector<HTMLElement>('[data-scope="scrubber"]')!;
+ const rect = frame.getBoundingClientRect();
+ const pointer = (target: EventTarget, type: string, fraction: number) =>
+ act(() => {
+ target.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button: 0,
+ clientX: rect.left + 8 + fraction * (rect.width - 16),
+ pointerId: 1,
+ })
+ );
+ });
+
+ await pointer(frame, 'pointerdown', 0.2);
+ rowCommits.clear();
+ for (let step = 1; step <= 10; step += 1) {
+ await pointer(window, 'pointermove', 0.2 + step * 0.05);
+ }
+ await pointer(window, 'pointerup', 0.7);
+ const finalWeight = Number(frame.querySelector('[role="slider"]')!.getAttribute('aria-valuenow'));
+
+ expect(finalWeight).not.toBe(0.75);
+ expect(rowCommits.get('lora-1')).toBeGreaterThan(0);
+ expect(rowCommits.get('lora-2') ?? 0).toBe(0);
+ expect(onUpdate).not.toHaveBeenCalled();
+ await expect.poll(() => onUpdate.mock.calls).toEqual([['lora-1', { weight: finalWeight }]]);
+ await act(() => flushWorkbenchDrafts());
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ });
+
it('shows the model cover as its thumbnail', async () => {
const row = await render(makeLora({ cover_image: 'cover.png' }));
@@ -92,6 +196,8 @@ describe('ConceptRow', () => {
row.querySelector<HTMLElement>('[role="slider"]')!.focus();
await act(() => userEvent.keyboard('{ArrowRight}'));
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ await act(() => flushWorkbenchDrafts());
expect(onUpdate).toHaveBeenLastCalledWith('lora-1', { weight: 0.8 });
await act(() =>
@@ -121,7 +227,7 @@ describe('ConceptRow', () => {
await openMenu();
await choose('widgets.generate.resetToConceptDefault');
- expect(onUpdate).toHaveBeenLastCalledWith('lora-1', { weight: 0.75 });
+ await expect.poll(() => onUpdate.mock.lastCall).toEqual(['lora-1', { weight: 0.75 }]);
await openMenu();
await choose('widgets.generate.conceptMenu.disable');
@@ -132,15 +238,18 @@ describe('ConceptRow', () => {
expect(onRemove).toHaveBeenCalledWith('lora-1');
});
- it('opens the menu from a right-click but not from a normal click', async () => {
+ it.each(['{Enter}', ' '])('opens row actions on %s and restores focus on Escape', async (key) => {
const row = await render(makeLora());
const primary = row.querySelector<HTMLElement>('[data-list-primary]')!;
- await act(() => userEvent.click(primary));
- expect(document.querySelector('[role="menu"]')).toBeNull();
-
- await act(() => userEvent.click(primary, { button: 'right' }));
- await expect.poll(() => document.querySelector('[role="menu"]')).not.toBeNull();
+ expect(primary.getAttribute('aria-haspopup')).toBe('menu');
+ primary.focus();
+ await act(() => userEvent.keyboard(key));
+ await expect.poll(menuLabels).toContain('widgets.generate.conceptMenu.remove');
+ expect(primary.getAttribute('aria-expanded')).toBe('true');
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.activeElement).toBe(primary);
+ expect(primary.getAttribute('aria-expanded')).toBe('false');
});
it('moves the open menu to a second row right-clicked while the first is open', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx
index 4026ee77d0..ef67a5ec51 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx
@@ -1,18 +1,19 @@
/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- ListItem slots take JSX; the React Compiler memoizes them. */
import type { GenerateLora } from '@features/generation/core/types';
-import type { ListContextMenuAnchor } from '@platform/ui/list/ListItem';
import type { MouseEvent, ReactNode } from 'react';
import { Avatar, Badge, Box, Flex, Icon, Menu, Portal } from '@chakra-ui/react';
import { DEFAULT_LORA_WEIGHT_CONFIG, getDefaultLoraWeight } from '@features/generation/core/settings';
+import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
+import { useRegisterDraftFlusher } from '@platform/react/draftRegistry';
import { IconButton } from '@platform/ui/Button';
import { ListItem } from '@platform/ui/list/ListItem';
import { ListStack } from '@platform/ui/list/ListStack';
-import { MenuActionItem, MenuContent } from '@platform/ui/Menu';
+import { MenuActionItem, MenuContent, useContextMenu } from '@platform/ui/Menu';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { Tooltip } from '@platform/ui/Tooltip';
import { BoxIcon, ExternalLinkIcon, PowerIcon, PowerOffIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';
-import { createContext, memo, use, useCallback, useMemo, useState } from 'react';
+import { createContext, memo, use, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { GenerateFieldContextMenu } from './GenerateFieldContextMenu';
@@ -34,11 +35,11 @@ export type ConceptUpdate = Partial<Pick<GenerateLora, 'isEnabled' | 'weight'>>;
export interface ConceptRowProps {
/** False dims the row, badges it, and locks it off; the caller decides compatibility against its main model. */
isCompatible?: boolean;
- /** `lora.weight` is the displayed weight, so a caller that defers commits passes its draft here. */
+ /** The committed concept. Weight edits stay in a local draft until idle or a workbench flush. */
lora: GenerateLora;
models: ConceptModelPort;
onRemove: (key: string) => void;
- /** Fires per weight step and on toggle; the caller owns any debouncing. */
+ /** Weight commits are debounced; toggles commit immediately. Apply updates to the latest settings. */
onUpdate: (key: string, update: ConceptUpdate) => void;
}
@@ -59,29 +60,9 @@ const findNeighbourRow = (from: Element | null): HTMLElement | null => {
return null;
};
-/** What the list's one context menu acts on, captured from the row that opened it. */
-interface ConceptMenuTarget extends ListContextMenuAnchor {
- isActive: boolean;
- isAtDefault: boolean;
- isCompatible: boolean;
- key: string;
- onOpenInModelManager?: () => void;
- onRemove: () => void;
- onReset: () => void;
- onToggle: () => void;
-}
-
-interface ConceptMenuPort {
- open: (target: ConceptMenuTarget) => void;
- openKey: string | null;
-}
+const ConceptProjectContext = createContext<string | undefined>(undefined);
-const ConceptMenuContext = createContext<ConceptMenuPort | null>(null);
-
-/**
- * The family's short list, with dividers between concepts. It owns the rows' single context menu: one menu per row
- * raced when a second row was right-clicked while the first's menu was closing, and both closed.
- */
+/** A short concept list shares its project lifetime with the rows' drafts and menus. */
export const ConceptList = ({
children,
label,
@@ -90,47 +71,64 @@ export const ConceptList = ({
children: ReactNode;
label: string;
projectId: string;
-}) => {
- const [target, setTarget] = useState<ConceptMenuTarget | null>(null);
- const [menuProjectId, setMenuProjectId] = useState(projectId);
- // Reset only the menu: remounting rows would flush their pending weight drafts into the new project.
- if (menuProjectId !== projectId) {
- setMenuProjectId(projectId);
- setTarget(null);
- }
- const port = useMemo<ConceptMenuPort>(() => ({ open: setTarget, openKey: target?.key ?? null }), [target]);
- const handleClose = useCallback(() => {
- target?.restoreFocus();
- setTarget(null);
- }, [target]);
-
- return (
- <ConceptMenuContext value={port}>
- <ListStack dividers label={label}>
- {children}
- </ListStack>
- {/* Keyed per row so switching rows replaces the menu rather than retargeting an open one. */}
- <ConceptContextMenu key={target?.key ?? 'closed'} target={target} onClose={handleClose} />
- </ConceptMenuContext>
- );
-};
+}) => (
+ <ConceptProjectContext value={projectId}>
+ <ListStack dividers label={label}>
+ {children}
+ </ListStack>
+ </ConceptProjectContext>
+);
/**
* One applied LoRA/concept: a list row (thumbnail, identity, toggle, remove, and a context menu) with its weight
* scrubber as the row's detail, so the whole item shares one hover surface.
*/
-export const ConceptRow = memo(function ConceptRow({
+export const ConceptRow = memo(function ConceptRow(props: ConceptRowProps) {
+ const projectId = use(ConceptProjectContext);
+ const { lora, onUpdate } = props;
+ const commitWeight = useCallback(
+ (weight: number) => onUpdate(lora.model.key, { weight }),
+ [lora.model.key, onUpdate]
+ );
+ const {
+ draftValue: weight,
+ flushDraftValue,
+ setDraftValue,
+ } = useDebouncedDraftValue({
+ delayMs: 250,
+ onCommit: commitWeight,
+ resetKey: projectId,
+ value: lora.weight,
+ });
+ useRegisterDraftFlusher(flushDraftValue);
+ const update = useCallback(
+ (key: string, update: ConceptUpdate) => {
+ if (update.weight === undefined) {
+ onUpdate(key, update);
+ } else {
+ setDraftValue(update.weight);
+ }
+ },
+ [onUpdate, setDraftValue]
+ );
+
+ // Reset the menu on project changes without remounting/flushing the weight draft into the next project.
+ return <ConceptRowContent key={projectId} {...props} weight={weight} onUpdate={update} />;
+});
+
+const ConceptRowContent = ({
isCompatible = true,
lora,
models,
onRemove,
onUpdate,
-}: ConceptRowProps) {
+ weight,
+}: ConceptRowProps & { weight: number }) => {
const { t } = useTranslation();
const { key, name, trigger_phrases: triggerPhrases } = lora.model;
const isActive = lora.isEnabled && isCompatible;
const defaultWeight = getDefaultLoraWeight(lora.model);
- const menu = use(ConceptMenuContext);
+ const menu = useContextMenu();
const handleToggle = useCallback((isEnabled: boolean) => onUpdate(key, { isEnabled }), [key, onUpdate]);
const handleWeightChange = useCallback((weight: number) => onUpdate(key, { weight }), [key, onUpdate]);
const removeFrom = useCallback(
@@ -149,21 +147,8 @@ export const ConceptRow = memo(function ConceptRow({
[removeFrom]
);
const handleReset = useCallback(() => onUpdate(key, { weight: defaultWeight }), [defaultWeight, key, onUpdate]);
- const copyWeight = useCallback(() => String(lora.weight), [lora.weight]);
+ const copyWeight = useCallback(() => String(weight), [weight]);
const { openInModelManager } = models;
- const isAtDefault = lora.weight === defaultWeight;
- const handleContextMenu = (anchor: ListContextMenuAnchor) =>
- menu?.open({
- ...anchor,
- isActive,
- isAtDefault,
- isCompatible,
- key,
- onOpenInModelManager: openInModelManager ? () => openInModelManager(key) : undefined,
- onRemove: () => removeFrom(anchor.focusTarget()),
- onReset: handleReset,
- onToggle: () => handleToggle(!isActive),
- });
return (
<Box role="listitem">
@@ -213,7 +198,7 @@ export const ConceptRow = memo(function ConceptRow({
<Box bg="bg.muted" rounded="control">
<GenerateFieldContextMenu
copyValue={copyWeight}
- isAtDefault={lora.weight === defaultWeight}
+ isAtDefault={weight === defaultWeight}
resetLabel={t('widgets.generate.resetToConceptDefault')}
onReset={handleReset}
>
@@ -227,7 +212,7 @@ export const ConceptRow = memo(function ConceptRow({
max={DEFAULT_LORA_WEIGHT_CONFIG.sliderMax}
min={DEFAULT_LORA_WEIGHT_CONFIG.sliderMin}
step={DEFAULT_LORA_WEIGHT_CONFIG.coarseStep}
- value={lora.weight}
+ value={weight}
onChange={handleWeightChange}
/>
</GenerateFieldContextMenu>
@@ -251,74 +236,67 @@ export const ConceptRow = memo(function ConceptRow({
{lora.model.cover_image ? <Avatar.Image alt="" src={models.getImageUrl(key)} /> : null}
</Avatar.Root>
}
- isMenuOpen={menu?.openKey === key}
+ isMenuOpen={menu.anchor !== null}
role="presentation"
title={name}
- onContextMenu={menu ? handleContextMenu : undefined}
+ onContextMenu={menu.open}
/>
</Box>
- </Box>
- );
-});
-
-const ConceptContextMenu = ({ onClose, target }: { onClose: () => void; target: ConceptMenuTarget | null }) => {
- const { t } = useTranslation();
-
- return (
- <Menu.Root
- lazyMount
- open={target !== null}
- positioning={{
- getAnchorRect: () => (target ? { height: 1, width: 1, x: target.x, y: target.y } : null),
- placement: 'bottom-start',
- }}
- unmountOnExit
- onOpenChange={(event) => {
- if (!event.open) {
- onClose();
- }
- }}
- >
- <Portal>
- <Menu.Positioner>
- {target ? (
- <MenuContent minW="12rem">
- {target.onOpenInModelManager ? (
+ <Menu.Root
+ lazyMount
+ open={menu.anchor !== null}
+ positioning={{
+ getAnchorRect: () => (menu.anchor ? { height: 1, width: 1, x: menu.anchor.x, y: menu.anchor.y } : null),
+ placement: 'bottom-start',
+ }}
+ unmountOnExit
+ onOpenChange={(event) => {
+ if (!event.open) {
+ menu.close();
+ }
+ }}
+ >
+ <Portal>
+ <Menu.Positioner>
+ {menu.anchor ? (
+ <MenuContent minW="12rem">
+ {openInModelManager ? (
+ <MenuActionItem
+ icon={ExternalLinkIcon}
+ label={t('widgets.generate.conceptMenu.openInModelManager')}
+ value="open-in-model-manager"
+ onSelect={() => openInModelManager(key)}
+ />
+ ) : null}
<MenuActionItem
- icon={ExternalLinkIcon}
- label={t('widgets.generate.conceptMenu.openInModelManager')}
- value="open-in-model-manager"
- onSelect={target.onOpenInModelManager}
+ disabled={weight === defaultWeight || !isActive}
+ icon={RotateCcwIcon}
+ label={t('widgets.generate.resetToConceptDefault')}
+ value="reset-weight"
+ onSelect={handleReset}
/>
- ) : null}
- <MenuActionItem
- disabled={target.isAtDefault || !target.isActive}
- icon={RotateCcwIcon}
- label={t('widgets.generate.resetToConceptDefault')}
- value="reset-weight"
- onSelect={target.onReset}
- />
- <MenuActionItem
- disabled={!target.isCompatible}
- icon={target.isActive ? PowerOffIcon : PowerIcon}
- label={
- target.isActive ? t('widgets.generate.conceptMenu.disable') : t('widgets.generate.conceptMenu.enable')
- }
- value="toggle"
- onSelect={target.onToggle}
- />
- <Menu.Separator />
- <MenuActionItem
- icon={Trash2Icon}
- label={t('widgets.generate.conceptMenu.remove')}
- tone="danger"
- value="remove"
- onSelect={target.onRemove}
- />
- </MenuContent>
- ) : null}
- </Menu.Positioner>
- </Portal>
- </Menu.Root>
+ <MenuActionItem
+ disabled={!isCompatible}
+ icon={isActive ? PowerOffIcon : PowerIcon}
+ label={
+ isActive ? t('widgets.generate.conceptMenu.disable') : t('widgets.generate.conceptMenu.enable')
+ }
+ value="toggle"
+ onSelect={() => handleToggle(!isActive)}
+ />
+ <Menu.Separator />
+ <MenuActionItem
+ icon={Trash2Icon}
+ label={t('widgets.generate.conceptMenu.remove')}
+ tone="danger"
+ value="remove"
+ onSelect={() => removeFrom(menu.anchor?.focusTarget?.() ?? null)}
+ />
+ </MenuContent>
+ ) : null}
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </Box>
);
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx
index dc7dad35d5..0447c03aec 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx
@@ -2,9 +2,7 @@
import type { ReactNode } from 'react';
import { Box, Menu, Portal } from '@chakra-ui/react';
-import { createExternalStore } from '@platform/state/externalStore';
-import { MenuContent } from '@platform/ui/Menu';
-import { useId } from 'react';
+import { MenuContent, useContextMenu } from '@platform/ui/Menu';
import { useTranslation } from 'react-i18next';
interface GenerateFieldContextMenuProps {
@@ -18,13 +16,6 @@ interface GenerateFieldContextMenuProps {
resetLabel?: string;
}
-/**
- * One field menu is open at a time. A right-click on a second field leaves the first menu open (right-button
- * presses don't dismiss it), and the two menus' dismissal then raced so the next right-click closed both; switching
- * owners closes the first menu instead.
- */
-const openMenu = createExternalStore<{ owner: string | null; x: number; y: number }>({ owner: null, x: 0, y: 0 });
-
export const GenerateFieldContextMenu = ({
children,
copyValue,
@@ -33,15 +24,14 @@ export const GenerateFieldContextMenu = ({
resetLabel,
}: GenerateFieldContextMenuProps) => {
const { t } = useTranslation();
- const owner = useId();
- const point = openMenu.useSelector((menu) => (menu.owner === owner ? { x: menu.x, y: menu.y } : null));
+ const { anchor: point, close, open } = useContextMenu();
return (
<Box
w="full"
onContextMenu={(event) => {
event.preventDefault();
- openMenu.setSnapshot({ owner, x: event.clientX, y: event.clientY });
+ open({ x: event.clientX, y: event.clientY });
}}
>
{children}
@@ -52,8 +42,8 @@ export const GenerateFieldContextMenu = ({
placement: 'bottom-start',
}}
onOpenChange={(event) => {
- if (!event.open && openMenu.getSnapshot().owner === owner) {
- openMenu.patchSnapshot({ owner: null });
+ if (!event.open) {
+ close();
}
}}
>
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
index 0774e897ce..88e5f40d85 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx
@@ -7,7 +7,11 @@ import { createContext, use, useMemo } from 'react';
/** This UI port preserves dependency direction: Upscale cannot import Workbench. */
export interface UpscaleUiAdapter {
patchPromptDraft(values: ProjectPromptDraftPatch): void;
- patchValues(values: Partial<UpscaleWidgetValues>, origin?: 'user' | 'system'): void;
+ /** Functional patches run synchronously against the originating project's latest normalized values. */
+ patchValues(
+ values: Partial<UpscaleWidgetValues> | ((current: UpscaleWidgetValues) => Partial<UpscaleWidgetValues>),
+ origin?: 'user' | 'system'
+ ): void;
projectId: string;
promptDraft: ProjectPromptDraft;
rawValues: Record<string, unknown>;
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
index e732540834..9242a420a9 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
@@ -347,22 +347,29 @@ export const UpscaleWidgetView = () => {
const addLora = useCallback(
(model: ModelConfig | null) => {
- if (!values.model || !isLoraModelConfig(model) || !isLoraCompatibleWithModel(model, values.model)) {
+ if (!isLoraModelConfig(model)) {
return;
}
- patch({ loras: [...values.loras, { isEnabled: true, model, weight: getDefaultLoraWeight(model) }] });
+ patchValues((current) =>
+ current.model && isLoraCompatibleWithModel(model, current.model)
+ ? { loras: [...current.loras, { isEnabled: true, model, weight: getDefaultLoraWeight(model) }] }
+ : {}
+ );
},
- [patch, values.loras, values.model]
+ [patchValues]
);
const updateLora = useCallback(
(key: string, update: Partial<GenerateLora>) =>
- patch({ loras: values.loras.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora)) }),
- [patch, values.loras]
+ patchValues((current) => ({
+ loras: current.loras.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora)),
+ })),
+ [patchValues]
);
const removeLora = useCallback(
- (key: string) => patch({ loras: values.loras.filter((candidate) => candidate.model.key !== key) }),
- [patch, values.loras]
+ (key: string) =>
+ patchValues((current) => ({ loras: current.loras.filter((candidate) => candidate.model.key !== key) })),
+ [patchValues]
);
const selectedLoraKeys = useMemo(() => new Set(values.loras.map((lora) => lora.model.key)), [values.loras]);
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx
index 713f2ca30c..6756ec861a 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx
@@ -29,7 +29,7 @@ export const VideoConceptsSection = memo(
}: {
loras: GenerateLora[];
model: MainModelConfig | null;
- onChangeLoras: (loras: GenerateLora[]) => void;
+ onChangeLoras: (update: (current: GenerateLora[]) => GenerateLora[]) => void;
projectId: string;
}) {
const { t } = useTranslation();
@@ -55,18 +55,21 @@ export const VideoConceptsSection = memo(
return;
}
- onChangeLoras([...loras, { isEnabled: true, model: candidate, weight: getDefaultLoraWeight(candidate) }]);
+ onChangeLoras((current) => [
+ ...current,
+ { isEnabled: true, model: candidate, weight: getDefaultLoraWeight(candidate) },
+ ]);
},
- [loras, model, onChangeLoras]
+ [model, onChangeLoras]
);
const updateLora = useCallback(
(key: string, update: Partial<GenerateLora>) =>
- onChangeLoras(loras.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora))),
- [loras, onChangeLoras]
+ onChangeLoras((current) => current.map((lora) => (lora.model.key === key ? { ...lora, ...update } : lora))),
+ [onChangeLoras]
);
const removeLora = useCallback(
- (key: string) => onChangeLoras(loras.filter((candidate) => candidate.model.key !== key)),
- [loras, onChangeLoras]
+ (key: string) => onChangeLoras((current) => current.filter((candidate) => candidate.model.key !== key)),
+ [onChangeLoras]
);
return (
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
index c228167062..bfdbdab903 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx
@@ -10,7 +10,11 @@ export interface VideoUiAdapter {
findInGallery(ref: GalleryItemRef): void;
/** Read the selected upload board at upload time without subscribing to board changes. */
getUploadBoardId(): string;
- patchValues(values: Partial<VideoWidgetValues>, origin?: 'user' | 'system'): void;
+ /** Functional patches run synchronously against the originating project's latest normalized values. */
+ patchValues(
+ values: Partial<VideoWidgetValues> | ((current: VideoWidgetValues) => Partial<VideoWidgetValues>),
+ origin?: 'user' | 'system'
+ ): void;
/**
* Select item in Preview and request looping this window. Returns its playback token, or null if Preview could
* not be raised and no request was made.
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
index f5dc5a4f83..7d069652d4 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
@@ -356,36 +356,45 @@ export const VideoWidgetView = () => {
);
const clearReferences = useCallback(() => patch({ references: [] }), [patch]);
const setLoras = useCallback(
- (loras: VideoWidgetValues['loras']) => {
- // While enabled, follow a replacement accelerator set or restore model sampling defaults if none remains.
- // Preserve the edit and notify; never enable acceleration from a list edit.
- if (!values.model) {
- patch({ loras });
- return;
- }
+ (update: (current: VideoWidgetValues['loras']) => VideoWidgetValues['loras']) => {
+ let notice: Parameters<typeof toaster.create>[0] | undefined;
+ patchValues((current) => {
+ const loras = update(current.loras);
+ // While enabled, follow a replacement accelerator set or restore model sampling defaults if none remains.
+ // Preserve the edit and notify; never enable acceleration from a list edit.
+ if (!current.model) {
+ return { loras };
+ }
- const result = getAcceleratorLoraChangeResult(values, values.model, models, loras);
+ const result = getAcceleratorLoraChangeResult(current, current.model, models, loras);
+
+ if (result.outcome === 'switched') {
+ notice = {
+ description: t('widgets.video.acceleratorSwitchedDescription', {
+ name: result.acceleratorLoras?.map((lora) => lora.name).join(', ') ?? '',
+ steps: result.settings.steps,
+ }),
+ title: t('widgets.video.acceleratorSwitched', {
+ label: getVideoModelPolicy(current.model, current).ui.accelerator?.label ?? '',
+ }),
+ type: 'info',
+ };
+ } else if (result.outcome === 'disabled') {
+ notice = {
+ description: t('widgets.video.acceleratorBrokenDescription'),
+ title: t('widgets.video.acceleratorBroken'),
+ type: 'info',
+ };
+ }
- patch({ ...result.settings });
+ return { ...result.settings };
+ });
- if (result.outcome === 'switched') {
- toaster.create({
- description: t('widgets.video.acceleratorSwitchedDescription', {
- name: result.acceleratorLoras?.map((lora) => lora.name).join(', ') ?? '',
- steps: result.settings.steps,
- }),
- title: t('widgets.video.acceleratorSwitched', { label: policy.ui.accelerator?.label ?? '' }),
- type: 'info',
- });
- } else if (result.outcome === 'disabled') {
- toaster.create({
- description: t('widgets.video.acceleratorBrokenDescription'),
- title: t('widgets.video.acceleratorBroken'),
- type: 'info',
- });
+ if (notice) {
+ toaster.create(notice);
}
},
- [models, patch, policy.ui.accelerator?.label, t, values]
+ [models, patchValues, t]
);
const clearFirstFrame = useCallback(() => patch({ firstFrameImage: null }), [patch]);
const clearLastFrame = useCallback(() => patch({ lastFrameImage: null }), [patch]);
diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx
index 3b327b12e0..f22c6f5d97 100644
--- a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx
@@ -2,6 +2,9 @@ import type { LucideIcon } from 'lucide-react';
import type { ComponentProps } from 'react';
import { Box, HStack, Icon, Kbd, Menu, Stack, Text, useMenuContext } from '@chakra-ui/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { createExternalStore } from '@platform/state/externalStore';
+import { useCallback, useId } from 'react';
import { Tooltip } from './Tooltip';
import { useRegisterWidgetOverlay } from './widgetOverlays';
@@ -126,3 +129,39 @@ export const MenuIconItem = ({ disabled, icon, iconFill, label, onSelect, tone,
</Tooltip>
</Menu.Item>
);
+
+interface ContextMenuAnchor {
+ x: number;
+ y: number;
+ focusTarget?: () => HTMLElement | null;
+ restoreFocus?: () => void;
+}
+
+// Only the active gesture is retained. Actions and their enabled state belong to the live menu's render.
+const activeMenu = createExternalStore<{ owner: string | null; anchor: ContextMenuAnchor | null }>({
+ owner: null,
+ anchor: null,
+});
+
+/** Row and field menus share ownership so a second right-click replaces the first menu. */
+export const useContextMenu = () => {
+ const owner = useId();
+ const anchor = activeMenu.useSelector((menu) => (menu.owner === owner ? menu.anchor : null));
+ const open = useCallback((anchor: ContextMenuAnchor) => activeMenu.setSnapshot({ owner, anchor }), [owner]);
+ const close = useCallback(() => {
+ const menu = activeMenu.getSnapshot();
+ if (menu.owner !== owner) {
+ return;
+ }
+ activeMenu.setSnapshot({ owner: null, anchor: null });
+ menu.anchor?.restoreFocus?.();
+ }, [owner]);
+
+ useMountEffect(() => () => {
+ if (activeMenu.getSnapshot().owner === owner) {
+ activeMenu.setSnapshot({ owner: null, anchor: null });
+ }
+ });
+
+ return { anchor, close, open };
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx
index 7959fc4003..c2390ab81f 100644
--- a/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx
@@ -218,16 +218,35 @@ describe('list dividers', () => {
expect(rowA.right - line.right).toBeCloseTo(8, 0);
});
+ it('keeps static rows and their neighbouring dividers unchanged on hover', async () => {
+ await render(
+ <ListStack dividers label="subjects">
+ <ListItem title="one" />
+ <div role="listitem">
+ <ListItem role="presentation" title="two" />
+ </div>
+ <ListItem title="three" />
+ </ListStack>
+ );
+ const row = host.querySelectorAll<HTMLElement>('[data-list-surface]')[1]!;
+ const background = getComputedStyle(row).backgroundColor;
+
+ await userEvent.hover(row);
+ expect(row.querySelector('button')).toBeNull();
+ expect(getComputedStyle(row).backgroundColor).toBe(background);
+ expect(hairlines().map((line) => getComputedStyle(line).opacity)).toEqual(['1', '1']);
+ });
+
it('hides the hairlines either side of a pointed row, stacked or virtualized', async () => {
const opacities = () =>
[...host.querySelectorAll<HTMLElement>('[data-list-divider]')].map((line) => getComputedStyle(line).opacity);
await render(
<ListStack dividers label="subjects">
- <ListItem title="one" />
- <ListItem title="two" />
- <ListItem title="three" />
- <ListItem title="four" />
+ <ListItem onPress={() => undefined} title="one" />
+ <ListItem onPress={() => undefined} title="two" />
+ <ListItem onPress={() => undefined} title="three" />
+ <ListItem onPress={() => undefined} title="four" />
</ListStack>
);
const stacked = host.querySelectorAll<HTMLElement>('[role="listitem"]');
@@ -236,10 +255,10 @@ describe('list dividers', () => {
await expect.poll(opacities).toEqual(['0', '0', '1']);
await render(
<ListStack dividers label="subjects">
- <ListItem isMenuOpen title="one" />
- <ListItem title="two" />
- <ListItem title="three" />
- <ListItem title="four" />
+ <ListItem onContextMenu={() => undefined} isMenuOpen title="one" />
+ <ListItem onPress={() => undefined} title="two" />
+ <ListItem onPress={() => undefined} title="three" />
+ <ListItem onPress={() => undefined} title="four" />
</ListStack>
);
await userEvent.unhover(host);
@@ -248,12 +267,12 @@ describe('list dividers', () => {
// A caller-wrapped row (its own list item around the row) holding an open menu.
await render(
<ListStack dividers label="subjects">
- <ListItem title="one" />
+ <ListItem onPress={() => undefined} title="one" />
<div role="listitem">
- <ListItem isMenuOpen role="presentation" title="two" />
+ <ListItem onContextMenu={() => undefined} isMenuOpen role="presentation" title="two" />
</div>
- <ListItem title="three" />
- <ListItem title="four" />
+ <ListItem onPress={() => undefined} title="three" />
+ <ListItem onPress={() => undefined} title="four" />
</ListStack>
);
await expect.poll(opacities).toEqual(['0', '0', '1']);
diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx
index c34f36d4b1..60e54d4444 100644
--- a/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx
@@ -36,25 +36,22 @@ const IN_SLOT_CSS = {
// A row shows its pointed fill while hovered or while its context menu is open; the hairlines either side of it hide
// so that fill reads as one surface rather than a band between lines. `:has()` cannot nest, so a row wrapped by its
// caller (menu state on a descendant) is matched as "a sibling containing it" instead.
-const POINTED = ':is(:hover, [data-menu-open])';
+const POINTED = '[data-list-surface]:not([data-static]):is(:hover, [data-menu-open])';
const HIDDEN = { opacity: 0 } as const;
/** For a container of in-flow rows and dividers (`ListStack`); rows may be wrapped by their caller. */
export const IN_FLOW_DIVIDER_HIDING_CSS = {
[[
`& > ${POINTED} + [data-list-divider]`,
- '& > :has([data-menu-open]) + [data-list-divider]',
+ `& > :has(${POINTED}) + [data-list-divider]`,
`& > [data-list-divider]:has(+ ${POINTED})`,
- '& > [data-list-divider]:has(+ * [data-menu-open])',
+ `& > [data-list-divider]:has(+ * ${POINTED})`,
].join(', ')]: HIDDEN,
} as const;
/** For a container of row slots that each draw the divider below themselves (`List`). */
export const IN_SLOT_DIVIDER_HIDING_CSS = {
- [[
- `& > :has([data-list-row]${POINTED}) > [data-list-divider]`,
- `& > :has(+ * [data-list-row]${POINTED}) > [data-list-divider]`,
- ].join(', ')]: HIDDEN,
+ [[`& > :has(${POINTED}) > [data-list-divider]`, `& > :has(+ * ${POINTED}) > [data-list-divider]`].join(', ')]: HIDDEN,
} as const;
/** Hairline between two rows; decorative, so hidden from assistive tech. */
diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx
index 6fff19217c..88ab00bd3a 100644
--- a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx
@@ -66,6 +66,7 @@ export interface ListItemProps {
onIntent?: () => void;
/** Renders the leading checkbox. */
onCheckedChange?: (checked: boolean) => void;
+ /** Without onPress, activating the primary button also opens this menu. */
onContextMenu?: (anchor: ListContextMenuAnchor) => void;
}
@@ -109,20 +110,14 @@ export const ListItem = ({
// Inside a List every row is a keyboard stop; a standalone row is a button only when pressing it does something.
const isInteractive = onPress !== undefined || onContextMenu !== undefined || itemKey !== undefined;
- const handleContextMenu = useCallback(
- (event: MouseEvent<HTMLDivElement>) => {
- // A nested control (e.g. a field in `detail`) that opened its own menu already claimed the gesture.
- if (!onContextMenu || event.defaultPrevented) {
+ const openContextMenu = useCallback(
+ (row: HTMLElement, point?: { x: number; y: number }) => {
+ if (!onContextMenu) {
return;
}
- event.preventDefault();
- const row = event.currentTarget;
const viewport = row.closest<HTMLElement>('[data-list-viewport]');
const key = row.getAttribute('data-list-row');
- // Firefox reports keyboard-invoked menus at (0,0); Chromium reports a point on the element, which the pointer
- // branch anchors just as well.
- const fromKeyboard = event.clientX === 0 && event.clientY === 0;
const rect = row.getBoundingClientRect();
const focusTarget = (): HTMLElement | null => {
if (row.isConnected) {
@@ -144,23 +139,42 @@ export const ListItem = ({
onContextMenu({
focusTarget,
restoreFocus: () => focusTarget()?.focus(),
- x: fromKeyboard ? rect.left + 8 : event.clientX,
- y: fromKeyboard ? rect.bottom : event.clientY,
+ x: point?.x ?? rect.left + 8,
+ y: point?.y ?? rect.bottom,
});
},
[onContextMenu]
);
+ const handleContextMenu = useCallback(
+ (event: MouseEvent<HTMLDivElement>) => {
+ // A nested field's menu takes precedence. Keyboard-invoked menus can report (0,0).
+ if (event.defaultPrevented) {
+ return;
+ }
+ event.preventDefault();
+ openContextMenu(
+ event.currentTarget,
+ event.clientX === 0 && event.clientY === 0 ? undefined : { x: event.clientX, y: event.clientY }
+ );
+ },
+ [openContextMenu]
+ );
const handleCheckedChange = useCallback(
(details: { checked: boolean | 'indeterminate' }) => onCheckedChange?.(details.checked === true),
[onCheckedChange]
);
const handlePress = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
- if (!isBusy) {
- onPress?.(event);
+ if (isBusy) {
+ return;
+ }
+ if (onPress) {
+ onPress(event);
+ } else if (event.currentTarget.parentElement) {
+ openContextMenu(event.currentTarget.parentElement);
}
},
- [isBusy, onPress]
+ [isBusy, onPress, openContextMenu]
);
// Plain text keeps to its line; a node (badge row, figures) lays itself out.
const descriptionCss = useMemo(
@@ -200,7 +214,9 @@ export const ListItem = ({
css={styles.root}
data-busy={isBusy || undefined}
data-list-row={itemKey}
+ data-list-surface=""
data-menu-open={isMenuOpen || undefined}
+ data-static={!isInteractive || undefined}
role={role}
onContextMenu={onContextMenu ? handleContextMenu : undefined}
>
@@ -223,7 +239,8 @@ export const ListItem = ({
<chakra.button
aria-current={isActive || undefined}
aria-disabled={isBusy || undefined}
- aria-expanded={isExpanded}
+ aria-expanded={onContextMenu && !onPress ? isMenuOpen : isExpanded}
+ aria-haspopup={onContextMenu && !onPress ? 'menu' : undefined}
css={styles.primary}
data-list-primary=""
tabIndex={tabIndex}
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
index 43866f910a..41aa57a830 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
@@ -886,7 +886,7 @@ const rowFocusRing = {
} as const;
/** Hover, extended to a row whose context menu is open so the row it acts on stays marked. */
-const ROW_POINTED = '&:is(:hover, [data-hover], [data-menu-open]):not(:disabled, [data-disabled])';
+const ROW_POINTED = '&:is(:hover, [data-hover], [data-menu-open]):not(:disabled, [data-disabled], [data-static])';
/** One row surface for every list-like control; `Row` and `ListItem` both build on it. */
const rowSurface = {
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
index 057789a84b..8320cd88d9 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
@@ -22,6 +22,8 @@ export interface ImageMapPoint {
export interface ImageMapPoints {
points: ImageMapPoint[];
state: ImageMapState;
+ /** Encoder fingerprint; cached labels belong only to this model. */
+ modelId: string | null;
/** The accessible image set changed since this projection was computed; a refresh is pending. */
stale: boolean;
pointCount: number;
@@ -47,6 +49,7 @@ interface BackendImageMapPoint {
interface BackendImageMapPointsResponse {
points: BackendImageMapPoint[];
state: ImageMapState;
+ model_id?: string | null;
stale: boolean;
point_count: number;
model_name?: string | null;
@@ -60,6 +63,7 @@ const INCLUDE_VIDEOS_PARAM = { include_videos: 'true' } as const;
const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({
clusterEps: body.cluster_eps ?? null,
+ modelId: body.model_id ?? null,
modelName: body.model_name ?? null,
pointCount: body.point_count,
points: body.points.map((point) => {
@@ -98,32 +102,35 @@ export const fetchImageMapPoints = async (options?: { eps?: number; minSamples?:
export interface ImageMapStatus {
/** Embedding-index counts, or null: the backend omits them for non-admins. */
index: ImageIndexCounts | null;
+ state: ImageMapState;
+ modelId: string | null;
+ modelName: string | null;
}
interface BackendImageMapStatusResponse {
enabled: boolean;
+ model_id?: string | null;
index?: { total: number; embedded: number; failed?: number } | null;
+ model_name?: string | null;
+ projection: { state: ImageMapState };
}
-/** Read index counts from status; projection details already come from points. */
+/** Read index progress and encoder availability without fetching/clustering the points. */
export const fetchImageMapStatus = async (): Promise<ImageMapStatus> => {
- // Request the same video-inclusive map as other endpoints, including the unused projection portion.
const body = await apiFetchJson<BackendImageMapStatusResponse>(
`/api/v1/image_map/status?${new URLSearchParams(INCLUDE_VIDEOS_PARAM).toString()}`
);
- if (!body.index) {
- return { index: null };
- }
-
- const { embedded, total } = body.index;
- const failed = body.index.failed ?? 0;
+ const { embedded = 0, failed = 0, total = 0 } = body.index ?? {};
return {
// `pending` is a computed property on the backend model and so is absent
// from the serialized response; it is derived the same way here (failures
// are excluded so it can still drain to zero).
- index: { embedded, failed, pending: Math.max(0, total - embedded - failed), total },
+ index: body.index ? { embedded, failed, pending: Math.max(0, total - embedded - failed), total } : null,
+ modelId: body.model_id ?? null,
+ modelName: body.model_name ?? null,
+ state: body.projection.state,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
index cf90d4ffb7..d3a68d7c71 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
@@ -15,6 +15,7 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { clearImageLabels, getImageLabels } from './imageLabelCache';
+import { imageMapStore, refreshImageIndexStatus, refreshImageMapPoints } from './imageMapStore';
describe('image map image-label cache', () => {
beforeEach(() => {
@@ -201,6 +202,112 @@ describe('image map image-label cache', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
});
+ it.each(['points', 'status'] as const)(
+ 'discards cached and in-flight labels when %s reports a missing encoder',
+ async (source) => {
+ const cachedItem = { kind: 'image', name: 'cached.png' } as const;
+ const pendingItem = { kind: 'image', name: 'pending.png' } as const;
+ mocks.apiFetchJson.mockResolvedValueOnce({ alternates: [], label: 'old cached label' });
+ await getImageLabels(cachedItem);
+
+ let resolveOld: (labels: { alternates: string[]; label: string }) => void = () => {};
+ mocks.apiFetchJson.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve;
+ })
+ );
+ const stale = getImageLabels(pendingItem);
+ const missingResponse =
+ source === 'points'
+ ? { model_name: 'encoder', point_count: 0, points: [], stale: false, state: 'model_missing' }
+ : { enabled: false, index: null, model_name: 'encoder', projection: { state: 'model_missing' } };
+ mocks.apiFetchJson.mockResolvedValueOnce(missingResponse);
+
+ if (source === 'points') {
+ await refreshImageMapPoints();
+ } else {
+ refreshImageIndexStatus();
+ await vi.waitFor(() => expect(imageMapStore.getSnapshot().data?.state).toBe('model_missing'));
+ }
+
+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'fresh label' });
+ const fresh = getImageLabels(pendingItem);
+ resolveOld({ alternates: [], label: 'retired label' });
+ await expect(stale).resolves.toBeNull();
+ await expect(fresh).resolves.toEqual({ alternates: [], label: 'fresh label' });
+ await expect(getImageLabels(cachedItem)).resolves.toEqual({ alternates: [], label: 'fresh label' });
+
+ // Progress and repeated missing-state snapshots must not repeatedly clear the cache.
+ imageMapStore.patchSnapshot({ indexUpdatedAt: 1_000 });
+ await expect(getImageLabels(pendingItem)).resolves.toEqual({ alternates: [], label: 'fresh label' });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(5);
+ }
+ );
+
+ it.each(['points', 'status'] as const)(
+ 'invalidates old labels when %s observes a different encoder without a missing state',
+ async (source) => {
+ const response = {
+ model_id: 'encoder-a',
+ point_count: 0,
+ points: [],
+ stale: false,
+ state: 'empty',
+ updated_at: null,
+ };
+ mocks.apiFetchJson.mockResolvedValueOnce(response);
+ await refreshImageMapPoints();
+
+ const cachedItem = { kind: 'image', name: 'cached.png' } as const;
+ const pendingItem = { kind: 'image', name: 'pending.png' } as const;
+ mocks.apiFetchJson.mockResolvedValueOnce({ alternates: [], label: 'encoder A label' });
+ await getImageLabels(cachedItem);
+ let resolveOld: (value: { alternates: string[]; label: string }) => void = () => {};
+ mocks.apiFetchJson.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve;
+ })
+ );
+ const stale = getImageLabels(pendingItem);
+
+ // Removal and reinstallation happened while the map was closed. Neither
+ // endpoint needs to return model_missing for the cached labels to be stale.
+ const replacement = { ...response, model_id: 'encoder-b' };
+ const labelRequest = vi.fn().mockResolvedValue({ alternates: [], label: 'encoder B label' });
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/status')) {
+ return Promise.resolve({ enabled: true, model_id: 'encoder-b', projection: { state: 'empty' } });
+ }
+ if (url.startsWith('/api/v1/image_map/points')) {
+ return Promise.resolve(replacement);
+ }
+ return labelRequest();
+ });
+ if (source === 'points') {
+ await refreshImageMapPoints();
+ } else {
+ refreshImageIndexStatus();
+ await vi.waitFor(() => {
+ expect(imageMapStore.getSnapshot().data?.modelId).toBe('encoder-b');
+ expect(imageMapStore.getSnapshot().loadState).toBe('loaded');
+ });
+ }
+
+ resolveOld({ alternates: [], label: 'late encoder A label' });
+ await expect(stale).resolves.toBeNull();
+ await expect(getImageLabels(cachedItem)).resolves.toEqual({ alternates: [], label: 'encoder B label' });
+ await expect(getImageLabels(pendingItem)).resolves.toEqual({ alternates: [], label: 'encoder B label' });
+ expect(labelRequest).toHaveBeenCalledTimes(2);
+
+ // Normal progress/projection refreshes from the same encoder keep cached labels.
+ await refreshImageMapPoints();
+ await getImageLabels(cachedItem);
+ expect(labelRequest).toHaveBeenCalledTimes(2);
+ }
+ );
+
it('clears the cooldown on account switch', async () => {
mocks.apiFetchJson.mockRejectedValue(new ApiError('index disabled', 409));
await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
index d2a5ff247a..efddadf82e 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
@@ -11,10 +11,10 @@ import { ApiError } from '@platform/transport/http';
import type { ImageMapImageLabels } from './api';
import { fetchImageMapImageLabels } from './api';
+import { imageMapStore } from './imageMapStore';
/**
- * Caches per-item vocabulary labels, including empty results, until vocabulary rebuild. Embeddings are stable;
- * editable vocabulary determines invalidation.
+ * Caches per-item vocabulary labels, including empty results, until vocabulary rebuild or encoder change.
*/
const labels = new Map<string, ImageMapImageLabels | null>();
const inflight = new Map<string, Promise<ImageMapImageLabels | null>>();
@@ -53,6 +53,23 @@ export const clearImageLabels = (): void => {
unavailableUntil = 0;
};
+// One subscription lives with this lazy, account-fenced cache. The eagerly
+// loaded map read model never needs to import hover-label code to invalidate it.
+let modelMissing = imageMapStore.getSnapshot().data?.state === 'model_missing';
+let modelId = imageMapStore.getSnapshot().data?.modelId ?? null;
+imageMapStore.subscribe(() => {
+ const { data } = imageMapStore.getSnapshot();
+ const missing = data?.state === 'model_missing';
+ const nextModelId = data?.modelId ?? null;
+ // A replacement may become ready while the map is closed or its tab is
+ // suspended, so availability transitions alone cannot retire old labels.
+ if ((missing && !modelMissing) || nextModelId !== modelId) {
+ clearImageLabels();
+ }
+ modelMissing = missing;
+ modelId = nextModelId;
+});
+
export const getImageLabels = (item: GalleryItemRef): Promise<ImageMapImageLabels | null> => {
const key = toGalleryItemKey(item);
// Checked before the cooldown: labels already fetched for this item stay
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
index 1124dad57c..90ea648eb8 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
@@ -1,3 +1,4 @@
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
@@ -23,7 +24,9 @@ import type { ImageMapPoint, ImageMapPoints } from './api';
import { fetchImageMapPoints, fetchImageMapStatus, requestImageMapRefresh } from './api';
import { CLUSTER_PALETTE, getClusterColor, NOISE_COLOR } from './clusterPalette';
+import { getImageLabels } from './imageLabelCache';
import {
+ attachImageMapStatusPolling,
ensureImageMapLoaded,
imageMapStore,
recordImageIndexStatus,
@@ -890,6 +893,7 @@ const EMPTY_SNAPSHOT = {
const LOADED_POINTS: ImageMapPoints = {
clusterEps: null,
+ modelId: null,
modelName: null,
pointCount: 0,
points: [],
@@ -905,7 +909,11 @@ describe('image map status', () => {
});
it('derives the pending count the backend computes but does not serialize', async () => {
- mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 30, failed: 2, total: 100 } });
+ mocks.apiFetchJson.mockResolvedValue({
+ enabled: true,
+ projection: { state: 'ready' },
+ index: { embedded: 30, failed: 2, total: 100 },
+ });
const status = await fetchImageMapStatus();
@@ -918,7 +926,7 @@ describe('image map status', () => {
});
it('has no counts for a non-admin, who is not told the aggregate totals', async () => {
- mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: null });
+ mocks.apiFetchJson.mockResolvedValue({ enabled: true, projection: { state: 'ready' }, index: null });
expect((await fetchImageMapStatus()).index).toBeNull();
});
@@ -927,9 +935,162 @@ describe('image map status', () => {
describe('image index progress', () => {
beforeEach(() => {
mocks.apiFetchJson.mockReset();
+ accountLifecycle.invalidate();
imageMapStore.setSnapshot({ ...EMPTY_SNAPSHOT });
});
+ it('polls only for the mounted view lifetime, without overlapping requests or surviving account changes', async () => {
+ vi.useFakeTimers();
+ try {
+ let resolveStatus: (value: unknown) => void = () => {};
+ mocks.apiFetchJson.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveStatus = resolve;
+ })
+ );
+ const detach = attachImageMapStatusPolling();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ resolveStatus({ enabled: true, index: null, projection: { state: 'computing' } });
+ await vi.advanceTimersByTimeAsync(0);
+ detach();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+
+ const detachNext = attachImageMapStatusPolling();
+ accountLifecycle.activate('next-account');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ detachNext();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('replaces stalled progress with the missing encoder reported by a status poll, including for non-admins', async () => {
+ const item = { kind: 'image', name: 'before-removal.png' } as const;
+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'old encoder label', score: 0.7 });
+ expect((await getImageLabels(item))?.label).toBe('old encoder label');
+ imageMapStore.patchSnapshot({ data: LOADED_POINTS, loadState: 'loaded' });
+ recordImageIndexStatus({ embedded: 40, failed: 0, pending: 60, total: 100 }, 1_000);
+ mocks.apiFetchJson.mockResolvedValue({
+ enabled: false,
+ index: null,
+ model_name: 'removed-encoder',
+ projection: { point_count: 0, stale: false, state: 'model_missing' },
+ });
+
+ refreshImageIndexStatus();
+ await drainMacrotask();
+
+ expect(imageMapStore.getSnapshot().data).toMatchObject({ modelName: 'removed-encoder', state: 'model_missing' });
+ expect(imageMapStore.getSnapshot().indexCounts).toBeNull();
+ expect(imageMapStore.getSnapshot().indexUpdatedAt).toBeNull();
+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'reinstalled encoder label', score: 0.8 });
+ expect((await getImageLabels(item))?.label).toBe('reinstalled encoder label');
+ });
+
+ it('keeps a missing-model diagnosis when an older points request completes', async () => {
+ let resolvePoints: (value: unknown) => void = () => {};
+ mocks.apiFetchJson.mockImplementation((url: string) =>
+ url.startsWith('/api/v1/image_map/status')
+ ? Promise.resolve({
+ enabled: false,
+ index: null,
+ model_name: 'removed-encoder',
+ projection: { state: 'model_missing' },
+ })
+ : new Promise((resolve) => {
+ resolvePoints = resolve;
+ })
+ );
+ const points = refreshImageMapPoints();
+ refreshImageIndexStatus();
+ await drainMacrotask();
+ resolvePoints(BACKEND_RESPONSE);
+ await points;
+
+ expect(imageMapStore.getSnapshot().data?.state).toBe('model_missing');
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+ });
+
+ it('reloads points when status discovers the encoder reinstalled', async () => {
+ imageMapStore.patchSnapshot({
+ data: { ...LOADED_POINTS, modelName: 'encoder', state: 'model_missing' },
+ loadState: 'loaded',
+ });
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/status')) {
+ return Promise.resolve({ enabled: true, projection: { state: 'ready' }, index: null });
+ }
+ return Promise.resolve(
+ url.startsWith('/api/v1/image_map/cluster_labels') ? FOREIGN_LABELS_RESPONSE : BACKEND_RESPONSE
+ );
+ });
+
+ refreshImageIndexStatus();
+ await drainMacrotask();
+
+ expect(imageMapStore.getSnapshot().data?.state).toBe('ready');
+ expect(imageMapStore.getSnapshot().data?.pointCount).toBe(3);
+ });
+
+ it('discards old in-flight points when status discovers a replacement encoder', async () => {
+ imageMapStore.patchSnapshot({ data: { ...LOADED_POINTS, modelId: 'encoder-a' }, loadState: 'loaded' });
+ let resolveOldPoints: (value: unknown) => void = () => {};
+ mocks.apiFetchJson.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOldPoints = resolve;
+ })
+ );
+ const oldPoints = refreshImageMapPoints();
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/status')) {
+ return Promise.resolve({ enabled: true, model_id: 'encoder-b', projection: { state: 'ready' } });
+ }
+ return Promise.resolve(
+ url.startsWith('/api/v1/image_map/cluster_labels')
+ ? FOREIGN_LABELS_RESPONSE
+ : { ...BACKEND_RESPONSE, model_id: 'encoder-b' }
+ );
+ });
+
+ refreshImageIndexStatus();
+ await drainMacrotask();
+ expect(imageMapStore.getSnapshot().data).toMatchObject({ modelId: 'encoder-b', points: [] });
+ resolveOldPoints({ ...BACKEND_RESPONSE, model_id: 'encoder-a' });
+ await oldPoints;
+ await drainMacrotask();
+
+ expect(imageMapStore.getSnapshot().data).toMatchObject({ modelId: 'encoder-b', pointCount: 3, state: 'ready' });
+ });
+
+ it('ignores an old account status response without clearing its newer request', async () => {
+ const resolvers: Array<(value: unknown) => void> = [];
+ mocks.apiFetchJson.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolvers.push(resolve);
+ })
+ );
+ accountLifecycle.activate('first');
+ refreshImageIndexStatus();
+ accountLifecycle.activate('second');
+ refreshImageIndexStatus();
+ resolvers[0]?.({ enabled: false, index: null, model_name: 'foreign', projection: { state: 'model_missing' } });
+ await drainMacrotask();
+ refreshImageIndexStatus();
+ expect(resolvers).toHaveLength(2);
+ expect(imageMapStore.getSnapshot().data).toBeNull();
+ resolvers[1]?.({ enabled: false, index: null, model_name: 'current', projection: { state: 'model_missing' } });
+ await drainMacrotask();
+ expect(imageMapStore.getSnapshot().data?.modelName).toBe('current');
+ });
+
it('stamps when the index last moved so the UI can say how long it has stood still', () => {
recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 4_000);
@@ -958,7 +1119,11 @@ describe('image index progress', () => {
// worker is parked behind a generation would otherwise show no progress.
mocks.apiFetchJson.mockImplementation((url: string) => {
if (url.startsWith('/api/v1/image_map/status')) {
- return Promise.resolve({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ return Promise.resolve({
+ enabled: true,
+ projection: { state: 'ready' },
+ index: { embedded: 40, failed: 0, total: 100 },
+ });
}
return url.startsWith('/api/v1/image_map/cluster_labels')
@@ -988,7 +1153,7 @@ describe('image index progress', () => {
ensureImageMapLoaded();
recordImageIndexStatus({ embedded: 90, failed: 0, pending: 10, total: 100 }, 1_000);
- resolveStatus({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ resolveStatus({ enabled: true, projection: { state: 'ready' }, index: { embedded: 40, failed: 0, total: 100 } });
// A macrotask drains everything the resolved seed queued behind it.
await drainMacrotask();
@@ -1000,7 +1165,11 @@ describe('image index progress', () => {
// Reopening mid-backfill must fetch counts even if the worker is paused and no event is due.
mocks.apiFetchJson.mockImplementation((url: string) =>
url.startsWith('/api/v1/image_map/status')
- ? Promise.resolve({ enabled: true, index: { embedded: 70, failed: 0, total: 100 } })
+ ? Promise.resolve({
+ enabled: true,
+ projection: { state: 'ready' },
+ index: { embedded: 70, failed: 0, total: 100 },
+ })
: Promise.resolve(BACKEND_RESPONSE)
);
@@ -1036,7 +1205,11 @@ describe('image index progress', () => {
// without this the progress UI claims a finished backfill is still running
// until the page is reloaded.
recordImageIndexStatus({ embedded: 40, failed: 0, pending: 60, total: 100 }, 1_000);
- mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 100, failed: 0, total: 100 } });
+ mocks.apiFetchJson.mockResolvedValue({
+ enabled: true,
+ projection: { state: 'ready' },
+ index: { embedded: 100, failed: 0, total: 100 },
+ });
refreshImageIndexStatus();
@@ -1047,7 +1220,11 @@ describe('image index progress', () => {
// Otherwise pressing "Check again" — the one thing a user watching a
// frozen bar will do — pushes the note out by another interval, forever.
recordImageIndexStatus({ embedded: 40, failed: 0, pending: 60, total: 100 }, 1_000);
- mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ mocks.apiFetchJson.mockResolvedValue({
+ enabled: true,
+ projection: { state: 'ready' },
+ index: { embedded: 40, failed: 0, total: 100 },
+ });
refreshImageIndexStatus();
@@ -1073,12 +1250,12 @@ describe('image index progress', () => {
expect(resolvers).toHaveLength(1);
- resolvers[0]?.({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ resolvers[0]?.({ enabled: true, projection: { state: 'ready' }, index: { embedded: 40, failed: 0, total: 100 } });
await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts).not.toBeNull());
refreshImageIndexStatus();
expect(resolvers).toHaveLength(2);
- resolvers[1]?.({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ resolvers[1]?.({ enabled: true, projection: { state: 'ready' }, index: { embedded: 40, failed: 0, total: 100 } });
await drainMacrotask();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index 999dc80fa3..a6dd3dc385 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -64,6 +64,9 @@ let statusInflight: Promise<void> | null = null;
// Bumped by every socket-delivered status report, so a status fetch that
// started earlier can tell whether one landed while it was in flight.
let indexEventSequence = 0;
+// Status and points can discover model changes concurrently. Only a response
+// that began against the current read model may replace its availability.
+let mapRevision = 0;
// The projection is per-user server state: a login/logout must drop it before
// the next account's widgets can observe it.
@@ -79,6 +82,7 @@ registerAccountOwnedResource({
labelsSequence += 1;
statusInflight = null;
indexEventSequence += 1;
+ mapRevision += 1;
imageMapStore.setSnapshot(EMPTY_IMAGE_MAP_SNAPSHOT);
},
name: 'image-map',
@@ -123,20 +127,22 @@ export const refreshImageMapPoints = (): Promise<void> => {
}
const owner = captureAccountScope();
+ const revision = mapRevision;
imageMapStore.patchSnapshot({ loadState: 'loading' });
const refresh = fetchImageMapPoints(clusterEps !== null ? { eps: clusterEps } : undefined)
.then((data) => {
- if (!isAccountScopeCurrent(owner)) {
+ if (!isAccountScopeCurrent(owner) || revision !== mapRevision) {
return;
}
+ mapRevision += 1;
// Clear renderError on retry so fresh points receive a new WebGL draw attempt.
imageMapStore.patchSnapshot({ data, error: null, loadState: 'loaded', renderError: null });
refreshClusterLabels(data);
})
.catch((error: unknown) => {
- if (!isAccountScopeCurrent(owner)) {
+ if (!isAccountScopeCurrent(owner) || revision !== mapRevision) {
return;
}
@@ -152,7 +158,7 @@ export const refreshImageMapPoints = (): Promise<void> => {
inflight = null;
}
- if (rerunRequested) {
+ if (isAccountScopeCurrent(owner) && rerunRequested) {
rerunRequested = false;
void refreshImageMapPoints();
}
@@ -348,16 +354,56 @@ export const refreshImageIndexStatus = (): void => {
// Events that land while this is in flight are strictly newer than what it
// will return, and must not be rewound by it.
const sequence = indexEventSequence;
+ const revision = mapRevision;
const request: Promise<void> = fetchImageMapStatus()
.then((status) => {
- // Non-admins get no counts at all — the totals aggregate every user's
- // images — so `index` is null for them and there is nothing to record.
- if (status.index === null || !isAccountScopeCurrent(owner) || sequence !== indexEventSequence) {
+ if (!isAccountScopeCurrent(owner)) {
return;
}
- recordImageIndexStatus(status.index, Date.now(), { measure: false });
+ if (revision === mapRevision) {
+ const { data } = imageMapStore.getSnapshot();
+ const missing = status.state === 'model_missing';
+ const replaced = data !== null && status.modelId !== null && data.modelId !== status.modelId;
+ const recovered = data?.state === 'model_missing' && status.state !== 'disabled';
+
+ if (missing || replaced || recovered) {
+ mapRevision += 1;
+ labelsSequence += 1;
+ imageMapStore.patchSnapshot({
+ clusterLabels: null,
+ clusterLabelsEps: null,
+ clusterLabelsHash: null,
+ data: {
+ clusterEps: null,
+ modelId: status.modelId,
+ modelName: status.modelName,
+ pointCount: 0,
+ points: [],
+ stale: false,
+ state: missing ? 'model_missing' : 'computing',
+ updatedAt: null,
+ visibleHash: null,
+ },
+ error: null,
+ indexCounts: null,
+ indexUpdatedAt: null,
+ loadState: 'loaded',
+ renderError: null,
+ });
+ if (missing) {
+ return;
+ }
+ void refreshImageMapPoints();
+ }
+ }
+
+ // Counts aggregate every account and are omitted for non-admins. Newer
+ // socket counts fence this part of the response, not its model diagnosis.
+ if (status.index !== null && sequence === indexEventSequence) {
+ recordImageIndexStatus(status.index, Date.now(), { measure: false });
+ }
})
.catch(() => {
// Progress failure is optional detail; point loading reports its own errors.
@@ -386,3 +432,17 @@ export const ensureImageMapLoaded = (): void => {
// rewinds.
refreshImageIndexStatus();
};
+
+/** Poll only while a map view is mounted; missing encoders produce no index events. */
+export const attachImageMapStatusPolling = (): (() => void) => {
+ const owner = captureAccountScope();
+ const timer = setInterval(refreshImageIndexStatus, 5_000);
+ const dispose = () => {
+ clearInterval(timer);
+ owner.signal.removeEventListener('abort', dispose);
+ };
+
+ owner.signal.addEventListener('abort', dispose, { once: true });
+
+ return dispose;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts
index 3184370c08..aae796167c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as ImageMapStoreModule from './imageMapStore';
+
const mocks = vi.hoisted(() => ({
apiFetchJson: vi.fn(),
refetchClusterLabels: vi.fn(),
@@ -9,7 +11,8 @@ vi.mock('@platform/transport/http', () => ({
apiFetchJson: mocks.apiFetchJson,
}));
-vi.mock('./imageMapStore', () => ({
+vi.mock('./imageMapStore', async (importOriginal) => ({
+ ...(await importOriginal<typeof ImageMapStoreModule>()),
refetchClusterLabels: mocks.refetchClusterLabels,
}));
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
index c4d433fcdb..0f23598ee4 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
@@ -64,7 +64,7 @@ const createDispatch = () => {
open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),
patchInstanceValues: (instanceId, values, projectId) =>
dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),
- patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),
+ patchValues: vi.fn(),
reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),
revealFloating: (instanceId) => dispatch({ instanceId, type: 'revealFloatingWidget' }),
select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),
diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
index 90e7db8093..f7f5fe1654 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
@@ -2,7 +2,7 @@ import type { WidgetRegion } from '@workbench/layoutContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import type { NormalizedWidgetManifest, RegisteredWidget } from '@workbench/widgetContracts';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import type { WorkbenchAction } from './workbenchState.testing';
import type { WorkbenchWidgetCommands } from './workbenchStore';
@@ -78,7 +78,7 @@ const createWidgetCommands = (dispatch: (action: WorkbenchAction) => void): Work
open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),
patchInstanceValues: (instanceId, values, projectId) =>
dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),
- patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),
+ patchValues: vi.fn(),
reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),
revealFloating: (instanceId) => dispatch({ instanceId, type: 'revealFloatingWidget' }),
select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx
index f9ff818147..f90837defc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx
@@ -108,6 +108,7 @@ const render = async (resolved: number | null) => {
clusterLabelsHash: null,
data: {
clusterEps: resolved,
+ modelId: null,
modelName: null,
pointCount: 1,
points: [],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
index a8dc12abe1..67c5a949cf 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
@@ -36,6 +36,7 @@ const renderFooter = async (clusters: number[], width?: string, crowded = false)
clusterLabelsHash: null,
data: {
clusterEps: 0.2,
+ modelId: null,
modelName: null,
pointCount: clusters.length,
points: points(...clusters),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
index 5cf2faab91..14ee12aa1f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
@@ -1,4 +1,5 @@
import type { ImageMapState } from '@workbench/image-map/api';
+import type * as ImageMapStoreModule from '@workbench/image-map/imageMapStore';
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { ChakraProvider } from '@chakra-ui/react';
@@ -6,6 +7,7 @@ import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
// Stand-ins for the gallery's values and the workbench commands the chip and Esc write through.
const workbench = vi.hoisted(() => ({
@@ -13,6 +15,13 @@ const workbench = vi.hoisted(() => ({
patchValues: vi.fn(),
}));
+const recovery = vi.hoisted(() => ({ status: vi.fn(), points: vi.fn() }));
+vi.mock('@workbench/image-map/api', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ fetchImageMapStatus: recovery.status,
+ fetchImageMapPoints: recovery.points,
+}));
+
vi.mock('@workbench/WorkbenchContext', () => ({
// The gallery's values drive the cluster chip and the Esc clear. Every other widget's selector is applied to an
// empty value bag rather than answering `false`: each accessor owns its own default, and handing a boolean to a
@@ -151,6 +160,7 @@ const dataFor = (
modelName = 'clip-vit-large-patch14'
) => ({
clusterEps: null,
+ modelId: null,
modelName: state === 'model_missing' ? modelName : null,
pointCount: 0,
points: [],
@@ -218,8 +228,7 @@ describe('Image Map unavailable states', () => {
'model_missing',
'Embedding model not installed',
'To enable image indexing, install the image encoder model',
- // A standing action: nothing polls while the indexer is inert, so the
- // message has to offer its own way to ask the server again.
+ // A standing action also lets a user retry immediately after installing.
['Check again'],
],
[
@@ -250,6 +259,51 @@ describe('Image Map unavailable states', () => {
});
describe('Image Map missing-model link', () => {
+ it('replaces stalled indexing with the install link on a status poll and recovers after reinstall', async () => {
+ const actual = await vi.importActual<typeof ImageMapStoreModule>('@workbench/image-map/imageMapStore');
+ await renderState('disabled');
+ await act(() => {
+ imageMapStore.patchSnapshot({
+ data: { ...dataFor('disabled'), state: 'computing' },
+ indexCounts: { embedded: 4, failed: 0, pending: 6, total: 10 },
+ indexUpdatedAt: Date.now() - 120_000,
+ });
+ });
+ expect(host?.textContent).toContain('Indexing gallery');
+ recovery.status.mockResolvedValue({
+ index: null,
+ modelId: null,
+ modelName: 'DFN2B-CLIP-ViT-L-14-39B',
+ state: 'model_missing',
+ });
+ await act(async () => {
+ actual.refreshImageIndexStatus();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ });
+ expect(host?.textContent).toContain('Embedding model not installed');
+ expect(host?.querySelector('[role="progressbar"]')).toBeNull();
+ const link = host?.querySelector('button');
+ expect(link?.textContent).toBe('DFN2B-CLIP-ViT-L-14-39B');
+ await act(() => link?.click());
+ expect(models.openAddModelsSearch).toHaveBeenCalledWith('DFN2B-CLIP-ViT-L-14-39B');
+ await page.screenshot({ path: '../../../../artifacts/image-map/model-removed.png' });
+
+ actual.setClusterLabelsEnabled(false);
+ recovery.status.mockResolvedValue({ index: null, modelId: null, modelName: null, state: 'empty' });
+ recovery.points.mockResolvedValue({ ...dataFor('disabled'), state: 'empty' });
+ await act(async () => {
+ actual.refreshImageIndexStatus();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ });
+ expect(host?.textContent).toContain('Nothing to map yet');
+ expect(host?.textContent).not.toContain('Embedding model not installed');
+ actual.setClusterLabelsEnabled(true);
+ });
+
it('opens Add Models on the configured encoder instead of downloading it', async () => {
await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
@@ -344,6 +398,7 @@ describe('Image Map indexing activity', () => {
clusterLabelsHash: null,
data: {
clusterEps: null,
+ modelId: null,
modelName: null,
pointCount: 2,
points: [
@@ -430,6 +485,7 @@ describe('Image Map cluster selection chip', () => {
clusterLabelsHash: null,
data: {
clusterEps: null,
+ modelId: null,
modelName: null,
pointCount: POINTS.length,
points: POINTS,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 395cedd261..2f5b232d67 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -17,6 +17,7 @@ import {
getImageMapShowClusterLabels,
} from '@workbench/image-map/imageMapSettings';
import {
+ attachImageMapStatusPolling,
ensureImageMapLoaded,
imageMapStore,
refreshImageIndexStatus,
@@ -103,9 +104,11 @@ export const ImageMapWidgetView = ({ runtime }: WidgetViewProps) => {
setClusterEps(clusterEps);
}, [clusterEps]);
- useEffect(() => {
+ useMountEffect(() => {
ensureImageMapLoaded();
- }, []);
+
+ return attachImageMapStatusPolling();
+ });
// Pushed into the store so turning labels off stops the request, not just the
// drawing of what it returns.
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index 20392e86d2..ec456fe71d 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -706,6 +706,45 @@ describe('createWorkbenchStore', () => {
expect(listener).not.toHaveBeenCalled();
});
+ it('composes same-turn functional widget patches from the latest values', () => {
+ const store = createWorkbenchStore();
+ store.commands.widgets.patchValues('upscale', { weights: { first: 0.75, second: 0.5 }, steps: 30 });
+
+ store.commands.widgets.patchValues('upscale', (current) => ({
+ weights: { ...(current.weights as Record<string, number>), first: 0.8 },
+ }));
+ store.commands.widgets.patchValues('upscale', (current) => ({
+ weights: { ...(current.weights as Record<string, number>), second: 0.55 },
+ }));
+
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, 'upscale')).toMatchObject({
+ steps: 30,
+ weights: { first: 0.8, second: 0.55 },
+ });
+ });
+
+ it('reads and writes the fenced project after a switch and skips a closed project', () => {
+ const store = createWorkbenchStore();
+ const firstProjectId = store.getSnapshot().activeProject.id;
+ store.commands.widgets.patchValues('video', { steps: 12 });
+ const lateUpdate = () =>
+ store.commands.widgets.patchValues('video', (current) => ({ steps: Number(current.steps) + 1 }), firstProjectId);
+
+ store.commands.projects.create();
+ store.commands.widgets.patchValues('video', { steps: 50 });
+ lateUpdate();
+
+ const firstProject = store.getSnapshot().projects.find((project) => project.id === firstProjectId)!;
+ expect(getProjectWidgetValues(firstProject, 'video').steps).toBe(13);
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, 'video').steps).toBe(50);
+
+ store.commands.projects.close(firstProjectId);
+ const update = vi.fn(() => ({ steps: 99 }));
+ store.commands.widgets.patchValues('video', update, firstProjectId);
+ expect(update).not.toHaveBeenCalled();
+ expect(getProjectWidgetValues(store.getSnapshot().activeProject, 'video').steps).toBe(50);
+ });
+
it('does not notify subscribers for equivalent queue status writes', () => {
const store = createWorkbenchStore();
const project = store.getSnapshot().activeProject;
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index 74d4636b05..32c54e2874 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -23,6 +23,7 @@ import { getLayoutWidgetTypeIds } from './layoutWidgetSet';
import { createBlankWorkflowDocument, findProjectWorkflow } from './projectWorkflows';
import { getWorkbenchPreferences } from './settings/store';
import { areWidgetsLoaded } from './widgetRegistry';
+import { getProjectWidgetValues } from './widgetState';
import {
createInitialWorkbenchState,
__workbenchReducerInternal,
@@ -445,20 +446,28 @@ const createCommands = (
values,
})
),
- patchValues: command(
- 'patchWidgetValues',
- (
- widgetId: ActionPayload<'patchWidgetValues'>['widgetId'],
- values: Record<string, unknown>,
- projectId?: string,
- origin?: ActionPayload<'patchWidgetValues'>['origin']
- ) => ({
+ patchValues: (
+ widgetId: ActionPayload<'patchWidgetValues'>['widgetId'],
+ values: Record<string, unknown> | ((current: Record<string, unknown>) => Record<string, unknown>),
+ projectId?: string,
+ origin?: ActionPayload<'patchWidgetValues'>['origin']
+ ): void => {
+ const state = getState();
+ const project = state.projects.find((candidate) => candidate.id === (projectId ?? state.activeProjectId));
+
+ if (!project) {
+ return;
+ }
+
+ // Resolve before dispatch so same-turn draft commits compose, without storing callbacks in reducer actions.
+ dispatch({
origin,
- projectId,
- values,
+ projectId: project.id,
+ type: 'patchWidgetValues',
+ values: typeof values === 'function' ? values(getProjectWidgetValues(project, widgetId)) : values,
widgetId,
- })
- ),
+ });
+ },
reorder: command('reorderWidgetInstances'),
revealFloating: command('revealFloatingWidget', (instanceId: string) => ({ instanceId })),
setAlignment: command('setWidgetInstanceAlignment'),
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index 4af3b92ae6..03937eaf1a 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -382,6 +382,7 @@ def test_points_computing_and_enqueues_when_cache_missing(
body = response.json()
assert body["state"] == "computing"
+ assert body["model_id"] == MODEL_ID
assert body["stale"] is True
# System user is admin in single-user mode -> all_images scope.
assert image_index_service.projection_requests == [(SYSTEM_USER_ID, True)]
@@ -515,6 +516,47 @@ def test_points_serve_the_index_once_it_is_activated(
assert client.get("/api/v1/image_map/status").json()["enabled"] is True
[email protected]("endpoint", ["points", "status"])
+def test_reads_revalidate_an_encoder_deleted_after_activation(
+ endpoint: str, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ mock_invoker.services.configuration.image_index_enabled = True
+
+ def revalidate() -> bool:
+ image_index_service._model_id = None
+ return False
+
+ image_index_service.try_activate = revalidate # type: ignore[method-assign]
+ body = client.get(f"/api/v1/image_map/{endpoint}").json()
+ projection = body["projection"] if endpoint == "status" else body
+ assert projection["state"] == "model_missing"
+ assert body["model_id"] is None
+ assert body["model_name"] == mock_invoker.services.configuration.image_index_model
+ if endpoint == "status":
+ assert body["enabled"] is False
+ assert body["index"] is None
+
+
[email protected]("endpoint", ["points", "status"])
+def test_encoder_fingerprint_changes_without_a_missing_model_response(
+ endpoint: str, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _seed_embedded_image(mock_invoker, "a.png")
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))
+ before = client.get(f"/api/v1/image_map/{endpoint}").json()
+ assert before["model_id"] == MODEL_ID
+ assert (before["projection"] if endpoint == "status" else before)["point_count"] == 1
+
+ # The browser can miss the whole removal/reinstall while closed or suspended.
+ # The new encoder must identify itself before it has any projected points.
+ image_index_service._model_id = "replacement-model-hash"
+ after = client.get(f"/api/v1/image_map/{endpoint}").json()
+ assert after["model_id"] == "replacement-model-hash"
+ projection = after["projection"] if endpoint == "status" else after
+ assert projection["state"] == "empty"
+ assert projection["point_count"] == 0
+
+
def test_status_disabled(mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient) -> None:
image_index_service._model_id = None
mock_invoker.services.configuration.image_index_enabled = False
@@ -524,6 +566,19 @@ def test_status_disabled(mock_invoker: Invoker, image_index_service: FakeImageIn
assert body["projection"]["state"] == "disabled"
+def test_search_refuses_a_model_replaced_after_query_embedding(
+ image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ def embed_then_replace(text: str) -> np.ndarray:
+ image_index_service._model_id = "replacement-model"
+ return np.ones(DIM, dtype=np.float32)
+
+ image_index_service.embed_text = embed_then_replace # type: ignore[method-assign]
+ response = client.get("/api/v1/image_map/search", params={"q": "a cat"})
+ assert response.status_code == 409
+ assert image_index_service.search_calls == []
+
+
def test_eps_validation(client: TestClient) -> None:
assert client.get("/api/v1/image_map/points", params={"eps": 0}).status_code == 422
assert client.get("/api/v1/image_map/points", params={"eps": 99}).status_code == 422
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index 3126bc7757..e381bb878c 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -30,10 +30,14 @@ from invokeai.app.services.image_records.image_records_common import ImageCatego
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
from invokeai.app.services.images.images_common import image_record_to_dto
from invokeai.app.services.images.images_default import ImageService
+from invokeai.app.services.model_records.model_records_sql import ModelRecordServiceSQL
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStorage
from invokeai.app.services.videos.videos_common import VideoDTO, video_record_to_dto
from invokeai.app.services.videos.videos_default import VideoService
+from invokeai.backend.model_manager.configs.clip_vision import CLIPVision_Diffusers_Config
+from invokeai.backend.model_manager.configs.siglip import SigLIP_Diffusers_Config
+from invokeai.backend.model_manager.taxonomy import ModelRepoVariant, ModelSourceType
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
from tests.fixtures.sqlite_database import create_mock_sqlite_database
@@ -101,6 +105,21 @@ def index_records(db: SqliteDatabase) -> ImageIndexRecordsSqlite:
return ImageIndexRecordsSqlite(db=db)
[email protected](params=[CLIPVision_Diffusers_Config, SigLIP_Diffusers_Config], ids=["clip", "siglip"])
+def encoder_config(
+ request: pytest.FixtureRequest, tmp_path: Path
+) -> CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config:
+ return request.param(
+ key="encoder-key",
+ hash=MODEL_ID,
+ path=str(tmp_path / "encoder"),
+ file_size=1,
+ name="encoder",
+ source=str(tmp_path / "encoder"),
+ source_type=ModelSourceType.Path,
+ )
+
+
@pytest.fixture
def images_service() -> ImageService:
images = ImageService()
@@ -464,14 +483,13 @@ def test_model_not_installed_message_flags_same_name_wrong_type() -> None:
def test_try_activate_picks_up_a_model_installed_after_startup(
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
images_service: ImageService,
index_records: ImageIndexRecordsSqlite,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# The encoder is usually installed from the image map itself, long after
# the server came up; that must not need a restart.
- from invokeai.backend.model_manager.taxonomy import ModelType
-
installed: list[object] = []
resolutions = 0
@@ -497,15 +515,18 @@ def test_try_activate_picks_up_a_model_installed_after_startup(
assert service.try_activate() is False
assert resolutions == 2
- installed.append(SimpleNamespace(hash=MODEL_ID, type=ModelType.CLIPVision, path="/models/encoder"))
+ installed.append(encoder_config)
service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
assert service.try_activate() is True
assert service.model_id == MODEL_ID
_wait_until(lambda: service._worker is not None and service._worker.is_alive())
- # The fast path: no further model-store queries once it is running.
+ # Running and missing states share the same throttled catalog check.
assert service.try_activate() is True
assert resolutions == 3
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is True
+ assert resolutions == 4
finally:
service.stop()
@@ -517,6 +538,7 @@ def test_try_activate_picks_up_a_model_installed_after_startup(
def test_failed_late_activation_rolls_back_rather_than_wedging_the_service(
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
images_service: ImageService,
index_records: ImageIndexRecordsSqlite,
monkeypatch: pytest.MonkeyPatch,
@@ -524,10 +546,7 @@ def test_failed_late_activation_rolls_back_rather_than_wedging_the_service(
# Publishing the model before the worker exists would leave the service
# claiming to run with nothing consuming the queue — and try_activate's
# fast path would answer True forever, so no later request would retry.
- from invokeai.backend.model_manager.taxonomy import ModelType
-
- resolved = SimpleNamespace(hash=MODEL_ID, type=ModelType.CLIPVision, path="/models/encoder")
- monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: resolved)
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: encoder_config)
launches = 0
def launch(self, invoker):
@@ -547,7 +566,7 @@ def test_failed_late_activation_rolls_back_rather_than_wedging_the_service(
service.start(invoker)
assert service.model_id is None
- monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: resolved)
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: encoder_config)
monkeypatch.setattr(ImageIndexService, "_launch_worker", launch)
service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
@@ -566,6 +585,251 @@ def test_failed_late_activation_rolls_back_rather_than_wedging_the_service(
service.stop()
[email protected]("normalize_loaded_path", [False, True], ids=["catalog-path", "normalized-loaded-path"])
+def test_encoder_metadata_edits_keep_worker_indexing_without_map_requests(
+ normalize_loaded_path: bool,
+ db: SqliteDatabase,
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ models_dir = Path(encoder_config.path).parent
+ encoder_config.path = "encoder"
+ store = ModelRecordServiceSQL(db, InvokeAILogger.get_logger())
+ store.add_model(encoder_config)
+ invoker = _make_invoker(
+ images_service, index_records, image_records=image_records, model_manager=SimpleNamespace(store=store)
+ )
+ invoker.services.configuration.image_index_model = encoder_config.name
+ invoker.services.configuration.models_dir = models_dir
+
+ def encode(self, images):
+ if normalize_loaded_path:
+ # The shared model loader makes its supplied config path absolute.
+ self._model_config.path = str((models_dir / self._model_config.path).resolve())
+ return _fake_encode(images)
+
+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", encode)
+ service = ImageIndexService()
+ try:
+ _save_image(image_records, "before-edit.png")
+ service.start(invoker)
+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)
+ worker = service._worker
+
+ # Edit the catalog between worker checks, retaining the same configured
+ # encoder after its rename. No map request drives this reconciliation.
+ with service._activation_lock:
+ store.replace_model(
+ encoder_config.key,
+ encoder_config.model_copy(
+ update={"name": "renamed encoder", "description": "Edited description", "cover_image": "cover.png"}
+ ),
+ )
+ invoker.services.configuration.image_index_model = "renamed encoder"
+ expired = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ service._last_activation_attempt = expired
+ _wait_until(lambda: service._last_activation_attempt != expired)
+ # The timestamp is written before the catalog read. Wait for the whole
+ # check to finish before observing availability or adding new work.
+ with service._activation_lock:
+ assert service.model_id == MODEL_ID
+ assert service._worker is worker
+ assert worker is not None and worker.is_alive()
+
+ _save_image(image_records, "after-edit.png")
+ images_service._on_changed(_dto_for(image_records, "after-edit.png"))
+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 2)
+ finally:
+ service.stop()
+
+
+def test_deleted_encoder_becomes_unavailable_and_reinstall_resumes_without_duplicate_callbacks(
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ installed = [encoder_config]
+ monkeypatch.setattr(
+ ImageIndexService, "_resolve_model_config", lambda self, name: installed[0] if installed else None
+ )
+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", lambda self, images: _fake_encode(images))
+ invoker = _make_invoker(images_service, index_records, image_records=image_records)
+ service = ImageIndexService()
+ try:
+ _save_image(image_records, "before.png")
+ service.start(invoker)
+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)
+ service._processor = object()
+ service._cpu_model = object()
+ service._text_encoder_failure = "previous installation was incomplete"
+ service._vocab_cache = (["old"], np.ones((1, DIM), dtype=np.float32))
+
+ installed.clear()
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ assert service.model_id is None
+ assert service.get_status() is None
+ assert service.get_vocab_build_state() == ("unavailable", None)
+ assert service.request_projection("system") is False
+ _wait_until(lambda: not service._worker.is_alive())
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ assert service._processor is None
+ assert service._cpu_model is None
+
+ _save_image(image_records, "during.png")
+ images_service._on_changed(_dto_for(image_records, "during.png"))
+ assert service._queue.empty()
+ installed.append(encoder_config.model_copy(update={"path": encoder_config.path + "-reinstalled"}))
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is True
+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 2)
+ assert len(images_service._on_changed_callbacks) == 1
+ assert len(images_service._on_deleted_callbacks) == 1
+ assert len(invoker.services.videos._on_changed_callbacks) == 1
+ assert len(invoker.services.videos._on_deleted_callbacks) == 1
+ assert service._processor is None
+ assert service._cpu_model is None
+ assert service._text_encoder_failure is None
+ assert service._vocab_cache is None
+ finally:
+ service.stop()
+
+
[email protected]("replacement_kind", ["reinstall", "key", "path", "cpu_only", "repo_variant", "type"])
[email protected]("background_batch", [False, True], ids=["query", "worker"])
+def test_encoder_replacement_waits_for_inflight_embedding_and_discards_retired_batch(
+ replacement_kind: str,
+ background_batch: bool,
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ installed = [encoder_config]
+ entered = threading.Event()
+ release = threading.Event()
+ replacements = {
+ "reinstall": {"hash": "replacement-model-hash", "path": encoder_config.path + "-replacement"},
+ "key": {"key": "replacement-key"},
+ "path": {"path": encoder_config.path + "-moved"},
+ "cpu_only": {"cpu_only": True},
+ "repo_variant": {"repo_variant": ModelRepoVariant.FP16},
+ }
+ if replacement_kind == "type":
+ replacement_type = (
+ SigLIP_Diffusers_Config
+ if isinstance(encoder_config, CLIPVision_Diffusers_Config)
+ else CLIPVision_Diffusers_Config
+ )
+ replacement = replacement_type(**encoder_config.model_dump(exclude={"type"}))
+ else:
+ replacement = encoder_config.model_copy(update=replacements[replacement_kind])
+ seen_models: list[CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config] = []
+
+ def encode(self, images):
+ seen_models.append(self._model_config)
+ if len(seen_models) == 1:
+ entered.set()
+ assert release.wait(timeout=10)
+ assert self._model_config is encoder_config
+ return _fake_encode(images)
+
+ monkeypatch.setattr(
+ ImageIndexService, "_resolve_model_config", lambda self, name: installed[0] if installed else None
+ )
+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", encode)
+ service = ImageIndexService()
+ query = None
+ try:
+ if background_batch:
+ _save_image(image_records, "pending.png")
+ service.start(_make_invoker(images_service, index_records, image_records=image_records))
+ if not background_batch:
+ query = threading.Thread(target=lambda: service.embed_image(Image.new("RGB", (16, 16))))
+ query.start()
+ assert entered.wait(timeout=10)
+
+ if replacement_kind == "reinstall":
+ installed.clear()
+ else:
+ installed[0] = replacement
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ assert service.model_id is None
+ if not background_batch:
+ _wait_until(lambda: not service._worker.is_alive())
+ installed[:] = [replacement]
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ assert service._model_config is encoder_config
+
+ release.set()
+ if query is not None:
+ query.join(timeout=10)
+ assert not query.is_alive()
+ _wait_until(lambda: not service._worker.is_alive())
+ assert index_records.count_index_status(MODEL_ID).embedded == 0
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is True
+ assert service.model_id == replacement.hash
+ if background_batch:
+ _wait_until(lambda: index_records.count_index_status(replacement.hash).embedded == 1)
+ else:
+ service.embed_image(Image.new("RGB", (16, 16)))
+ assert seen_models == [encoder_config, replacement]
+ finally:
+ release.set()
+ if query is not None:
+ query.join(timeout=10)
+ service.stop()
+
+
+def test_projection_finishing_after_encoder_removal_does_not_publish(
+ encoder_config: CLIPVision_Diffusers_Config | SigLIP_Diffusers_Config,
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ installed = [encoder_config]
+ entered = threading.Event()
+ release = threading.Event()
+
+ def project(matrix):
+ entered.set()
+ assert release.wait(timeout=10)
+ return np.zeros((len(matrix), 2), dtype=np.float32)
+
+ monkeypatch.setattr(
+ ImageIndexService, "_resolve_model_config", lambda self, name: installed[0] if installed else None
+ )
+ monkeypatch.setattr(ImageIndexService, "_encode_with_model", lambda self, images: _fake_encode(images))
+ monkeypatch.setattr(image_index_default, "compute_umap", project)
+ service = ImageIndexService()
+ try:
+ _save_image(image_records, "projected.png")
+ service.start(_make_invoker(images_service, index_records, image_records=image_records))
+ _wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)
+ assert service.request_projection("system")
+ assert entered.wait(timeout=10)
+ installed.clear()
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ release.set()
+ _wait_until(lambda: not service._worker.is_alive())
+ assert index_records.get_projection("system", MODEL_ID) is None
+ finally:
+ release.set()
+ service.stop()
+
+
def test_late_activation_survives_a_model_store_failure(
images_service: ImageService,
index_records: ImageIndexRecordsSqlite,