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.

Merge upstream/main into codex/sync-upstream-main-20260819

joshistoastbcea96813ef6
diff --cc invokeai/app/api/routers/custom_nodes.py
index 1cb27e6012,77794ef1ef..ac26470eab
--- a/invokeai/app/api/routers/custom_nodes.py
+++ b/invokeai/app/api/routers/custom_nodes.py
@@@ -30,8 -31,18 +31,19 @@@ logger = InvokeAILogger.get_logger(
# — deleting by tag alone is unsafe because users can edit tags on their own workflows.
PACK_MANIFEST_FILENAME = ".invokeai_pack_manifest.json"
PACK_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
+GIT_CLONE_TIMEOUT_SECONDS = 120
+ # Install, uninstall and reload all mutate the same three pieces of global state: the custom-nodes
+ # directory, `sys.modules`, and the invocation registry. As `async def` bodies containing no
+ # `await` they could not interleave with each other - the event loop had no point at which to
+ # switch. Running in the threadpool they can, and the interleavings are destructive: a failed
+ # install's cleanup `rmtree`s the directory a concurrent install just cloned into, and an uninstall
+ # can delete a pack out from under an install. This lock restores the exclusion explicitly.
+ #
+ # It is held across the git clone (up to its 120s timeout), which delays other *pack* operations
+ # only. Before the routes were made synchronous the same clone blocked the entire event loop.
+ _PACK_MUTATION_LOCK = threading.Lock()
+
class NodePackInfo(BaseModel):
"""Information about an installed node pack."""
@@@ -221,9 -223,14 +224,14 @@@ def _install_pack(source: str, pack_nam
try:
# Clone the repository
- returncode, stderr = await _clone_node_pack(source, target_dir)
+ result = subprocess.run(
+ ["git", "clone", source, str(target_dir)],
+ capture_output=True,
+ text=True,
- timeout=120,
++ timeout=GIT_CLONE_TIMEOUT_SECONDS,
+ )
- if returncode != 0:
+ if result.returncode != 0:
# Clean up on failure
if target_dir.exists():
shutil.rmtree(target_dir)
diff --cc invokeai/app/api/routers/gallery.py
index 0cecd05615,1b63d31c43..5b33897e83
--- a/invokeai/app/api/routers/gallery.py
+++ b/invokeai/app/api/routers/gallery.py
@@@ -67,6 -58,56 +67,64 @@@ def list_gallery_items
)
+ @gallery_router.get(
+ "/item_names",
+ operation_id="list_gallery_item_names",
+ response_model=GalleryItemNames,
+ )
+ def list_gallery_item_names(
+ current_user: CurrentUserOrDefault,
+ origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of items to list."),
+ categories: Optional[list[ImageCategory]] = Query(
+ default=None,
+ description="The categories to include. Shared between images and videos.",
+ ),
+ is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate items."),
+ board_id: Optional[str] = Query(
+ default=None,
+ description="The board id to filter by. Use 'none' to find items without a board.",
+ ),
+ created_date: Optional[str] = Query(
+ default=None,
+ description="Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards.",
+ ),
++ created_from: Optional[date] = Query(
++ default=None, description="Inclusive start date (YYYY-MM-DD) to filter by created_at."
++ ),
++ created_to: Optional[date] = Query(
++ default=None, description="Inclusive end date (YYYY-MM-DD) to filter by created_at."
++ ),
+ order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
+ starred_first: bool = Query(default=True, description="Whether to sort by starred items first"),
+ search_term: Optional[str] = Query(default=None, description="The term to search for"),
+ ) -> GalleryItemNames:
+ """Returns the ordered flat list of item names — used to drive virtualized gallery selection.
+
+ Names are polymorphic: image and video names are interleaved by `created_at`. A name ending
+ in `.mp4` is a video.
+ """
+ if board_id is not None and board_id != "none":
+ _assert_board_read_access(board_id, current_user)
+
+ try:
+ return ApiDependencies.invoker.services.gallery.get_item_names(
+ starred_first=starred_first,
+ order_dir=order_dir,
+ origin=origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ user_id=current_user.user_id,
+ is_admin=current_user.is_admin,
+ created_date=created_date,
++ created_from=created_from.isoformat() if created_from else None,
++ created_to=created_to.isoformat() if created_to else None,
+ )
+ except Exception:
+ raise HTTPException(status_code=500, detail="Failed to get gallery item names")
+
+
@gallery_router.get(
"/items/names",
operation_id="get_gallery_item_names",
@@@ -87,14 -129,13 +146,19 @@@ def get_gallery_item_names
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred items first"),
search_term: Optional[str] = Query(default=None, description="The term to search for"),
+ created_from: Optional[date] = Query(
+ default=None, description="Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ ),
+ created_to: Optional[date] = Query(
+ default=None, description="Inclusive end date (YYYY-MM-DD) to filter by created_at."
+ ),
) -> GalleryItemNamesResult:
- """Returns an ordered (kind, name) list — used to drive virtualized gallery selection."""
+ """Returns an ordered (kind, name) list — used to drive virtualized gallery selection.
+
+ Deprecated: use `GET /v1/gallery/item_names`, which returns the same order as a flat name
+ list. The `kind` discriminator here costs a model per row — ~800ms on a 200k-item library —
+ for a value callers already derive from the file extension.
+ """
if board_id is not None and board_id != "none":
_assert_board_read_access(board_id, current_user)
diff --cc invokeai/app/api/routers/image_map.py
index 6a642d1dee,0000000000..94d8fa556b
mode 100644,000000..100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@@ -1,843 -1,0 +1,843 @@@
+import asyncio
+import threading
+import time
+from collections import OrderedDict
+from typing import Literal, Optional
+
+import numpy as np
+from fastapi import File, HTTPException, Query, UploadFile, status
+from fastapi.routing import APIRouter
+from pydantic import BaseModel, Field
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers._access import assert_image_read_access
+from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
+from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
+from invokeai.app.services.image_index.image_index_common import ImageIndexStatus
+from invokeai.app.services.image_index.projection import (
+ DEFAULT_CLUSTER_MIN_SAMPLES,
+ MAX_CLUSTERED_POINTS,
+ MIN_BUDGETED_EPS,
+ cluster_at_eps,
+ compute_clusters,
+ resolve_cluster_eps,
+ scope_hash,
+)
+from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException
+
+image_map_router = APIRouter(prefix="/v1/image_map", tags=["image_map"])
+
+ImageMapState = Literal["disabled", "model_missing", "empty", "computing", "ready"]
+
+
+class ImageMapPoint(BaseModel):
+ """One image's position on the 2D semantic map."""
+
+ x: float = Field(description="UMAP x coordinate")
+ y: float = Field(description="UMAP y coordinate")
+ image_name: str = Field(description="The image this point represents")
+ cluster: int = Field(description="DBSCAN cluster label; -1 means unclustered")
+
+
+class ImageMapPointsResponse(BaseModel):
+ """The current user's semantic map."""
+
+ points: list[ImageMapPoint] = Field(description="The projected points")
+ state: ImageMapState = Field(
+ 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_name: Optional[str] = Field(
+ default=None,
+ 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",
+ )
+ stale: bool = Field(
+ description="True when the accessible image set has changed since this projection was computed; a refresh has been requested"
+ )
+ point_count: int = Field(description="Number of points returned")
+ cluster_eps: Optional[float] = Field(
+ default=None,
+ description="The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). "
+ "Pass it back explicitly to get an identical clustering from a later request.",
+ )
+ visible_hash: Optional[str] = Field(
+ default=None,
+ description="Fingerprint of the visible image set these points were computed over; compare across "
+ "image-map responses to detect accessible-set drift between requests.",
+ )
+ updated_at: Optional[str] = Field(default=None, description="When the served projection was computed")
+
+
+class ImageMapProjectionStatus(BaseModel):
+ """Status of the current user's cached projection."""
+
+ state: ImageMapState = Field(description="Projection cache state")
+ stale: bool = Field(description="Whether the cached projection lags the accessible image set")
+ point_count: int = Field(description="Points in the cached projection")
+ updated_at: Optional[str] = Field(default=None, description="When the cached projection was computed")
+
+
+class ImageMapStatusResponse(BaseModel):
+ """Combined index + projection status for the current user."""
+
+ enabled: bool = Field(description="Whether the embedding index is running")
+ model_name: Optional[str] = Field(
+ default=None,
+ description="The configured embedding model's name; only set when the projection state is model_missing",
+ )
+ index: Optional[ImageIndexStatus] = Field(
+ default=None,
+ description="Embedding index progress counts. Admin-only: the counts aggregate over all users' images, so they are omitted for regular users.",
+ )
+ projection: ImageMapProjectionStatus = Field(description="The user's projection cache status")
+
+
+class ImageMapRefreshResponse(BaseModel):
+ """Result of a projection refresh request."""
+
+ enqueued: bool = Field(description="True if the recompute was accepted (or already pending)")
+
+
+ClusterEpsQuery = Query(
+ default=None,
+ # Floored at what the resolver itself can produce, not at a round number:
+ # `_shrink_eps_to_pair_budget` walks down to MIN_BUDGETED_EPS on a map with
+ # near-coincident coordinates (duplicate generations project to the same
+ # spot), and /points reports that value as `cluster_eps` for the client to
+ # pass back here. A higher bound rejects the server's own output, and the
+ # client treats the 422 as "no labels" with nothing logged anywhere.
+ ge=MIN_BUDGETED_EPS,
+ le=2.0,
+ description="DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's "
+ "k-distance distribution. Clamped server-side relative to the projection's coordinate span.",
+)
+ClusterMinSamplesQuery = Query(
+ default=DEFAULT_CLUSTER_MIN_SAMPLES, ge=2, le=100, description="DBSCAN min_samples for clustering"
+)
+
+
+def _scope(current_user) -> tuple[str, bool]:
+ """(projection cache key, admin-wide scope flag) for the requesting user."""
+ return current_user.user_id, current_user.is_admin
+
+
+# A recompute takes minutes on any gallery large enough for this to matter, so
+# refusing a second request inside this window costs a caller nothing — while a
+# loop of them would otherwise pin the single index worker for every user and
+# fan an event into every connected admin's socket per iteration.
+MIN_REFRESH_INTERVAL_SECONDS = 10.0
+
+_refresh_claims: dict[str, float] = {}
+# Guards both module-level caches below. Held only for dict work, never across
+# clustering or a DB call.
+_state_lock = threading.Lock()
+
+
+def _claim_refresh_slot(user_id: str) -> bool:
+ """Whether this user may enqueue a refresh now, claiming their interval if so."""
+ now = time.monotonic()
+ with _state_lock:
+ # Prune on write: entries older than the window can never throttle
+ # anyone, so this keeps the map to users who refreshed recently rather
+ # than one entry per user who ever has.
+ for uid, claimed_at in list(_refresh_claims.items()):
+ if now - claimed_at >= MIN_REFRESH_INTERVAL_SECONDS:
+ del _refresh_claims[uid]
+ if user_id in _refresh_claims:
+ return False
+ _refresh_claims[user_id] = now
+ return True
+
+
+def _release_refresh_slot(user_id: str) -> None:
+ with _state_lock:
+ _refresh_claims.pop(user_id, None)
+
+
+# /points is polled, and between polls its inputs almost never change, so the
+# clustering it repeats is usually identical work. Caching the labels turns the
+# steady state into a dict lookup; entries are int64 label arrays, bounded at
+# ~400KB each by the 50k-point clustering cap (only a clustering that actually
+# ran is stored, so the all-noise array returned above the cap — which is free
+# to recompute and unbounded in size — never lands here).
+#
+# ONE entry per user, rather than a shared pool of N. A shared pool made the
+# cache worse than none: with more concurrent map users than slots, strict LRU
+# over a round-robin access pattern misses every time, and any single caller
+# could evict everyone else by varying `eps` across a handful of requests.
+_CLUSTER_CACHE_USERS = 32
+_ClusterCacheKey = tuple[str, Optional[str], str, Optional[float], int]
+_cluster_cache: "OrderedDict[str, tuple[_ClusterCacheKey, np.ndarray, Optional[float]]]" = OrderedDict()
+
+
+def _cluster_cache_get(user_id: str, key: _ClusterCacheKey) -> Optional[tuple[np.ndarray, Optional[float]]]:
+ with _state_lock:
+ entry = _cluster_cache.get(user_id)
+ if entry is None or entry[0] != key:
+ return None
+ _cluster_cache.move_to_end(user_id)
+ return entry[1], entry[2]
+
+
+def _cluster_cache_put(user_id: str, key: _ClusterCacheKey, labels: np.ndarray, resolved_eps: Optional[float]) -> None:
+ with _state_lock:
+ _cluster_cache[user_id] = (key, labels, resolved_eps)
+ _cluster_cache.move_to_end(user_id)
+ while len(_cluster_cache) > _CLUSTER_CACHE_USERS:
+ _cluster_cache.popitem(last=False)
+
+
+@image_map_router.get("/points", operation_id="get_image_map_points", response_model=ImageMapPointsResponse)
+async def get_image_map_points(
+ current_user: CurrentUserOrDefault,
+ eps: Optional[float] = ClusterEpsQuery,
+ min_samples: int = ClusterMinSamplesQuery,
+) -> ImageMapPointsResponse:
+ """Gets the current user's semantic image map.
+
+ Serves the cached UMAP projection (never blocks on a UMAP fit) and runs
+ DBSCAN per request, so `eps` is live-adjustable. If the cache is missing
+ or stale, a recompute is enqueued and reflected in `state`/`stale`.
+ """
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ # The service is also inert when indexing is enabled but the
+ # configured model is not installed; tell the client which case
+ # this is so it can show an actionable message.
+ if services.configuration.image_index_enabled:
+ return ImageMapPointsResponse(
+ points=[],
+ state="model_missing",
+ model_name=services.configuration.image_index_model,
+ stale=False,
+ point_count=0,
+ )
+ return ImageMapPointsResponse(points=[], state="disabled", stale=False, point_count=0)
+
+ user_id, is_admin = _scope(current_user)
+ current_names = services.image_index_records.list_accessible_embedded_images(
+ None if is_admin else user_id, model_id
+ )
+ record = services.image_index_records.get_projection(user_id, model_id)
+
+ if record is None:
+ if not current_names:
+ return ImageMapPointsResponse(points=[], state="empty", 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
+ )
+
+ current_hash = scope_hash(model_id, current_names)
+ stale = record.scope_hash != current_hash
+
+ if stale:
+ services.image_index.request_projection(user_id, all_images=is_admin)
+
+ # Serve only points still in the user's current accessible set, so images
+ # un-shared (or deleted) since the projection was computed never leak out
+ # of a stale cache. Filtering happens BEFORE clustering: labels computed
+ # over hidden points would let density-chaining through an inaccessible
+ # image leak its existence (and be wrong besides). All of this is CPU-bound
+ # and O(point count) — including the accessibility mask, which is a Python
+ # membership test per cached point — so it runs off the event loop. Hoisting
+ # the mask into the coroutine to decide the retry first cost 54ms of event
+ # loop time per poll on a 500k-image gallery, stalling every other request
+ # in the process; the retry decision is made below instead, from the one
+ # fact it actually needs.
+ def build_points() -> tuple[list[ImageMapPoint], Optional[float], bool, str]:
+ accessible = set(current_names)
+ visible_mask = np.fromiter(
+ (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)
+ )
+ # A NaN cannot be serialized as valid JSON, so one corrupt coordinate
+ # would fail the whole response; rows written before the projection
+ # writer grew its isfinite guard are still out there in existing
+ # databases.
+ visible_mask &= np.isfinite(record.coords).all(axis=1)
+ visible_names = [name for name, keep in zip(record.image_names, visible_mask, strict=True) if keep]
+ visible_coords = record.coords[visible_mask]
+
+ # Every input to the clustering is pinned by this key: which projection
+ # row (its own scope hash plus updated_at, which moves on every rewrite),
+ # which subset of it this user can currently see (current_hash), and the
+ # two DBSCAN parameters. The cache is keyed by user on top of this, so
+ # one user's labels can never be served to another even if all of these
+ # collide.
+ cache_key: _ClusterCacheKey = (record.scope_hash, record.updated_at, current_hash, eps, min_samples)
+ cached_labels = _cluster_cache_get(user_id, cache_key)
+ if cached_labels is not None:
+ labels, resolved_eps = cached_labels
+ return (
+ [
+ ImageMapPoint(x=float(x), y=float(y), image_name=name, cluster=int(label))
+ for name, (x, y), label in zip(visible_names, visible_coords, labels, strict=True)
+ ],
+ resolved_eps,
+ True,
+ scope_hash(model_id, visible_names),
+ )
+
+ try:
+ if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
+ resolved_eps = resolve_cluster_eps(visible_coords, eps, min_samples)
+ # cluster_at_eps, not compute_clusters: the latter re-resolves
+ # what was just resolved, and the second pass re-applies the
+ # 0.01 floor to a budget-shrunk eps — so the value reported
+ # here would not be the value DBSCAN used.
+ labels = cluster_at_eps(visible_coords, resolved_eps, min_samples)
+ # Cached only here. The other branch's labels are a constant
+ # -1 array sized to the full point count — free to recompute,
+ # unbounded in size, and above the cap that is the only array
+ # large enough to matter.
+ _cluster_cache_put(user_id, cache_key, labels, resolved_eps)
+ else:
+ resolved_eps = None
+ labels = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
+ except Exception:
+ # Clustering is a presentation detail; the coordinates are the
+ # data. sklearn raises on a non-finite cached row (which a build
+ # predating the writer's isfinite guard could have left behind),
+ # and an unhandled raise here 500s this user on EVERY request until
+ # their gallery changes. Serve the map unclustered instead. Nothing
+ # is cached on this path: a one-off failure must not stick.
+ services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving points unclustered")
+ resolved_eps = None
+ labels = np.full((visible_coords.shape[0],), -1, dtype=np.int64)
+ return (
+ [
+ ImageMapPoint(x=float(x), y=float(y), image_name=name, cluster=int(label))
+ for name, (x, y), label in zip(visible_names, visible_coords, labels, strict=True)
+ ],
+ resolved_eps,
+ bool(visible_mask.any()),
+ scope_hash(model_id, visible_names),
+ )
+
+ points, resolved_eps, any_visible, visible_hash = await asyncio.to_thread(build_points)
+
+ retrying = False
+ if not stale and current_names and not any_visible:
+ # Nothing servable over a gallery that HAS embedded images: a failed
+ # fit, not a result — and it is stamped with the current scope, so
+ # staleness will never ask for it again. `failed_scope` makes the
+ # service refuse this once the scope's single retry is spent, so a
+ # permanent failure settles into an honest "empty" instead of a
+ # request/event cycle driven by every poll.
+ retrying = services.image_index.request_projection(user_id, all_images=is_admin, failed_scope=current_hash)
+
+ state: ImageMapState = "ready" if points else ("computing" if retrying else "empty")
+ return ImageMapPointsResponse(
+ points=points,
+ state=state,
+ stale=stale,
+ point_count=len(points),
+ cluster_eps=resolved_eps,
+ visible_hash=visible_hash,
+ updated_at=record.updated_at,
+ )
+
+
+class ImageMapSearchResult(BaseModel):
+ """One semantic search hit."""
+
+ image_name: str = Field(description="The matching image")
+ score: float = Field(description="Cosine similarity to the query; higher is more similar")
+
+
+class ImageMapSearchResponse(BaseModel):
+ """Semantic search results over the user's embedded images."""
+
+ results: list[ImageMapSearchResult] = Field(description="Ranked results, most similar first")
+
+
+@image_map_router.get("/search", operation_id="search_image_map", response_model=ImageMapSearchResponse)
+async def search_image_map(
+ current_user: CurrentUserOrDefault,
+ q: Optional[str] = Query(default=None, max_length=500, description="Text query to embed and search with"),
+ image_name: Optional[str] = Query(default=None, description="Reference image for similarity search"),
+ limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),
+) -> ImageMapSearchResponse:
+ """Ranks the user's accessible images by semantic similarity.
+
+ Provide exactly one of `q` (text search — requires the embedding model's
+ text encoder to be installed) or `image_name` (visual similarity — uses
+ the reference image's stored embedding when it exists, and otherwise
+ embeds the image file on demand, so unindexed images such as assets can
+ be reference images too).
+ """
+ services = ApiDependencies.invoker.services
+ if (q is None) == (image_name is None):
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of q or image_name"
+ )
+
+ model_id = services.image_index.model_id
+ if model_id is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="The image index is not enabled; semantic search is unavailable",
+ )
+
+ user_id, is_admin = _scope(current_user)
+ scope_user = None if is_admin else user_id
+
+ if q is not None:
+ try:
+ query_embedding = await asyncio.to_thread(services.image_index.embed_text, q)
+ except TextSearchUnavailableError as e:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
+ else:
+ assert image_name is not None
+ assert_image_read_access(image_name, current_user)
+ found, matrix = services.image_index_records.get_embeddings([image_name], model_id)
+ if found:
+ query_embedding = matrix[0]
+ else:
+ # Not in the index (assets and intermediates are never indexed) —
+ # embed the stored file on demand for this one query.
+ def embed_from_file() -> np.ndarray:
+ pil = services.images.get_pil_image(image_name)
+ # Capped exactly as the uploaded/downloaded path is: the encoder
+ # downscales to ~224px either way, and convert("RGB") on a large
+ # stored image materializes hundreds of MB on a request thread.
+ # This branch is the *normal* one for such images, since assets
+ # and intermediates are never indexed.
+ if pil.width * pil.height > MAX_SEARCH_IMAGE_PIXELS:
+ raise HTTPException(
+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
+ detail="The reference image has too many pixels",
+ )
+ return services.image_index.embed_image(pil)
+
+ try:
+ query_embedding = await asyncio.to_thread(embed_from_file)
+ except HTTPException:
+ raise
+ except (ImageFileNotFoundException, ImageRecordNotFoundException, OSError):
+ # The stored file is missing or undecodable — the only failure
+ # here that is really about this image. Both record and file
+ # exceptions are plain Exceptions rather than OSError, so they
+ # have to be named; PIL's decode failures are OSError subclasses.
+ services.logger.warning(f"Image search: cannot read '{image_name}' for on-demand embed", exc_info=True)
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="This image could not be embedded for search (its file may be missing)",
+ )
+ except Exception:
+ # An encoder fault, a stopped index, an OOM. Reporting these as
+ # "file may be missing" sent anyone debugging to the wrong place.
+ services.logger.error(f"Image search: failed to embed '{image_name}' on demand", exc_info=True)
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="This image could not be embedded for search",
+ )
+
+ results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)
+ return ImageMapSearchResponse(
+ results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]
+ )
+
+
+# One-off reference images are small; cap what we will buffer from an upload
+# or a URL download before decoding, and how many pixels we will decode.
+MAX_SEARCH_IMAGE_BYTES = 32 * 1024 * 1024
+MAX_SEARCH_IMAGE_PIXELS = 64_000_000
+_URL_TIMEOUT_SECONDS = 10.0
+_URL_TOTAL_DEADLINE_SECONDS = 30.0
+_URL_MAX_REDIRECTS = 5
+
+# Downloads run on the loop's shared default executor; a handful of slow
+# remote servers must not be able to park every thread in it.
+_download_slots = asyncio.Semaphore(4)
+
+
+def _assert_url_host_allowed(url: str) -> None:
+ """Reject URLs whose scheme is not http(s) or whose host resolves to any
+ non-global address (loopback, RFC1918, link-local, reserved).
+
+ Resolving via getaddrinfo covers hostnames like 'localhost' and the
+ non-canonical IP notations (decimal, hex, octal, shortened) that a plain
+ ip_address() literal parse misses. DNS rebinding between this check and
+ the actual request is accepted residual risk: the endpoint is
+ authenticated, and nothing about the response is revealed beyond whether
+ it decoded as an image.
+ """
+ import ipaddress
+ import socket
+ from urllib.parse import urlparse
+
+ parsed = urlparse(url)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url must be an http(s) URL")
+
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
+ try:
+ infos = socket.getaddrinfo(parsed.hostname, port, proto=socket.IPPROTO_TCP)
+ except OSError:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url host could not be resolved"
+ )
+ for info in infos:
+ if not ipaddress.ip_address(info[4][0]).is_global:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="image_url must not target a private or loopback address",
+ )
+
+
+def _download_search_image(url: str) -> bytes:
+ """Fetch a reference image for a one-off similarity search.
+
+ Redirects are followed manually so every hop is re-validated by
+ _assert_url_host_allowed — requests' automatic redirect handling would
+ happily follow a public URL into a private address. The wall-clock
+ deadline bounds slow-trickle servers that never trip the per-read
+ timeout.
+ """
+ import time
+ from urllib.parse import urljoin
+
+ import requests
+
+ deadline = time.monotonic() + _URL_TOTAL_DEADLINE_SECONDS
+
+ def _remaining() -> float:
+ """Budget left, as a positive number; raises once it is gone.
+
+ Checked before each hop and used as the per-request timeout, so the deadline bounds the
+ whole exchange rather than only the body. Without it the connect and read timeouts apply
+ afresh to every redirect, and a server that stalls each of the allowed hops before sending
+ a byte holds a thread for minutes — uninterruptibly, since this runs under
+ `asyncio.to_thread` on the executor that also serves embedding and search.
+ """
+ left = deadline - time.monotonic()
+
+ if left <= 0:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="The image download took too long",
+ )
+
+ return left
+
+ try:
+ for _ in range(_URL_MAX_REDIRECTS + 1):
+ _assert_url_host_allowed(url)
+ hop_timeout = min(_URL_TIMEOUT_SECONDS, _remaining())
+ with requests.get(url, stream=True, timeout=hop_timeout, allow_redirects=False) as response:
+ if response.is_redirect:
+ location = response.headers.get("location")
+ if not location:
+ break
+ url = urljoin(url, location)
+ continue
+ response.raise_for_status()
+ chunks: list[bytes] = []
+ received = 0
+ for chunk in response.iter_content(chunk_size=64 * 1024):
+ received += len(chunk)
+ if received > MAX_SEARCH_IMAGE_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ detail="The reference image is too large",
+ )
+ _remaining()
+ chunks.append(chunk)
+ return b"".join(chunks)
+ except HTTPException:
+ raise
+ except Exception:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="The image could not be downloaded from image_url",
+ )
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Too many redirects for image_url")
+
+
+@image_map_router.post(
+ "/search_by_image", operation_id="search_image_map_by_image", response_model=ImageMapSearchResponse
+)
+async def search_image_map_by_image(
+ current_user: CurrentUserOrDefault,
+ image: Optional[UploadFile] = File(default=None, description="Reference image file"),
+ image_url: Optional[str] = Query(default=None, max_length=2000, description="URL of a reference image"),
+ limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),
+) -> ImageMapSearchResponse:
+ """Ranks the user's accessible images by similarity to an arbitrary reference image.
+
+ Provide exactly one of `image` (multipart upload) or `image_url` (the
+ server downloads it). The reference is embedded for this query only —
+ nothing is stored.
+ """
+ services = ApiDependencies.invoker.services
+ if (image is None) == (image_url is None):
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of image or image_url"
+ )
+
+ model_id = services.image_index.model_id
+ if model_id is None:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="The image index is not enabled; semantic search is unavailable",
+ )
+
+ user_id, is_admin = _scope(current_user)
+ scope_user = None if is_admin else user_id
+
+ if image is not None:
+ data = await image.read(MAX_SEARCH_IMAGE_BYTES + 1)
+ if len(data) > MAX_SEARCH_IMAGE_BYTES:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="The reference image is too large"
+ )
+ else:
+ assert image_url is not None
+ async with _download_slots:
+ data = await asyncio.to_thread(_download_search_image, image_url)
+
+ def embed_bytes() -> np.ndarray:
+ from io import BytesIO
+
+ from PIL import Image
+
+ pil = Image.open(BytesIO(data))
+ # The encoder downscales to ~224px anyway; refuse decompression bombs
+ # before convert() materializes hundreds of MB of RGB.
+ if pil.width * pil.height > MAX_SEARCH_IMAGE_PIXELS:
+ raise HTTPException(
+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="The reference image has too many pixels"
+ )
+ return services.image_index.embed_image(pil)
+
+ try:
+ query_embedding = await asyncio.to_thread(embed_bytes)
+ except HTTPException:
+ raise
+ except Exception:
+ services.logger.warning("Image search: failed to decode or embed an uploaded reference image", exc_info=True)
+ raise HTTPException(
+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
+ detail="The reference could not be decoded as an image",
+ )
+
+ results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)
+ return ImageMapSearchResponse(
+ results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]
+ )
+
+
+class ImageMapClusterLabel(BaseModel):
+ """The best vocabulary label for one cluster."""
+
+ label: str = Field(description="Best-matching vocabulary phrase")
+ alternates: list[str] = Field(description="Runner-up phrases")
+ score: float = Field(description="Cosine similarity of the best phrase to the cluster centroid")
+
+
+class ImageMapClusterLabelsResponse(BaseModel):
+ """Automatic labels for the current user's visible clusters, keyed by cluster id."""
+
+ labels: dict[str, ImageMapClusterLabel] = Field(description="Cluster id -> label; noise (-1) is omitted")
+ visible_hash: Optional[str] = Field(
+ default=None,
+ description="Fingerprint of the visible image set these labels were clustered over; clients must discard "
+ "labels whose visible_hash does not match their points response",
+ )
+ updated_at: Optional[str] = Field(
+ default=None,
+ description="The projection these labels were computed against; clients must discard labels whose projection does not match their points",
+ )
+
+
+@image_map_router.get(
+ "/cluster_labels", operation_id="get_image_map_cluster_labels", response_model=ImageMapClusterLabelsResponse
+)
+async def get_image_map_cluster_labels(
+ current_user: CurrentUserOrDefault,
+ eps: Optional[float] = ClusterEpsQuery,
+ min_samples: int = ClusterMinSamplesQuery,
+ top_k: int = Query(default=3, ge=1, le=10, description="Candidate labels per cluster"),
+) -> ImageMapClusterLabelsResponse:
+ """Labels the user's visible clusters with the most similar vocabulary phrases.
+
+ Clustering mirrors `/points` (same eps semantics, computed over the
+ caller's currently-accessible points), so cluster ids line up with the
+ served map. Pass the `cluster_eps` reported by `/points` so both requests
+ cluster with the same eps; cluster ids can still differ if the accessible
+ set changes between the requests, so compare the two responses'
+ `visible_hash` (and `updated_at`) and discard labels on mismatch.
+ Requires the embedding model's text encoder; the first call per model
+ embeds the whole vocabulary and is slow.
+ """
+ from invokeai.app.services.image_index.cluster_labels import label_clusters
+
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="The image index is not enabled")
+
+ user_id, is_admin = _scope(current_user)
+ record = services.image_index_records.get_projection(user_id, model_id)
+ if record is None or record.point_count == 0:
+ return ImageMapClusterLabelsResponse(labels={})
+
+ try:
+ vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)
+ except TextSearchUnavailableError as e:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
+
+ current_names = services.image_index_records.list_accessible_embedded_images(
+ None if is_admin else user_id, model_id
+ )
+
+ def build() -> tuple[dict[int, dict], str]:
+ accessible = set(current_names)
+ mask = np.fromiter(
+ (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)
+ )
+ # Exactly the mask /points applies, non-finite filter included. Without
+ # it this endpoint's visible_hash is computed over a different set of
+ # names than the one /points reports, so every response the client
+ # receives fails the hash comparison it is told to make and all labels
+ # are discarded — and the clustering below is handed a NaN, which
+ # sklearn raises on, 500ing this user until their gallery changes.
+ mask &= np.isfinite(record.coords).all(axis=1)
+ visible_names = [name for name, keep in zip(record.image_names, mask, strict=True) if keep]
+ visible_hash = scope_hash(model_id, visible_names)
+ if not visible_names:
+ return {}, visible_hash
+ visible_coords = record.coords[mask]
+ try:
+ if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
+ # cluster_at_eps on a resolved eps, matching /points: passing an
+ # already-resolved eps to compute_clusters re-resolves it, so
+ # the labels here could come from a different eps than the
+ # cluster_eps /points reported and the client passed back.
+ cluster_ids = cluster_at_eps(
+ visible_coords, resolve_cluster_eps(visible_coords, eps, min_samples), min_samples
+ )
+ else:
+ cluster_ids = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
+ except Exception:
+ # /points degrades to unclustered rather than 500ing; labels over no
+ # clusters is the same degradation, and the client already discards
+ # a label set whose visible_hash does not match its points.
+ services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving no labels")
+ return {}, visible_hash
+ # Nothing clustered, nothing to label. Worth checking before the gather
+ # below: above MAX_CLUSTERED_POINTS every id is -1 by design, and on a
+ # gallery that large the fancy-index would copy gigabytes purely to
+ # hand label_clusters a set of noise rows it discards.
+ clustered = cluster_ids >= 0
+ if not clustered.any():
+ return {}, visible_hash
+
+ cluster_by_name = dict(zip(visible_names, cluster_ids, strict=True))
+ # The accessible matrix comes from the same LRU the search endpoint
+ # uses — this endpoint fires after every points refresh, and a full
+ # BLOB read per request would not scale to large galleries.
+ accessible_names, accessible_matrix = services.image_index.get_accessible_embeddings(
+ None if is_admin else user_id
+ )
+ row_by_name = {name: index for index, name in enumerate(accessible_names)}
+ # Noise rows are excluded here rather than inside label_clusters: they
+ # contribute to no centroid, so gathering them only widens the copy.
+ found_names = [
+ name
+ for name, is_clustered in zip(visible_names, clustered, strict=True)
+ if is_clustered and name in row_by_name
+ ]
+ if not found_names:
+ return {}, visible_hash
+ embeddings = accessible_matrix[[row_by_name[name] for name in found_names]]
+ aligned = np.fromiter((cluster_by_name[name] for name in found_names), dtype=np.int64, count=len(found_names))
+ return label_clusters(aligned, embeddings, vocabulary, vocab_embeddings, top_k=top_k), visible_hash
+
+ labels, visible_hash = await asyncio.to_thread(build)
+ return ImageMapClusterLabelsResponse(
+ labels={
+ str(cluster_id): ImageMapClusterLabel(
+ alternates=info["alternates"], label=info["label"], score=info["score"]
+ )
+ for cluster_id, info in labels.items()
+ },
+ visible_hash=visible_hash,
+ updated_at=record.updated_at,
+ )
+
+
+@image_map_router.post(
+ "/refresh",
+ operation_id="refresh_image_map",
+ response_model=ImageMapRefreshResponse,
+ status_code=status.HTTP_202_ACCEPTED,
+)
- async def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefreshResponse:
++def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefreshResponse:
+ """Requests a recompute of the current user's image map projection."""
+ user_id, is_admin = _scope(current_user)
+ if not _claim_refresh_slot(user_id):
+ # Throttled, not failed: `enqueued` already means "was this accepted",
+ # so a client needs no new status code or field to understand it.
+ return ImageMapRefreshResponse(enqueued=False)
+
+ try:
+ enqueued = ApiDependencies.invoker.services.image_index.request_projection(
+ user_id, all_images=is_admin, user_initiated=True
+ )
+ except Exception:
+ # A raise between the claim and the release (the invoker is absent
+ # during a startup or shutdown window, say) would otherwise leave the
+ # claim held with nothing queued against it.
+ _release_refresh_slot(user_id)
+ raise
+ if not enqueued:
+ # Nothing was actually queued (the indexer is not running), so this
+ # request must not consume the user's interval — otherwise a client
+ # polling through a restart is locked out of the first real refresh.
+ _release_refresh_slot(user_id)
+ return ImageMapRefreshResponse(enqueued=enqueued)
+
+
+@image_map_router.get("/status", operation_id="get_image_map_status", response_model=ImageMapStatusResponse)
- async def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:
++def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:
+ """Gets embedding index progress and the user's projection cache status."""
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ model_missing = services.configuration.image_index_enabled
+ return ImageMapStatusResponse(
+ enabled=False,
+ model_name=services.configuration.image_index_model if model_missing else None,
+ projection=ImageMapProjectionStatus(
+ state="model_missing" if model_missing else "disabled", stale=False, point_count=0
+ ),
+ )
+
+ user_id, is_admin = _scope(current_user)
+ record = services.image_index_records.get_projection(user_id, model_id)
+ if record is None:
+ projection = ImageMapProjectionStatus(state="empty", stale=False, point_count=0)
+ else:
+ current_names = services.image_index_records.list_accessible_embedded_images(
+ None if is_admin else user_id, model_id
+ )
+ # Count only currently-accessible points; a stale record's raw count
+ # would reveal the size of a since-revoked scope.
+ visible_count = len(set(record.image_names) & set(current_names))
+ projection = ImageMapProjectionStatus(
+ state="ready" if visible_count else "empty",
+ stale=record.scope_hash != scope_hash(model_id, current_names),
+ point_count=visible_count,
+ updated_at=record.updated_at,
+ )
+ # 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)
diff --cc invokeai/app/api/routers/images.py
index 1d003b3117,d352b7bd77..c0198c89d1
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@@ -106,9 -102,21 +107,9 @@@ async def upload_image
"""Uploads an image for the current user"""
# If uploading into a board, verify the user has write access.
# Public boards allow uploads from any authenticated user.
- _assert_board_write_access(board_id, current_user)
- if board_id is not None:
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = await asyncio.to_thread(ApiDependencies.invoker.services.boards.get_dto, board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if (
- not current_user.is_admin
- and board.user_id != current_user.user_id
- and board.board_visibility != BoardVisibility.Public
- ):
- raise HTTPException(status_code=403, detail="Not authorized to upload to this board")
++ await asyncio.to_thread(_assert_board_write_access, board_id, current_user)
- assert_image_move_maintenance_inactive()
+ await asyncio.to_thread(assert_image_move_maintenance_inactive)
if not file.content_type or not file.content_type.startswith("image"):
raise HTTPException(status_code=415, detail="Not an image")
@@@ -823,17 -762,15 +832,21 @@@ def get_image_names
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred images first"),
search_term: Optional[str] = Query(default=None, description="The term to search for"),
+ created_from: Optional[date] = Query(
+ default=None, description="Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ ),
+ created_to: Optional[date] = Query(
+ default=None, description="Inclusive end date (YYYY-MM-DD) to filter by created_at."
+ ),
) -> ImageNamesResult:
- """Gets ordered list of image names with metadata for optimistic updates"""
+ """Gets ordered list of image names with metadata for optimistic updates.
+
+ Deprecated: use `GET /v1/gallery/item_names`, which returns images and videos interleaved
+ in one ordered list. This image-only endpoint predates the polymorphic gallery.
+ """
# Validate that the caller can read from this board before listing its images.
- if board_id is not None and board_id != "none":
+ if board_id is not None and board_id not in {"none", "all"}:
_assert_board_read_access(board_id, current_user)
try:
diff --cc invokeai/app/api/routers/model_manager.py
index 3fe863c2d3,52f6544e30..713a26cc92
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@@ -9,10 -11,10 +11,10 @@@ from collections.abc import Generato
from copy import deepcopy
from enum import Enum
from tempfile import TemporaryDirectory
- from typing import List, Optional, Type
+ from typing import Any, List, Optional, Type
import huggingface_hub
-from fastapi import Body, Path, Query, Response, UploadFile
+from fastapi import Body, Header, Path, Query, Response, UploadFile
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.routing import APIRouter
from PIL import Image
@@@ -229,20 -296,6 +301,20 @@@ def list_missing_models(current_user: C
return ModelsList(models=missing_models)
+@model_manager_router.get(
+ "/models_dir",
+ operation_id="get_models_dir",
+ responses={200: {"description": "The absolute path of the models directory"}},
+)
- async def get_models_dir(current_user: CurrentUserOrDefault) -> str:
++def get_models_dir(current_user: CurrentUserOrDefault) -> str:
+ """Get the absolute path of the directory managed models are stored in.
+
+ Model config `path` values are relative to this directory unless they are
+ absolute (in-place installs from outside it).
+ """
+ return ApiDependencies.invoker.services.configuration.models_path.resolve().as_posix()
+
+
@model_manager_router.get(
"/get_by_attrs",
operation_id="get_model_records_by_attrs",
@@@ -1391,9 -1480,8 +1508,9 @@@ def get_stats(current_admin: AdminUserO
"/empty_model_cache",
operation_id="empty_model_cache",
status_code=200,
+ response_model=EmptyModelCacheResponse,
)
- async def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheResponse:
-def empty_model_cache(current_admin: AdminUserOrDefault) -> None:
++def empty_model_cache(current_admin: AdminUserOrDefault) -> EmptyModelCacheResponse:
"""Drop all models from the model cache to free RAM/VRAM. 'Locked' models that are in active use will not be dropped."""
# Request 1000GB of room in order to force each per-device cache to drop all models.
ApiDependencies.invoker.services.logger.info("Emptying model cache.")
diff --cc invokeai/app/api/routers/projects.py
index 8869bf11a7,0000000000..97518c8448
mode 100644,000000..100644
--- a/invokeai/app/api/routers/projects.py
+++ b/invokeai/app/api/routers/projects.py
@@@ -1,152 -1,0 +1,152 @@@
+from typing import Any
+
+from fastapi import Body, HTTPException, Path, status
+from fastapi.routing import APIRouter
+from pydantic import BaseModel, Field
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.project_records.project_records_common import (
+ ProjectBoardNotFoundError,
+ ProjectBoardSnapshotDTO,
+ ProjectBoardTooLargeError,
+ ProjectBoardUnavailableError,
+ ProjectRecordConflictError,
+ ProjectRecordDTO,
+ ProjectRecordExistsError,
+ ProjectRecordNotFoundError,
+ ProjectSummaryDTO,
+)
+
+projects_router = APIRouter(prefix="/v1/projects", tags=["projects"])
+
+
+class ProjectCreateRequest(BaseModel):
+ """Request body for creating a project."""
+
+ project_id: str | None = Field(
+ default=None, description="Client-generated project id (e.g. for imports); generated when omitted"
+ )
+ board_id: str | None = Field(
+ default=None,
+ description=(
+ "An existing unclaimed private board for the project to adopt, renamed to match. Omit to create"
+ " one. Restoring a project uploads its media into such a board first, so that creating the"
+ " project is the single commit point for an import."
+ ),
+ )
+ name: str = Field(description="The project's display name")
+ data: dict[str, Any] = Field(description="The opaque client-owned project document")
+
+
+class ProjectUpdateRequest(BaseModel):
+ """Request body for saving a project with optimistic concurrency."""
+
+ name: str = Field(description="The project's display name")
+ data: dict[str, Any] = Field(description="The opaque client-owned project document")
+ expected_revision: int = Field(description="The revision this save is based on; mismatch returns 409")
+
+
+@projects_router.get("/", operation_id="list_projects", response_model=list[ProjectSummaryDTO])
- async def list_projects(current_user: CurrentUserOrDefault) -> list[ProjectSummaryDTO]:
++def list_projects(current_user: CurrentUserOrDefault) -> list[ProjectSummaryDTO]:
+ """Lists the current user's projects as lightweight summaries (no documents)."""
+ return ApiDependencies.invoker.services.project_records.list(current_user.user_id)
+
+
+@projects_router.post(
+ "/", operation_id="create_project", response_model=ProjectRecordDTO, status_code=status.HTTP_201_CREATED
+)
- async def create_project(
++def create_project(
+ current_user: CurrentUserOrDefault,
+ request: ProjectCreateRequest = Body(description="The project to create"),
+) -> ProjectRecordDTO:
+ """Creates a project, and the private board it owns, for the current user."""
+ try:
+ return ApiDependencies.invoker.services.project_records.create(
+ user_id=current_user.user_id,
+ name=request.name,
+ data=request.data,
+ project_id=request.project_id,
+ board_id=request.board_id,
+ )
+ except (ProjectRecordExistsError, ProjectBoardUnavailableError) as e:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
+ except ProjectBoardNotFoundError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+
+
+@projects_router.get("/{project_id}", operation_id="get_project", response_model=ProjectRecordDTO)
- async def get_project(
++def get_project(
+ current_user: CurrentUserOrDefault,
+ project_id: str = Path(description="The id of the project to get"),
+) -> ProjectRecordDTO:
+ """Gets one of the current user's projects, including its document."""
+ try:
+ return ApiDependencies.invoker.services.project_records.get(current_user.user_id, project_id)
+ except ProjectRecordNotFoundError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+
+
+@projects_router.put("/{project_id}", operation_id="update_project", response_model=ProjectRecordDTO)
- async def update_project(
++def update_project(
+ current_user: CurrentUserOrDefault,
+ project_id: str = Path(description="The id of the project to save"),
+ request: ProjectUpdateRequest = Body(description="The project document and the revision it is based on"),
+) -> ProjectRecordDTO:
+ """Saves a project. Returns 409 with the current revision when the save is based on a stale revision."""
+ try:
+ return ApiDependencies.invoker.services.project_records.update(
+ user_id=current_user.user_id,
+ project_id=project_id,
+ expected_revision=request.expected_revision,
+ name=request.name,
+ data=request.data,
+ )
+ except ProjectRecordNotFoundError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+ except ProjectRecordConflictError as e:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={"message": str(e), "current_revision": e.current_revision},
+ )
+
+
+@projects_router.get(
+ "/{project_id}/board-snapshot",
+ operation_id="get_project_board_snapshot",
+ response_model=ProjectBoardSnapshotDTO,
+)
- async def get_project_board_snapshot(
++def get_project_board_snapshot(
+ current_user: CurrentUserOrDefault,
+ project_id: str = Path(description="The id of the project whose board to enumerate"),
+) -> ProjectBoardSnapshotDTO:
+ """Lists everything on the project's board that the gallery would show.
+
+ Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller
+ that needs this — exporting a project — has to hold the whole list anyway. It is still bounded,
+ because the answer is built entirely in memory and any client with a project id can ask for it;
+ a board past the ceiling is one an export could not have packed either, so it is refused as a
+ 413 rather than paged.
+ """
+ try:
+ return ApiDependencies.invoker.services.project_records.get_board_snapshot(current_user.user_id, project_id)
+ except ProjectRecordNotFoundError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+ except ProjectBoardTooLargeError as e:
+ raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=str(e))
+
+
+@projects_router.delete("/{project_id}", operation_id="delete_project", status_code=status.HTTP_204_NO_CONTENT)
- async def delete_project(
++def delete_project(
+ current_user: CurrentUserOrDefault,
+ project_id: str = Path(description="The id of the project to delete"),
+) -> None:
+ """Deletes one of the current user's projects, and the board it owns, in one transaction.
+
+ Idempotent. The media survives: deleting the board drops its memberships, so the images and
+ videos on it return to Uncategorized, exactly as they would if the board were deleted without
+ `include_images`. There is deliberately no option to take them with it — a project is a
+ workspace, and emptying someone's gallery is not what deleting one should be able to mean.
+ Nothing is reported back for the same reason: nothing was destroyed to report.
+ """
+ ApiDependencies.invoker.services.project_records.delete(current_user.user_id, project_id)
diff --cc invokeai/app/api/routers/session_queue.py
index 49cc4899da,e0cde55fbd..3726e7803b
--- a/invokeai/app/api/routers/session_queue.py
+++ b/invokeai/app/api/routers/session_queue.py
@@@ -143,52 -107,16 +186,30 @@@ def sanitize_queue_item_for_user(queue_
"""
# Admins and item owners can see everything
if is_admin or queue_item.user_id == current_user_id:
- return strip_missing_image_results(queue_item)
-
- # For non-admins viewing other users' items, strip everything except
- # item_id, queue_id, status, and timestamps
- sanitized_item = queue_item.model_copy(deep=False)
- sanitized_item.user_id = "redacted"
- sanitized_item.user_display_name = None
- sanitized_item.user_email = None
- sanitized_item.batch_id = "redacted"
- sanitized_item.session_id = "redacted"
- sanitized_item.origin = None
- sanitized_item.destination = None
- sanitized_item.priority = 0
- sanitized_item.field_values = None
- sanitized_item.retried_from_item_id = None
- sanitized_item.workflow_call_id = None
- sanitized_item.parent_item_id = None
- sanitized_item.parent_session_id = None
- sanitized_item.root_item_id = None
- sanitized_item.workflow_call_depth = None
- sanitized_item.workflow = None
- sanitized_item.error_type = None
- sanitized_item.error_message = None
- sanitized_item.error_traceback = None
- # Upstream's per-GPU field, redacted for the same reason as origin/destination/priority: a
- # non-admin has no business knowing where another user's work is placed.
- sanitized_item.device = None
- sanitized_item.session = GraphExecutionState(
- id="redacted",
- graph=Graph(),
- )
- return sanitized_item
++ if isinstance(queue_item, SessionQueueItem):
++ return strip_missing_image_results(queue_item)
+ return queue_item
+
+ updates = {
+ field: build_replacement()
+ for field, build_replacement in _REDACTIONS.items()
+ if field in type(queue_item).model_fields
+ }
+ return queue_item.model_copy(update=updates)
+def get_queue_item_for_mutation(queue_id: str, item_id: int, current_user: CurrentUserOrDefault) -> SessionQueueItem:
+ queue_item = ApiDependencies.invoker.services.session_queue.get_queue_item(item_id)
+
+ if queue_item.queue_id != queue_id:
+ raise HTTPException(status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}")
+
+ if queue_item.user_id != current_user.user_id and not current_user.is_admin:
+ raise HTTPException(status_code=403, detail=f"You do not have permission to mutate queue item {item_id}")
+
+ return queue_item
+
+
@session_queue_router.post(
"/{queue_id}/enqueue_batch",
operation_id="enqueue_batch",
@@@ -517,12 -471,9 +569,12 @@@ def prune
200: {"model": Optional[SessionQueueItem]},
},
)
- async def get_current_queue_item(
+ def get_current_queue_item(
current_user: CurrentUserOrDefault,
queue_id: str = Path(description="The queue id to perform this operation on"),
+ origin_prefix: Optional[str] = Query(
+ default=None, description="Only include queue items whose origin starts with this prefix"
+ ),
) -> Optional[SessionQueueItem]:
"""Gets the currently execution queue item"""
try:
@@@ -541,12 -492,9 +593,12 @@@
200: {"model": Optional[SessionQueueItem]},
},
)
- async def get_next_queue_item(
+ def get_next_queue_item(
current_user: CurrentUserOrDefault,
queue_id: str = Path(description="The queue id to perform this operation on"),
+ origin_prefix: Optional[str] = Query(
+ default=None, description="Only include queue items whose origin starts with this prefix"
+ ),
) -> Optional[SessionQueueItem]:
"""Gets the next queue item, without executing it"""
try:
@@@ -565,12 -513,9 +617,12 @@@
200: {"model": SessionQueueAndProcessorStatus},
},
)
- async def get_queue_status(
+ def get_queue_status(
current_user: CurrentUserOrDefault,
queue_id: str = Path(description="The queue id to perform this operation on"),
+ origin_prefix: Optional[str] = Query(
+ default=None, description="Only include queue items whose origin starts with this prefix"
+ ),
) -> SessionQueueAndProcessorStatus:
"""Gets the status of the session queue. Returns global counts; every user additionally gets
their own pending/in_progress counts (so the UI can show an X/Y badge and scope personal UI
diff --cc invokeai/app/api/routers/style_presets.py
index 7fee46e643,3ae52e5eeb..dfdcdf3eba
--- a/invokeai/app/api/routers/style_presets.py
+++ b/invokeai/app/api/routers/style_presets.py
@@@ -121,12 -119,9 +122,12 @@@ async def update_style_preset
except (json.JSONDecodeError, pydantic.ValidationError):
raise HTTPException(status_code=400, detail="Invalid preset data")
- record = _load_record_or_404(style_preset_id)
+ record = await asyncio.to_thread(_load_record_or_404, style_preset_id)
_assert_preset_write(record, current_user)
+ if image is not None and preserve_image:
+ raise HTTPException(status_code=400, detail="Cannot preserve and replace an image in the same request")
+
if image is not None:
if not image.content_type or not image.content_type.startswith("image"):
raise HTTPException(status_code=415, detail="Not an image")
@@@ -140,12 -135,14 +141,14 @@@
raise HTTPException(status_code=415, detail="Failed to read image")
try:
- ApiDependencies.invoker.services.style_preset_image_files.save(style_preset_id, pil_image)
+ await asyncio.to_thread(
+ ApiDependencies.invoker.services.style_preset_image_files.save, style_preset_id, pil_image
+ )
except ValueError as e:
raise HTTPException(status_code=409, detail=str(e))
- else:
+ elif not preserve_image:
try:
- ApiDependencies.invoker.services.style_preset_image_files.delete(style_preset_id)
+ await asyncio.to_thread(ApiDependencies.invoker.services.style_preset_image_files.delete, style_preset_id)
except StylePresetImageFileNotFoundException:
pass
diff --cc invokeai/app/api/routers/videos.py
index 2df76009f6,0604befb25..f943c83d67
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@@ -200,7 -254,19 +200,7 @@@ async def upload_video
raise HTTPException(status_code=422, detail="Metadata must be a JSON object") from e
# Check board access for uploads to a specific board.
- _assert_board_write_access(board_id, current_user)
- if board_id is not None:
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = await run_in_threadpool(ApiDependencies.invoker.services.boards.get_dto, board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if (
- not current_user.is_admin
- and board.user_id != current_user.user_id
- and board.board_visibility != BoardVisibility.Public
- ):
- raise HTTPException(status_code=403, detail="Not authorized to upload to this board")
++ await run_in_threadpool(_assert_board_write_access, board_id, current_user)
if not _is_accepted_video_upload(file):
raise HTTPException(status_code=415, detail="Not a supported video file")
diff --cc invokeai/app/api/routers/wildcards.py
index ed08c76033,0000000000..66b88aa712
mode 100644,000000..100644
--- a/invokeai/app/api/routers/wildcards.py
+++ b/invokeai/app/api/routers/wildcards.py
@@@ -1,90 -1,0 +1,90 @@@
+from fastapi import Body, HTTPException, Path
+from fastapi.routing import APIRouter
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.wildcard_records.wildcard_records_common import (
+ WildcardChanges,
+ WildcardNameConflictError,
+ WildcardNotFoundError,
+ WildcardRecordDTO,
+ WildcardWithoutId,
+)
+
+wildcards_router = APIRouter(prefix="/v1/wildcards", tags=["wildcards"])
+
+
+def _get_owned_wildcard(wildcard_id: str, user_id: str) -> WildcardRecordDTO:
+ """Loads a wildcard, treating someone else's as absent rather than forbidden.
+
+ Answering 403 would confirm the id exists, so a non-owner gets the same 404 as a bad id.
+ """
+ try:
+ wildcard = ApiDependencies.invoker.services.wildcard_records.get(wildcard_id)
+ except WildcardNotFoundError:
+ raise HTTPException(status_code=404, detail="Wildcard not found")
+
+ if wildcard.user_id != user_id:
+ raise HTTPException(status_code=404, detail="Wildcard not found")
+
+ return wildcard
+
+
+@wildcards_router.get(
+ "/",
+ operation_id="list_wildcards",
+ responses={200: {"model": list[WildcardRecordDTO]}},
+)
- async def list_wildcards(current_user: CurrentUserOrDefault) -> list[WildcardRecordDTO]:
++def list_wildcards(current_user: CurrentUserOrDefault) -> list[WildcardRecordDTO]:
+ """Lists the current user's wildcards."""
+ return ApiDependencies.invoker.services.wildcard_records.get_many(user_id=current_user.user_id)
+
+
+@wildcards_router.post(
+ "/",
+ operation_id="create_wildcard",
+ responses={201: {"model": WildcardRecordDTO}},
+ status_code=201,
+)
- async def create_wildcard(
++def create_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard: WildcardWithoutId = Body(description="The wildcard to create"),
+) -> WildcardRecordDTO:
+ """Creates a wildcard owned by the current user."""
+ try:
+ return ApiDependencies.invoker.services.wildcard_records.create(wildcard=wildcard, user_id=current_user.user_id)
+ except WildcardNameConflictError as e:
+ raise HTTPException(status_code=409, detail=str(e))
+
+
+@wildcards_router.patch(
+ "/{wildcard_id}",
+ operation_id="update_wildcard",
+ responses={200: {"model": WildcardRecordDTO}},
+)
- async def update_wildcard(
++def update_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard_id: str = Path(description="The id of the wildcard to update"),
+ changes: WildcardChanges = Body(description="The changes to apply"),
+) -> WildcardRecordDTO:
+ """Updates a wildcard owned by the current user."""
+ _get_owned_wildcard(wildcard_id, current_user.user_id)
+
+ try:
+ return ApiDependencies.invoker.services.wildcard_records.update(wildcard_id=wildcard_id, changes=changes)
+ except WildcardNameConflictError as e:
+ raise HTTPException(status_code=409, detail=str(e))
+
+
+@wildcards_router.delete(
+ "/{wildcard_id}",
+ operation_id="delete_wildcard",
+ status_code=204,
+)
- async def delete_wildcard(
++def delete_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard_id: str = Path(description="The id of the wildcard to delete"),
+) -> None:
+ """Deletes a wildcard owned by the current user."""
+ _get_owned_wildcard(wildcard_id, current_user.user_id)
+ ApiDependencies.invoker.services.wildcard_records.delete(wildcard_id)
diff --cc invokeai/app/api/routers/workflows.py
index feefa0a176,110fa01b25..93e44bcd02
--- a/invokeai/app/api/routers/workflows.py
+++ b/invokeai/app/api/routers/workflows.py
@@@ -477,26 -478,3 +478,26 @@@ def update_opened_at
user_id = None if current_user.is_admin else current_user.user_id
ApiDependencies.invoker.services.workflow_records.update_opened_at(workflow_id, user_id=user_id)
+
+
+@workflows_router.put(
+ "/i/{workflow_id}/last_run_at",
+ operation_id="update_workflow_last_run_at",
+ status_code=204,
+)
- async def update_workflow_last_run_at(
++def update_workflow_last_run_at(
+ current_user: CurrentUserOrDefault,
+ workflow_id: str = Path(description="The workflow to update"),
+) -> None:
+ """Updates the last_run_at field of a workflow"""
+ try:
+ existing = ApiDependencies.invoker.services.workflow_records.get(workflow_id)
+ except WorkflowNotFoundError:
+ raise HTTPException(status_code=404, detail="Workflow not found")
+
+ config = ApiDependencies.invoker.services.configuration
+ if config.multiuser and not current_user.is_admin and existing.user_id != current_user.user_id:
+ raise HTTPException(status_code=403, detail="Not authorized to update this workflow")
+
+ user_id = None if current_user.is_admin else current_user.user_id
+ ApiDependencies.invoker.services.workflow_records.update_last_run_at(workflow_id, user_id=user_id)
diff --cc invokeai/app/api/sockets.py
index 1e1327e17e,6dd6ab2382..8f7615643a
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@@ -108,19 -122,8 +128,20 @@@ MODEL_EVENTS =
BULK_DOWNLOAD_EVENTS = {BulkDownloadStartedEvent, BulkDownloadCompleteEvent, BulkDownloadErrorEvent}
WORKFLOW_EVENTS = {WorkflowCreatedEvent, WorkflowUpdatedEvent, WorkflowDeletedEvent}
+ USER_EVENTS = {UserAccessChangedEvent}
+IMAGE_INDEX_EVENTS = {ImageIndexStatusEvent, ImageIndexUpdatedEvent, ImageMapProjectionReadyEvent}
+
+MODEL_INSTALL_EVENTS = (
+ ModelInstallDownloadStartedEvent,
+ ModelInstallDownloadProgressEvent,
+ ModelInstallDownloadsCompleteEvent,
+ ModelInstallStartedEvent,
+ ModelInstallCompleteEvent,
+ ModelInstallCancelledEvent,
+ ModelInstallErrorEvent,
+)
+
LLM_TASK_EVENTS = {LLMTaskProgressEvent, LLMTaskCompleteEvent, LLMTaskErrorEvent}
@@@ -160,7 -172,7 +190,8 @@@ class SocketIO
register_events(BULK_DOWNLOAD_EVENTS, self._handle_bulk_image_download_event)
register_events(LLM_TASK_EVENTS, self._handle_llm_task_event)
register_events(WORKFLOW_EVENTS, self._handle_workflow_event)
+ register_events(IMAGE_INDEX_EVENTS, self._handle_image_index_event)
+ register_events(USER_EVENTS, self._handle_user_access_changed)
async def _handle_connect(self, sid: str, environ: dict, auth: dict | None) -> bool:
"""Handle socket connection and authenticate the user.
diff --cc invokeai/app/services/events/events_common.py
index 47f604da92,1a0f91b766..353c2e026c
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@@ -875,61 -883,29 +883,89 @@@ class RecallParametersUpdatedEvent(Queu
return cls(queue_id=queue_id, user_id=user_id, parameters=parameters)
+class ImageIndexEventBase(EventBase):
+ """Base class for image index events"""
+
+
+@payload_schema.register
+class ImageIndexStatusEvent(ImageIndexEventBase):
+ """Event model for image_index_status"""
+
+ __event_name__ = "image_index_status"
+
+ total: int = Field(description="Number of gallery images eligible for embedding")
+ embedded: int = Field(description="Number of eligible images that have an embedding")
+ pending: int = Field(description="Number of eligible images awaiting embedding")
+ failed: int = Field(
+ default=0,
+ description=(
+ "Eligible images that repeatedly failed to embed and were given up on. Excluded from "
+ "`pending`, so `total != embedded` with `pending == 0` means this many were skipped."
+ ),
+ )
+
+ @classmethod
+ def build(cls, total: int, embedded: int, pending: int, failed: int = 0) -> "ImageIndexStatusEvent":
+ return cls(total=total, embedded=embedded, pending=pending, failed=failed)
+
+
+@payload_schema.register
+class ImageIndexUpdatedEvent(ImageIndexEventBase):
+ """Event model for image_index_updated.
+
+ A counts-free poke to one user whose images were just (re)embedded, so
+ their client can refresh views built on the index. Kept separate from
+ ImageIndexStatusEvent because the counts aggregate every user's images
+ and are therefore admin-only, while this event is safe to route to the
+ owning user's room.
+ """
+
+ __event_name__ = "image_index_updated"
+
+ user_id: str = Field(description="The user whose images were embedded")
+
+ @classmethod
+ def build(cls, user_id: str) -> "ImageIndexUpdatedEvent":
+ return cls(user_id=user_id)
+
+
+@payload_schema.register
+class ImageMapProjectionReadyEvent(ImageIndexEventBase):
+ """Event model for image_map_projection_ready"""
+
+ __event_name__ = "image_map_projection_ready"
+
+ user_id: str = Field(description="The user whose image map projection was recomputed")
+ point_count: int = Field(description="Number of points in the recomputed projection")
+
+ @classmethod
+ def build(cls, user_id: str, point_count: int) -> "ImageMapProjectionReadyEvent":
+ return cls(user_id=user_id, point_count=point_count)
++
++
+ class UserAccessChangedEvent(EventBase):
+ """Event model for user_access_changed.
+
+ Emitted when a user's authorization state changes (role change, deactivation,
+ or deletion) so that live connections — e.g. open sockets — can be re-authorized
+ immediately instead of trusting connect-time claims until reconnect.
+
+ This event is server-internal: it is deliberately NOT registered with
+ `payload_schema`, is excluded from the generated API schema, and is never
+ emitted to clients.
+ """
+
+ __event_name__ = "user_access_changed"
+ __server_internal__ = True
+
+ user_id: str = Field(description="The ID of the affected user")
+ is_admin: bool = Field(description="Whether the user currently has admin privileges")
+ is_active: bool = Field(description="Whether the user account is currently active (False for deleted users)")
+ token_epoch: int = Field(
+ default=0,
+ description="The user's current token revocation epoch; sockets that authenticated under an older one are dropped",
+ )
+
+ @classmethod
+ def build(cls, user_id: str, is_admin: bool, is_active: bool, token_epoch: int = 0) -> "UserAccessChangedEvent":
+ return cls(user_id=user_id, is_admin=is_admin, is_active=is_active, token_epoch=token_epoch)
diff --cc invokeai/app/services/gallery/gallery_base.py
index 1366308a53,a2679aba7a..608425fefd
--- a/invokeai/app/services/gallery/gallery_base.py
+++ b/invokeai/app/services/gallery/gallery_base.py
@@@ -49,10 -50,29 +54,33 @@@ class GalleryServiceABC(ABC)
) -> GalleryItemNamesResult:
"""Returns ordered (kind, name) refs for optimistic UI / virtualized lists.
+ Deprecated — use :meth:`get_item_names`, which returns the same order without building
+ a model per row.
+ """
+ pass
+
+ @abstractmethod
+ def get_item_names(
+ self,
+ starred_first: bool = True,
+ order_dir: SQLiteDirection = SQLiteDirection.Descending,
+ origin: Optional[ResourceOrigin] = None,
+ categories: Optional[list[ImageCategory]] = None,
+ is_intermediate: Optional[bool] = None,
+ board_id: Optional[str] = None,
+ search_term: Optional[str] = None,
+ user_id: Optional[str] = None,
+ is_admin: bool = False,
+ created_date: Optional[str] = None,
++ created_from: Optional[str] = None,
++ created_to: Optional[str] = None,
+ ) -> GalleryItemNames:
+ """Returns the ordered flat name list for optimistic UI / virtualized lists.
+
`created_date` restricts the result to items created on the given ISO date — used by
date-based virtual boards.
+
+ `created_from` and `created_to` are inclusive YYYY-MM-DD bounds on created_at (UTC days).
"""
pass
diff --cc invokeai/app/services/gallery/gallery_default.py
index c5f39feb25,0fdeaca48c..6f7c475587
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@@ -106,21 -101,24 +107,26 @@@ class SqliteGalleryService(GalleryServi
total=image_count + video_count,
)
- def list_item_names(
+ def _query_name_rows(
self,
- starred_first: bool = True,
- order_dir: SQLiteDirection = SQLiteDirection.Descending,
- origin: Optional[ResourceOrigin] = None,
- categories: Optional[list[ImageCategory]] = None,
- is_intermediate: Optional[bool] = None,
- board_id: Optional[str] = None,
- search_term: Optional[str] = None,
- user_id: Optional[str] = None,
- is_admin: bool = False,
- created_date: Optional[str] = None,
- created_from: Optional[str] = None,
- created_to: Optional[str] = None,
- ) -> GalleryItemNamesResult:
+ starred_first: bool,
+ order_dir: SQLiteDirection,
+ origin: Optional[ResourceOrigin],
+ categories: Optional[list[ImageCategory]],
+ is_intermediate: Optional[bool],
+ board_id: Optional[str],
+ search_term: Optional[str],
+ user_id: Optional[str],
+ is_admin: bool,
+ created_date: Optional[str],
++ created_from: Optional[str],
++ created_to: Optional[str],
+ ) -> tuple[list[sqlite3.Row], int]:
+ """Runs the ordered name query and returns its rows plus the starred count.
+
+ Shared by both name-list shapes so the deprecated `(kind, name)` variant and the flat
+ one can never drift apart in ordering or filtering.
+ """
image_half, image_params, _ = self._build_half(
kind="image",
origin=origin,
@@@ -170,9 -164,66 +176,74 @@@
if starred_first:
starred_count = sum(1 for r in rows if r["starred"])
+ return rows, starred_count
+
+ def list_item_names(
+ self,
+ starred_first: bool = True,
+ order_dir: SQLiteDirection = SQLiteDirection.Descending,
+ origin: Optional[ResourceOrigin] = None,
+ categories: Optional[list[ImageCategory]] = None,
+ is_intermediate: Optional[bool] = None,
+ board_id: Optional[str] = None,
+ search_term: Optional[str] = None,
+ user_id: Optional[str] = None,
+ is_admin: bool = False,
+ created_date: Optional[str] = None,
++ created_from: Optional[str] = None,
++ created_to: Optional[str] = None,
+ ) -> GalleryItemNamesResult:
+ rows, starred_count = self._query_name_rows(
+ starred_first=starred_first,
+ order_dir=order_dir,
+ origin=origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ user_id=user_id,
+ is_admin=is_admin,
+ created_date=created_date,
++ created_from=created_from,
++ created_to=created_to,
+ )
refs = [GalleryItemRef(kind=GalleryItemKind(row["kind"]), name=row["name"]) for row in rows]
return GalleryItemNamesResult(items=refs, starred_count=starred_count, total_count=len(refs))
+ def get_item_names(
+ self,
+ starred_first: bool = True,
+ order_dir: SQLiteDirection = SQLiteDirection.Descending,
+ origin: Optional[ResourceOrigin] = None,
+ categories: Optional[list[ImageCategory]] = None,
+ is_intermediate: Optional[bool] = None,
+ board_id: Optional[str] = None,
+ search_term: Optional[str] = None,
+ user_id: Optional[str] = None,
+ is_admin: bool = False,
+ created_date: Optional[str] = None,
++ created_from: Optional[str] = None,
++ created_to: Optional[str] = None,
+ ) -> GalleryItemNames:
+ rows, starred_count = self._query_name_rows(
+ starred_first=starred_first,
+ order_dir=order_dir,
+ origin=origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ user_id=user_id,
+ is_admin=is_admin,
+ created_date=created_date,
++ created_from=created_from,
++ created_to=created_to,
+ )
+ # A list comprehension over the raw column, deliberately: building one model per row
+ # is what made the deprecated variant expensive.
+ names = [row["name"] for row in rows]
+ return GalleryItemNames(item_names=names, starred_count=starred_count, total_count=len(names))
+
def get_dates(
self,
user_id: Optional[str] = None,
diff --cc invokeai/frontend/web/openapi.json
index 0a873b455f,6de4b71d54..53d717d319
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@@ -5966,90 -6027,14 +5978,91 @@@
],
"parameters": [
{
- "name": "video_category",
- "in": "query",
+ "name": "bulk_download_item_name",
+ "in": "path",
"required": true,
"schema": {
- "$ref": "#/components/schemas/ImageCategory",
- "description": "The category of the video"
+ "type": "string",
+ "description": "The bulk_download_item_name of the bulk download item to get",
+ "title": "Bulk Download Item Name"
},
- "description": "The category of the video"
+ "description": "The bulk_download_item_name of the bulk download item to get"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Return the complete bulk download item",
+ "content": {
+ "application/zip": {}
+ }
+ },
+ "404": {
+ "description": "Image not found"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/images/names": {
+ "get": {
+ "tags": ["images"],
+ "summary": "Get Image Names",
- "description": "Gets ordered list of image names with metadata for optimistic updates",
++ "description": "Gets ordered list of image names with metadata for optimistic updates.\n\nDeprecated: use `GET /v1/gallery/item_names`, which returns images and videos interleaved\nin one ordered list. This image-only endpoint predates the polymorphic gallery.",
+ "operationId": "get_image_names",
++ "deprecated": true,
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "image_origin",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ResourceOrigin"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The origin of images to list.",
+ "title": "Image Origin"
+ },
+ "description": "The origin of images to list."
+ },
+ {
+ "name": "categories",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ImageCategory"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The categories of image to include.",
+ "title": "Categories"
+ },
+ "description": "The categories of image to include."
},
{
"name": "is_intermediate",
@@@ -8050,6 -7369,177 +8064,215 @@@
}
}
},
+ "/api/v1/gallery/item_names": {
+ "get": {
+ "tags": ["gallery"],
+ "summary": "List Gallery Item Names",
+ "description": "Returns the ordered flat list of item names \u2014 used to drive virtualized gallery selection.\n\nNames are polymorphic: image and video names are interleaved by `created_at`. A name ending\nin `.mp4` is a video.",
+ "operationId": "list_gallery_item_names",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "origin",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ResourceOrigin"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The origin of items to list.",
+ "title": "Origin"
+ },
+ "description": "The origin of items to list."
+ },
+ {
+ "name": "categories",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ImageCategory"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The categories to include. Shared between images and videos.",
+ "title": "Categories"
+ },
+ "description": "The categories to include. Shared between images and videos."
+ },
+ {
+ "name": "is_intermediate",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Whether to list intermediate items.",
+ "title": "Is Intermediate"
+ },
+ "description": "Whether to list intermediate items."
+ },
+ {
+ "name": "board_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The board id to filter by. Use 'none' to find items without a board.",
+ "title": "Board Id"
+ },
+ "description": "The board id to filter by. Use 'none' to find items without a board."
+ },
+ {
+ "name": "created_date",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards.",
+ "title": "Created Date"
+ },
+ "description": "Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards."
+ },
++ {
++ "name": "created_from",
++ "in": "query",
++ "required": false,
++ "schema": {
++ "anyOf": [
++ {
++ "type": "string",
++ "format": "date"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at.",
++ "title": "Created From"
++ },
++ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at."
++ },
++ {
++ "name": "created_to",
++ "in": "query",
++ "required": false,
++ "schema": {
++ "anyOf": [
++ {
++ "type": "string",
++ "format": "date"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at.",
++ "title": "Created To"
++ },
++ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at."
++ },
+ {
+ "name": "order_dir",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/SQLiteDirection",
+ "description": "The order of sort",
+ "default": "DESC"
+ },
+ "description": "The order of sort"
+ },
+ {
+ "name": "starred_first",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "description": "Whether to sort by starred items first",
+ "default": true,
+ "title": "Starred First"
+ },
+ "description": "Whether to sort by starred items first"
+ },
+ {
+ "name": "search_term",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The term to search for",
+ "title": "Search Term"
+ },
+ "description": "The term to search for"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryItemNames"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/gallery/items/names": {
"get": {
"tags": ["gallery"],
@@@ -17213,25 -16117,6 +17518,25 @@@
"required": ["video_name"],
"title": "Body_remove_video_from_board"
},
+ "Body_search_image_map_by_image": {
+ "properties": {
+ "image": {
+ "anyOf": [
+ {
+ "type": "string",
- "format": "binary"
++ "contentMediaType": "application/octet-stream"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Image",
+ "description": "Reference image file"
+ }
+ },
+ "type": "object",
+ "title": "Body_search_image_map_by_image"
+ },
"Body_set_workflow_thumbnail": {
"properties": {
"image": {
@@@ -51435,7 -49503,7 +51774,7 @@@
"additionalProperties": false,
"type": "object",
"title": "InvokeAIAppConfig",
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set."
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
++ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
@@@ -64569,237 -62502,395 +64908,755 @@@
"default": "sdnq_quantized"
},
"variant": {
- "$ref": "#/components/schemas/ZImageVariantType"
+ "$ref": "#/components/schemas/FluxVariantType"
- },
- "repo_variant": {
- "$ref": "#/components/schemas/ModelRepoVariant",
- "default": ""
- },
- "submodels": {
- "anyOf": [
- {
- "additionalProperties": {
- "$ref": "#/components/schemas/SubmodelDefinition"
- },
- "propertyNames": {
- "$ref": "#/components/schemas/SubModelType"
- },
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "title": "Submodels",
- "description": "Loadable submodels in this model"
+ },
+ "repo_variant": {
+ "$ref": "#/components/schemas/ModelRepoVariant",
+ "default": ""
+ },
+ "submodels": {
+ "anyOf": [
+ {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/SubmodelDefinition"
+ },
+ "propertyNames": {
+ "$ref": "#/components/schemas/SubModelType"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Submodels",
+ "description": "Loadable submodels in this model"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
+ "type",
+ "trigger_phrases",
+ "default_settings",
+ "base",
+ "format",
+ "variant",
+ "repo_variant",
+ "submodels"
+ ],
- "title": "Main_SDNQ_Diffusers_ZImage_Config",
- "description": "Model config for SDNQ-quantized Z-Image models in diffusers format (full ZImagePipeline folder)."
++ "title": "Main_SDNQ_Diffusers_FLUX_Config",
++ "description": "Model config for SDNQ-quantized FLUX models in diffusers format (folder with transformer, text_encoder, etc.)."
+ },
- "Main_SDNQ_FLUX_Config": {
++ "Main_SDNQ_Diffusers_Flux2_Config": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key",
+ "description": "A unique key for this model."
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The hash of the model file(s)."
+ },
+ "path": {
+ "type": "string",
+ "title": "Path",
+ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
+ },
+ "file_size": {
+ "type": "integer",
+ "title": "File Size",
+ "description": "The size of the model in bytes."
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "Name of the model."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description",
+ "description": "Model description"
+ },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "The original source of the model (path, URL or repo_id)."
+ },
+ "source_type": {
+ "$ref": "#/components/schemas/ModelSourceType",
+ "description": "The type of source"
+ },
+ "source_api_response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Api Response",
+ "description": "The original API response from the source, as stringified JSON."
+ },
+ "source_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Url",
+ "description": "Optional URL for the model (e.g. download page or model page)."
+ },
+ "cover_image": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image",
+ "description": "Url for image to preview model"
+ },
+ "type": {
+ "type": "string",
+ "const": "main",
+ "title": "Type",
+ "default": "main"
+ },
+ "trigger_phrases": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "uniqueItems": true
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Trigger Phrases",
+ "description": "Set of trigger phrases for this model"
+ },
+ "default_settings": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/MainModelDefaultSettings"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Default settings for this model"
+ },
- "config_path": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Config Path",
- "description": "Path to the config for this model, if any."
- },
+ "base": {
+ "type": "string",
- "const": "flux",
++ "const": "flux2",
+ "title": "Base",
- "default": "flux"
++ "default": "flux2"
+ },
+ "format": {
+ "type": "string",
+ "const": "sdnq_quantized",
+ "title": "Format",
+ "default": "sdnq_quantized"
+ },
+ "variant": {
- "$ref": "#/components/schemas/FluxVariantType"
++ "$ref": "#/components/schemas/Flux2VariantType"
++ },
++ "repo_variant": {
++ "$ref": "#/components/schemas/ModelRepoVariant",
++ "default": ""
++ },
++ "submodels": {
++ "anyOf": [
++ {
++ "additionalProperties": {
++ "$ref": "#/components/schemas/SubmodelDefinition"
++ },
++ "propertyNames": {
++ "$ref": "#/components/schemas/SubModelType"
++ },
++ "type": "object"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Submodels",
++ "description": "Loadable submodels in this model"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
+ "type",
+ "trigger_phrases",
+ "default_settings",
- "config_path",
+ "base",
+ "format",
- "variant"
++ "variant",
++ "repo_variant",
++ "submodels"
+ ],
- "title": "Main_SDNQ_FLUX_Config",
- "description": "Model config for SDNQ-quantized FLUX transformer models."
++ "title": "Main_SDNQ_Diffusers_Flux2_Config",
++ "description": "Model config for SDNQ-quantized FLUX.2 models in diffusers format\n(Flux2KleinPipeline / Flux2Pipeline folder with transformer/, text_encoder/, vae/, ...)."
+ },
- "Main_SDNQ_Flux2_Config": {
++ "Main_SDNQ_Diffusers_ZImage_Config": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key",
+ "description": "A unique key for this model."
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The hash of the model file(s)."
+ },
+ "path": {
+ "type": "string",
+ "title": "Path",
+ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
+ },
+ "file_size": {
+ "type": "integer",
+ "title": "File Size",
+ "description": "The size of the model in bytes."
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "Name of the model."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description",
+ "description": "Model description"
+ },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "The original source of the model (path, URL or repo_id)."
+ },
+ "source_type": {
+ "$ref": "#/components/schemas/ModelSourceType",
+ "description": "The type of source"
+ },
+ "source_api_response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Api Response",
+ "description": "The original API response from the source, as stringified JSON."
+ },
+ "source_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Url",
+ "description": "Optional URL for the model (e.g. download page or model page)."
+ },
+ "cover_image": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image",
+ "description": "Url for image to preview model"
+ },
+ "type": {
+ "type": "string",
+ "const": "main",
+ "title": "Type",
+ "default": "main"
+ },
+ "trigger_phrases": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "uniqueItems": true
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Trigger Phrases",
+ "description": "Set of trigger phrases for this model"
+ },
+ "default_settings": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/MainModelDefaultSettings"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Default settings for this model"
+ },
- "config_path": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Config Path",
- "description": "Path to the config for this model, if any."
- },
+ "base": {
+ "type": "string",
- "const": "flux2",
++ "const": "z-image",
+ "title": "Base",
- "default": "flux2"
++ "default": "z-image"
+ },
+ "format": {
+ "type": "string",
+ "const": "sdnq_quantized",
+ "title": "Format",
+ "default": "sdnq_quantized"
+ },
+ "variant": {
- "$ref": "#/components/schemas/Flux2VariantType"
++ "$ref": "#/components/schemas/ZImageVariantType"
++ },
++ "repo_variant": {
++ "$ref": "#/components/schemas/ModelRepoVariant",
++ "default": ""
++ },
++ "submodels": {
++ "anyOf": [
++ {
++ "additionalProperties": {
++ "$ref": "#/components/schemas/SubmodelDefinition"
++ },
++ "propertyNames": {
++ "$ref": "#/components/schemas/SubModelType"
++ },
++ "type": "object"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Submodels",
++ "description": "Loadable submodels in this model"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
+ "type",
+ "trigger_phrases",
+ "default_settings",
- "config_path",
+ "base",
+ "format",
- "variant"
++ "variant",
++ "repo_variant",
++ "submodels"
+ ],
- "title": "Main_SDNQ_Flux2_Config",
- "description": "Model config for SDNQ-quantized FLUX.2 transformer models (e.g. Klein 4B / 9B)."
++ "title": "Main_SDNQ_Diffusers_ZImage_Config",
++ "description": "Model config for SDNQ-quantized Z-Image models in diffusers format (full ZImagePipeline folder)."
+ },
- "Main_SDNQ_ZImage_Config": {
++ "Main_SDNQ_FLUX_Config": {
++ "properties": {
++ "key": {
++ "type": "string",
++ "title": "Key",
++ "description": "A unique key for this model."
++ },
++ "hash": {
++ "type": "string",
++ "title": "Hash",
++ "description": "The hash of the model file(s)."
++ },
++ "path": {
++ "type": "string",
++ "title": "Path",
++ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
++ },
++ "file_size": {
++ "type": "integer",
++ "title": "File Size",
++ "description": "The size of the model in bytes."
++ },
++ "name": {
++ "type": "string",
++ "title": "Name",
++ "description": "Name of the model."
++ },
++ "description": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Description",
++ "description": "Model description"
++ },
++ "source": {
++ "type": "string",
++ "title": "Source",
++ "description": "The original source of the model (path, URL or repo_id)."
++ },
++ "source_type": {
++ "$ref": "#/components/schemas/ModelSourceType",
++ "description": "The type of source"
++ },
++ "source_api_response": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Source Api Response",
++ "description": "The original API response from the source, as stringified JSON."
++ },
++ "source_url": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Source Url",
++ "description": "Optional URL for the model (e.g. download page or model page)."
++ },
++ "cover_image": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Cover Image",
++ "description": "Url for image to preview model"
++ },
++ "type": {
++ "type": "string",
++ "const": "main",
++ "title": "Type",
++ "default": "main"
++ },
++ "trigger_phrases": {
++ "anyOf": [
++ {
++ "items": {
++ "type": "string"
++ },
++ "type": "array",
++ "uniqueItems": true
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Trigger Phrases",
++ "description": "Set of trigger phrases for this model"
++ },
++ "default_settings": {
++ "anyOf": [
++ {
++ "$ref": "#/components/schemas/MainModelDefaultSettings"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "description": "Default settings for this model"
++ },
++ "config_path": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Config Path",
++ "description": "Path to the config for this model, if any."
++ },
++ "base": {
++ "type": "string",
++ "const": "flux",
++ "title": "Base",
++ "default": "flux"
++ },
++ "format": {
++ "type": "string",
++ "const": "sdnq_quantized",
++ "title": "Format",
++ "default": "sdnq_quantized"
++ },
++ "variant": {
++ "$ref": "#/components/schemas/FluxVariantType"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
+ "type",
+ "trigger_phrases",
+ "default_settings",
++ "config_path",
+ "base",
+ "format",
- "variant",
- "repo_variant",
- "submodels"
++ "variant"
+ ],
- "title": "Main_SDNQ_Diffusers_FLUX_Config",
- "description": "Model config for SDNQ-quantized FLUX models in diffusers format (folder with transformer, text_encoder, etc.)."
++ "title": "Main_SDNQ_FLUX_Config",
++ "description": "Model config for SDNQ-quantized FLUX transformer models."
+ },
- "Main_SDNQ_Diffusers_Flux2_Config": {
++ "Main_SDNQ_Flux2_Config": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key",
+ "description": "A unique key for this model."
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The hash of the model file(s)."
+ },
+ "path": {
+ "type": "string",
+ "title": "Path",
+ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
+ },
+ "file_size": {
+ "type": "integer",
+ "title": "File Size",
+ "description": "The size of the model in bytes."
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "Name of the model."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description",
+ "description": "Model description"
+ },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "The original source of the model (path, URL or repo_id)."
+ },
+ "source_type": {
+ "$ref": "#/components/schemas/ModelSourceType",
+ "description": "The type of source"
+ },
+ "source_api_response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Api Response",
+ "description": "The original API response from the source, as stringified JSON."
+ },
+ "source_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Url",
+ "description": "Optional URL for the model (e.g. download page or model page)."
+ },
+ "cover_image": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image",
+ "description": "Url for image to preview model"
+ },
+ "type": {
+ "type": "string",
+ "const": "main",
+ "title": "Type",
+ "default": "main"
+ },
+ "trigger_phrases": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "uniqueItems": true
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Trigger Phrases",
+ "description": "Set of trigger phrases for this model"
+ },
+ "default_settings": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/MainModelDefaultSettings"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Default settings for this model"
+ },
++ "config_path": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Config Path",
++ "description": "Path to the config for this model, if any."
++ },
+ "base": {
+ "type": "string",
+ "const": "flux2",
+ "title": "Base",
+ "default": "flux2"
+ },
+ "format": {
+ "type": "string",
+ "const": "sdnq_quantized",
+ "title": "Format",
+ "default": "sdnq_quantized"
+ },
+ "variant": {
+ "$ref": "#/components/schemas/Flux2VariantType"
- },
- "repo_variant": {
- "$ref": "#/components/schemas/ModelRepoVariant",
- "default": ""
- },
- "submodels": {
- "anyOf": [
- {
- "additionalProperties": {
- "$ref": "#/components/schemas/SubmodelDefinition"
- },
- "propertyNames": {
- "$ref": "#/components/schemas/SubModelType"
- },
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "title": "Submodels",
- "description": "Loadable submodels in this model"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
+ "type",
+ "trigger_phrases",
+ "default_settings",
++ "config_path",
+ "base",
+ "format",
- "variant",
- "repo_variant",
- "submodels"
++ "variant"
+ ],
- "title": "Main_SDNQ_Diffusers_Flux2_Config",
- "description": "Model config for SDNQ-quantized FLUX.2 models in diffusers format\n(Flux2KleinPipeline / Flux2Pipeline folder with transformer/, text_encoder/, vae/, ...)."
++ "title": "Main_SDNQ_Flux2_Config",
++ "description": "Model config for SDNQ-quantized FLUX.2 transformer models (e.g. Klein 4B / 9B)."
+ },
- "Main_SDNQ_Diffusers_ZImage_Config": {
++ "Main_SDNQ_ZImage_Config": {
"properties": {
"key": {
"type": "string",
@@@ -77246,164 -73635,164 +78092,305 @@@
"cpu_only",
"variant"
],
- "title": "Qwen3Encoder_Checkpoint_Config",
- "description": "Configuration for single-file Qwen3 Encoder models (safetensors)."
+ "title": "Qwen3Encoder_Checkpoint_Config",
+ "description": "Configuration for single-file Qwen3 Encoder models (safetensors)."
+ },
+ "Qwen3Encoder_GGUF_Config": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key",
+ "description": "A unique key for this model."
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The hash of the model file(s)."
+ },
+ "path": {
+ "type": "string",
+ "title": "Path",
+ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
+ },
+ "file_size": {
+ "type": "integer",
+ "title": "File Size",
+ "description": "The size of the model in bytes."
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "Name of the model."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description",
+ "description": "Model description"
+ },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "The original source of the model (path, URL or repo_id)."
+ },
+ "source_type": {
+ "$ref": "#/components/schemas/ModelSourceType",
+ "description": "The type of source"
+ },
+ "source_api_response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Api Response",
+ "description": "The original API response from the source, as stringified JSON."
+ },
+ "source_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Url",
+ "description": "Optional URL for the model (e.g. download page or model page)."
+ },
+ "cover_image": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image",
+ "description": "Url for image to preview model"
+ },
+ "config_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Config Path",
+ "description": "Path to the config for this model, if any."
+ },
+ "base": {
+ "type": "string",
+ "const": "any",
+ "title": "Base",
+ "default": "any"
+ },
+ "type": {
+ "type": "string",
+ "const": "qwen3_encoder",
+ "title": "Type",
+ "default": "qwen3_encoder"
+ },
+ "format": {
+ "type": "string",
+ "const": "gguf_quantized",
+ "title": "Format",
+ "default": "gguf_quantized"
+ },
+ "cpu_only": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cpu Only",
+ "description": "Whether this model should run on CPU only"
+ },
+ "variant": {
+ "$ref": "#/components/schemas/Qwen3VariantType",
+ "description": "Qwen3 model size variant (4B or 8B)"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
- "config_path",
++ "config_path",
++ "base",
++ "type",
++ "format",
++ "cpu_only",
++ "variant"
++ ],
++ "title": "Qwen3Encoder_GGUF_Config",
++ "description": "Configuration for GGUF-quantized Qwen3 Encoder models."
+ },
- "Qwen3Encoder_GGUF_Config": {
++ "Qwen3Encoder_Qwen3Encoder_Config": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key",
+ "description": "A unique key for this model."
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The hash of the model file(s)."
+ },
+ "path": {
+ "type": "string",
+ "title": "Path",
+ "description": "Path to the model on the filesystem. Relative paths are relative to the Invoke root directory."
+ },
+ "file_size": {
+ "type": "integer",
+ "title": "File Size",
+ "description": "The size of the model in bytes."
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "Name of the model."
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description",
+ "description": "Model description"
+ },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "The original source of the model (path, URL or repo_id)."
+ },
+ "source_type": {
+ "$ref": "#/components/schemas/ModelSourceType",
+ "description": "The type of source"
+ },
+ "source_api_response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Api Response",
+ "description": "The original API response from the source, as stringified JSON."
+ },
+ "source_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Source Url",
+ "description": "Optional URL for the model (e.g. download page or model page)."
+ },
+ "cover_image": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cover Image",
+ "description": "Url for image to preview model"
+ },
- "config_path": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Config Path",
- "description": "Path to the config for this model, if any."
- },
+ "base": {
+ "type": "string",
+ "const": "any",
+ "title": "Base",
+ "default": "any"
+ },
+ "type": {
+ "type": "string",
+ "const": "qwen3_encoder",
+ "title": "Type",
+ "default": "qwen3_encoder"
+ },
+ "format": {
+ "type": "string",
- "const": "gguf_quantized",
++ "const": "qwen3_encoder",
+ "title": "Format",
- "default": "gguf_quantized"
++ "default": "qwen3_encoder"
+ },
+ "cpu_only": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cpu Only",
+ "description": "Whether this model should run on CPU only"
+ },
+ "variant": {
+ "$ref": "#/components/schemas/Qwen3VariantType",
+ "description": "Qwen3 model size variant (4B or 8B)"
+ }
+ },
+ "type": "object",
+ "required": [
+ "key",
+ "hash",
+ "path",
+ "file_size",
+ "name",
+ "description",
+ "source",
+ "source_type",
+ "source_api_response",
+ "source_url",
+ "cover_image",
- "config_path",
"base",
"type",
"format",
"cpu_only",
"variant"
],
-- "title": "Qwen3Encoder_GGUF_Config",
-- "description": "Configuration for GGUF-quantized Qwen3 Encoder models."
++ "title": "Qwen3Encoder_Qwen3Encoder_Config",
++ "description": "Configuration for Qwen3 Encoder models in a diffusers-like format.\n\nThe model weights are expected to be in a folder called text_encoder inside the model directory,\ncompatible with Qwen2VLForConditionalGeneration or similar architectures used by Z-Image."
},
-- "Qwen3Encoder_Qwen3Encoder_Config": {
++ "Qwen3Encoder_SDNQ_Config": {
"properties": {
"key": {
"type": "string",
@@@ -77487,6 -73876,6 +78474,18 @@@
"title": "Cover Image",
"description": "Url for image to preview model"
},
++ "config_path": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "title": "Config Path",
++ "description": "Path to the config for this model, if any."
++ },
"base": {
"type": "string",
"const": "any",
@@@ -77501,9 -73890,9 +78500,9 @@@
},
"format": {
"type": "string",
-- "const": "qwen3_encoder",
++ "const": "sdnq_quantized",
"title": "Format",
-- "default": "qwen3_encoder"
++ "default": "sdnq_quantized"
},
"cpu_only": {
"anyOf": [
@@@ -77535,16 -73924,16 +78534,17 @@@
"source_api_response",
"source_url",
"cover_image",
++ "config_path",
"base",
"type",
"format",
"cpu_only",
"variant"
],
-- "title": "Qwen3Encoder_Qwen3Encoder_Config",
-- "description": "Configuration for Qwen3 Encoder models in a diffusers-like format.\n\nThe model weights are expected to be in a folder called text_encoder inside the model directory,\ncompatible with Qwen2VLForConditionalGeneration or similar architectures used by Z-Image."
++ "title": "Qwen3Encoder_SDNQ_Config",
++ "description": "Configuration for SDNQ-quantized Qwen3 Encoder models (single file)."
},
- "Qwen3Encoder_SDNQ_Config": {
+ "Qwen3Encoder_SDNQ_Folder_Config": {
"properties": {
"key": {
"type": "string",
diff --cc invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts
index 945fd1702c,9a22e8cc32..9078b0262c
--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts
+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts
@@@ -11,32 -11,3 +11,32 @@@ describe('CurrentVideoPreview playback
expect(source).toContain('onError={handleVideoError}');
});
});
+
+describe('CurrentVideoPreview progress overlay', () => {
+ const source = readFileSync(fileURLToPath(new URL('./CurrentVideoPreview.tsx', import.meta.url)), 'utf8');
+
+ it('lifts the overlay during the temporary reveal so mid-render thumbnail clicks visibly land', () => {
+ // The overlay must consult the shared reveal atom (and never re-cover an actively-playing
+ // video) — an unconditional overlay swallows every gallery click for the whole render.
+ expect(source).toMatch(
+ /withProgress =\s+shouldShowProgressInViewer && hasProgressImage && !isTemporarilyShowingSelectedImage && !isPlaying/
+ );
+ expect(source).toContain('SELECTED_ITEM_REVEAL_DURATION_MS');
+ // The previous-item ref must be the shared one from the viewer context, so image -> video
+ // clicks still read as a selection change after the preview component swaps.
+ expect(source).toContain('lastRenderedItemNameRef.current = videoName');
+ });
+
+ it('tiles concurrent sessions instead of letting them overwrite each other (multi-GPU)', () => {
+ // CurrentImagePreview tiles per-session previews when several renders run at once; the video
+ // overlay must do the same or the sessions fight over the single full-size preview slot.
+ expect(source).toMatch(/withTiledProgress = withProgress && activeProgressData\.length > 1/);
+ expect(source).toContain('<ProgressImageTiles data={activeProgressData} />');
+ });
+
+ it('clears a pending post-render overlay when the video element errors', () => {
+ // onLoadedMetadata normally clears the resolve state; an errored element never fires it.
+ const errorHandler = source.slice(source.indexOf('const handleVideoError'), source.indexOf('const handlePlay'));
- expect(errorHandler).toContain('onLoadImage()');
++ expect(errorHandler).toContain('onLoadImage(videoDTO?.session_id ?? null)');
+ });
+});
diff --cc invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx
index 35369b9161,19aacb1944..7a107a8318
--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx
+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx
@@@ -193,17 -125,13 +193,17 @@@ export const CurrentVideoPreview = memo
if (isMediaCookieSelfHealPending()) {
return;
}
+ // A genuinely errored element will never fire onLoadedMetadata, which is what normally clears
+ // a pending post-render progress overlay — clear it here or it strands over the viewer.
+ // (onLoadImage is a no-op unless a resolve is actually pending.)
- onLoadImage();
++ onLoadImage(videoDTO?.session_id ?? null);
toast({
id: 'VIDEO_PLAYBACK_FAILED',
status: 'error',
title: t('toast.videoPlaybackFailed'),
description: t('toast.videoPlaybackFailedDesc'),
});
- }, [onLoadImage, t]);
- }, [t]);
++ }, [onLoadImage, t, videoDTO?.session_id]);
const handlePlay = useCallback(() => {
setIsPlaying(true);
diff --cc invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
index 9121472bed,19530ffebb..1cbd6baaf3
--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
@@@ -33,23 -31,13 +31,21 @@@ type ImageViewerContextValue =
$activeProgressData: Atom<ViewerProgressDatum[]>;
$isProgressImageResolving: Atom<boolean>;
$isTemporarilyShowingSelectedImage: WritableAtom<boolean>;
+ /** Name of the item most recently rendered by either preview component (image or video). Shared
+ * across the two components so a click that switches media type (image -> video or back) still
+ * reads as a selection change to the temporary-reveal logic — a per-component ref resets on the
+ * swap and would silently swallow the first reveal after every type switch. */
+ lastRenderedItemNameRef: MutableRefObject<string | null>;
- onLoadImage: () => void;
+ /**
+ * The viewer finished loading the final image/video for the given session (its DTO's
+ * `session_id`, or null when it has none). Ends the completed session's "resolve" illusion.
+ */
+ onLoadImage: (sessionId: string | null) => void;
};
+/** How long a mid-generation gallery click shows the clicked item before the live preview returns. */
+export const SELECTED_ITEM_REVEAL_DURATION_MS = 2000;
+
- /** Upper bound on the post-completion "progress preview resolves into the final media" illusion.
- * The clear normally fires from the final image's onLoad / the final video's onLoadedMetadata, but
- * on a slow connection that load can lag far behind completion — and if the media element errors,
- * it never fires at all. Past this deadline we drop the illusion rather than strand the overlay. */
- const RESOLVE_FAILSAFE_MS = 10_000;
-
const ImageViewerContext = createContext<ImageViewerContextValue | null>(null);
const log = logger('events');
@@@ -72,9 -60,6 +68,7 @@@ export const ImageViewerContextProvide
)[0];
const $isProgressImageResolving = useState(() => atom(false))[0];
const $isTemporarilyShowingSelectedImage = useState(() => atom(false))[0];
- const shouldClearProgressImageOnLoadRef = useRef(false);
+ const lastRenderedItemNameRef = useRef<string | null>(null);
- const resolveFailsafeTimeoutRef = useRef(0);
// We can have race conditions where we receive a progress event for a queue item that has already finished. Easiest
// way to handle this is to keep track of finished queue items in a cache and ignore progress events for those.
const [finishedQueueItemIds] = useState(() => new LRUCache<number, boolean>({ max: 200 }));
diff --cc invokeai/frontend/web/src/services/api/schema.ts
index a6f1240fd5,f1779d9814..391ee3083c
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@@ -32929,112 -31207,26 +33308,200 @@@ export type components =
type: "qwen3_encoder";
/**
* Format
- * @default gguf_quantized
+ * @default gguf_quantized
+ * @constant
+ */
+ format: "gguf_quantized";
+ /**
+ * Cpu Only
+ * @description Whether this model should run on CPU only
+ */
+ cpu_only: boolean | null;
+ /** @description Qwen3 model size variant (4B or 8B) */
+ variant: components["schemas"]["Qwen3VariantType"];
+ };
+ /**
+ * Qwen3Encoder_Qwen3Encoder_Config
+ * @description Configuration for Qwen3 Encoder models in a diffusers-like format.
+ *
+ * The model weights are expected to be in a folder called text_encoder inside the model directory,
+ * compatible with Qwen2VLForConditionalGeneration or similar architectures used by Z-Image.
+ */
+ Qwen3Encoder_Qwen3Encoder_Config: {
+ /**
+ * Key
+ * @description A unique key for this model.
+ */
+ key: string;
+ /**
+ * Hash
+ * @description The hash of the model file(s).
+ */
+ hash: string;
+ /**
+ * Path
+ * @description Path to the model on the filesystem. Relative paths are relative to the Invoke root directory.
+ */
+ path: string;
+ /**
+ * File Size
+ * @description The size of the model in bytes.
+ */
+ file_size: number;
+ /**
+ * Name
+ * @description Name of the model.
+ */
+ name: string;
+ /**
+ * Description
+ * @description Model description
+ */
+ description: string | null;
+ /**
+ * Source
+ * @description The original source of the model (path, URL or repo_id).
+ */
+ source: string;
+ /** @description The type of source */
+ source_type: components["schemas"]["ModelSourceType"];
+ /**
+ * Source Api Response
+ * @description The original API response from the source, as stringified JSON.
+ */
+ source_api_response: string | null;
+ /**
+ * Source Url
+ * @description Optional URL for the model (e.g. download page or model page).
+ */
+ source_url: string | null;
+ /**
+ * Cover Image
+ * @description Url for image to preview model
+ */
+ cover_image: string | null;
+ /**
+ * Base
+ * @default any
+ * @constant
+ */
+ base: "any";
+ /**
+ * Type
+ * @default qwen3_encoder
+ * @constant
+ */
+ type: "qwen3_encoder";
+ /**
+ * Format
+ * @default qwen3_encoder
+ * @constant
+ */
+ format: "qwen3_encoder";
+ /**
+ * Cpu Only
+ * @description Whether this model should run on CPU only
+ */
+ cpu_only: boolean | null;
+ /** @description Qwen3 model size variant (4B or 8B) */
+ variant: components["schemas"]["Qwen3VariantType"];
+ };
++ /**
++ * Qwen3Encoder_SDNQ_Config
++ * @description Configuration for SDNQ-quantized Qwen3 Encoder models (single file).
++ */
++ Qwen3Encoder_SDNQ_Config: {
++ /**
++ * Key
++ * @description A unique key for this model.
++ */
++ key: string;
++ /**
++ * Hash
++ * @description The hash of the model file(s).
++ */
++ hash: string;
++ /**
++ * Path
++ * @description Path to the model on the filesystem. Relative paths are relative to the Invoke root directory.
++ */
++ path: string;
++ /**
++ * File Size
++ * @description The size of the model in bytes.
++ */
++ file_size: number;
++ /**
++ * Name
++ * @description Name of the model.
++ */
++ name: string;
++ /**
++ * Description
++ * @description Model description
++ */
++ description: string | null;
++ /**
++ * Source
++ * @description The original source of the model (path, URL or repo_id).
++ */
++ source: string;
++ /** @description The type of source */
++ source_type: components["schemas"]["ModelSourceType"];
++ /**
++ * Source Api Response
++ * @description The original API response from the source, as stringified JSON.
++ */
++ source_api_response: string | null;
++ /**
++ * Source Url
++ * @description Optional URL for the model (e.g. download page or model page).
++ */
++ source_url: string | null;
++ /**
++ * Cover Image
++ * @description Url for image to preview model
++ */
++ cover_image: string | null;
++ /**
++ * Config Path
++ * @description Path to the config for this model, if any.
++ */
++ config_path: string | null;
++ /**
++ * Base
++ * @default any
++ * @constant
++ */
++ base: "any";
++ /**
++ * Type
++ * @default qwen3_encoder
++ * @constant
++ */
++ type: "qwen3_encoder";
++ /**
++ * Format
++ * @default sdnq_quantized
+ * @constant
+ */
- format: "gguf_quantized";
++ format: "sdnq_quantized";
+ /**
+ * Cpu Only
+ * @description Whether this model should run on CPU only
+ */
+ cpu_only: boolean | null;
+ /** @description Qwen3 model size variant (4B or 8B) */
+ variant: components["schemas"]["Qwen3VariantType"];
+ };
/**
- * Qwen3Encoder_Qwen3Encoder_Config
- * @description Configuration for Qwen3 Encoder models in a diffusers-like format.
+ * Qwen3Encoder_SDNQ_Folder_Config
+ * @description Configuration for folder-based SDNQ-quantized Qwen3 Encoder models.
*
- * The model weights are expected to be in a folder called text_encoder inside the model directory,
- * compatible with Qwen2VLForConditionalGeneration or similar architectures used by Z-Image.
+ * Used for SDNQ bundles where the text_encoder is a folder containing
+ * quantization_config.json and safetensors files with SDNQ keys.
*/
- Qwen3Encoder_Qwen3Encoder_Config: {
+ Qwen3Encoder_SDNQ_Folder_Config: {
/**
* Key
* @description A unique key for this model.
@@@ -47755,6 -45796,52 +48361,56 @@@ export interface operations
};
};
};
+ list_gallery_item_names: {
+ parameters: {
+ query?: {
+ /** @description The origin of items to list. */
+ origin?: components["schemas"]["ResourceOrigin"] | null;
+ /** @description The categories to include. Shared between images and videos. */
+ categories?: components["schemas"]["ImageCategory"][] | null;
+ /** @description Whether to list intermediate items. */
+ is_intermediate?: boolean | null;
+ /** @description The board id to filter by. Use 'none' to find items without a board. */
+ board_id?: string | null;
+ /** @description Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards. */
+ created_date?: string | null;
++ /** @description Inclusive start date (YYYY-MM-DD) to filter by created_at. */
++ created_from?: string | null;
++ /** @description Inclusive end date (YYYY-MM-DD) to filter by created_at. */
++ created_to?: string | null;
+ /** @description The order of sort */
+ order_dir?: components["schemas"]["SQLiteDirection"];
+ /** @description Whether to sort by starred items first */
+ starred_first?: boolean;
+ /** @description The term to search for */
+ search_term?: string | null;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryItemNames"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
get_gallery_item_names: {
parameters: {
query?: {
diff --cc tests/app/routers/conftest.py
index 397938bd95,fe139998a6..4d5d1a9858
--- a/tests/app/routers/conftest.py
+++ b/tests/app/routers/conftest.py
@@@ -53,8 -53,8 +53,9 @@@ _PATCHED_API_DEPENDENCIES_MODULES =
"invokeai.app.api.routers.style_presets",
"invokeai.app.api.routers.model_relationships",
"invokeai.app.api.routers.utilities",
+ "invokeai.app.api.routers.wildcards",
"invokeai.app.api.routers.virtual_boards",
+ "invokeai.app.api.routers.gallery",
"invokeai.app.api.routers.images",
"invokeai.app.api.routers.workflows",
"invokeai.app.api.routers._access",
diff --cc tests/app/routers/test_gallery.py
index ae1219fcd7,0000000000..bb2338664c
mode 100644,000000..100644
--- a/tests/app/routers/test_gallery.py
+++ b/tests/app/routers/test_gallery.py
@@@ -1,60 -1,0 +1,64 @@@
+"""Router contracts for polymorphic gallery filtering."""
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi.testclient import TestClient
+
+from invokeai.app.api.dependencies import ApiDependencies
- from invokeai.app.services.gallery.gallery_common import GalleryItemNamesResult
++from invokeai.app.services.gallery.gallery_common import GalleryItemNames, GalleryItemNamesResult
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.pagination import OffsetPaginatedResults
+
+
+class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker: Invoker) -> None:
+ self.invoker = invoker
+
+
- def _prepare_gallery_router_test(monkeypatch: Any, mock_invoker: Invoker) -> tuple[MagicMock, MagicMock]:
++def _prepare_gallery_router_test(monkeypatch: Any, mock_invoker: Invoker) -> tuple[MagicMock, MagicMock, MagicMock]:
+ dependencies = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.gallery.ApiDependencies", dependencies)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", dependencies)
+
+ list_items = MagicMock(return_value=OffsetPaginatedResults(items=[], offset=0, limit=10, total=0))
+ list_item_names = MagicMock(return_value=GalleryItemNamesResult(items=[], starred_count=0, total_count=0))
++ get_item_names = MagicMock(return_value=GalleryItemNames(item_names=[], starred_count=0, total_count=0))
+ monkeypatch.setattr(mock_invoker.services.gallery, "list_items", list_items)
+ monkeypatch.setattr(mock_invoker.services.gallery, "list_item_names", list_item_names)
- return list_items, list_item_names
++ monkeypatch.setattr(mock_invoker.services.gallery, "get_item_names", get_item_names)
++ return list_items, list_item_names, get_item_names
+
+
+ ("path", "service_index"),
- [("/api/v1/gallery/items/", 0), ("/api/v1/gallery/items/names", 1)],
++ [("/api/v1/gallery/items/", 0), ("/api/v1/gallery/items/names", 1), ("/api/v1/gallery/item_names", 2)],
+)
+def test_gallery_list_endpoints_parse_and_forward_created_ranges(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, service_index: int
+) -> None:
+ service_calls = _prepare_gallery_router_test(monkeypatch, mock_invoker)
+
+ response = client.get(path, params={"created_from": "2026-07-01", "created_to": "2026-07-15"})
+
+ assert response.status_code == 200
+ kwargs = service_calls[service_index].call_args.kwargs
+ assert kwargs["created_from"] == "2026-07-01"
+ assert kwargs["created_to"] == "2026-07-15"
+
+
- @pytest.mark.parametrize("path", ["/api/v1/gallery/items/", "/api/v1/gallery/items/names"])
++ "path", ["/api/v1/gallery/items/", "/api/v1/gallery/items/names", "/api/v1/gallery/item_names"]
++)
[email protected]("param", ["created_from", "created_to"])
+def test_gallery_list_endpoints_reject_invalid_created_range_dates(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, param: str
+) -> None:
+ _prepare_gallery_router_test(monkeypatch, mock_invoker)
+
+ response = client.get(path, params={param: "2026-02-31"})
+
+ assert response.status_code == 422
diff --cc tests/app/routers/test_multiuser_authorization.py
index dee3d1920c,267c46a36f..2ca71e68d3
--- a/tests/app/routers/test_multiuser_authorization.py
+++ b/tests/app/routers/test_multiuser_authorization.py
@@@ -2666,16 -2518,18 +2674,21 @@@ class TestCustomNodesAuthorization
def test_install_allows_admin(self, client: TestClient, admin_token: str, monkeypatch: Any, tmp_path: Any) -> None:
"""Admin caller can successfully install a node pack (filesystem/subprocess mocked)."""
++ from types import SimpleNamespace
++
monkeypatch.setattr("invokeai.app.api.routers.custom_nodes._get_custom_nodes_path", lambda: tmp_path)
# Simulate a successful git clone by creating the target dir with __init__.py
- async def fake_clone_node_pack(source: str, target_dir: Any) -> tuple[int, str]:
- def fake_git_clone(cmd: list[str], **kwargs: Any) -> MagicMock:
++ def fake_clone_node_pack(cmd: list[str], **kwargs: Any) -> Any:
target_dir = tmp_path / "test-pack"
target_dir.mkdir(parents=True, exist_ok=True)
(target_dir / "__init__.py").touch()
- return 0, ""
- result = MagicMock()
- result.returncode = 0
- return result
++ return SimpleNamespace(returncode=0, stderr="")
- monkeypatch.setattr("invokeai.app.api.routers.custom_nodes._clone_node_pack", fake_clone_node_pack)
- monkeypatch.setattr("invokeai.app.api.routers.custom_nodes.subprocess.run", fake_git_clone)
++ monkeypatch.setattr(
++ "invokeai.app.api.routers.custom_nodes.subprocess.run",
++ fake_clone_node_pack,
++ )
monkeypatch.setattr("invokeai.app.api.routers.custom_nodes._load_node_pack", lambda *a, **kw: None)
monkeypatch.setattr("invokeai.app.api.routers.custom_nodes._import_workflows_from_pack", lambda *a, **kw: [])
monkeypatch.setattr("invokeai.app.api.routers.custom_nodes._write_pack_manifest", lambda *a, **kw: None)
diff --cc tests/app/routers/test_privilege_revocation.py
index 0000000000,af4b5fe6dd..1a43e77292
mode 000000,100644..100644
--- a/tests/app/routers/test_privilege_revocation.py
+++ b/tests/app/routers/test_privilege_revocation.py
@@@ -1,0 -1,613 +1,617 @@@
+ """Tests that database role/status changes take effect immediately for existing JWTs.
+
+ The JWT proves identity only. Authorization (`is_admin`, `is_active`) is derived from
+ the database on every authenticated request, and sliding-window refresh mints the new
+ token from the database record. Without this, a demoted administrator could keep admin
+ rights until token expiry — renewing the stale claim (and media cookie) indefinitely
+ with every mutation.
+ """
+
+ import logging
+ from datetime import timedelta
+ from typing import Any
+ from unittest.mock import MagicMock
+
+ import pytest
+ from fastapi import status
+ from fastapi.testclient import TestClient
+
+ from invokeai.app.api.dependencies import ApiDependencies
+ from invokeai.app.api_app import app
+ from invokeai.app.services.auth.token_service import TokenData, create_access_token, verify_token
+ from invokeai.app.services.config.config_default import InvokeAIAppConfig
+ from invokeai.app.services.events.events_common import UserAccessChangedEvent
+ from invokeai.app.services.invocation_services import InvocationServices
+ from invokeai.app.services.invoker import Invoker
+ from invokeai.app.services.users.users_common import UserCreateRequest
+ from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
+ from invokeai.backend.util.logging import InvokeAILogger
+ from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+
+ class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker: Invoker) -> None:
+ self.invoker = invoker
+
+
+ @pytest.fixture
+ def setup_jwt_secret():
+ from invokeai.app.services.auth.token_service import set_jwt_secret
+
+ set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")
+
+
+ @pytest.fixture
+ def client():
+ return TestClient(app)
+
+
+ @pytest.fixture
+ def mock_services() -> InvocationServices:
+ from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
+ from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
+ from invokeai.app.services.board_video_records.board_video_records_sqlite import SqliteBoardVideoRecordStorage
+ from invokeai.app.services.boards.boards_default import BoardService
+ from invokeai.app.services.bulk_download.bulk_download_default import BulkDownloadService
+ from invokeai.app.services.client_state_persistence.client_state_persistence_sqlite import (
+ ClientStatePersistenceSqlite,
+ )
+ from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
+ from invokeai.app.services.images.images_default import ImageService
+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
+ from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
+ from invokeai.app.services.system_prompt_records.system_prompt_records_sqlite import (
+ SqliteSystemPromptRecordsStorage,
+ )
+ from invokeai.app.services.users.users_default import UserService
+ from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStorage
+ from tests.test_nodes import TestEventService
+
+ configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
+ logger = InvokeAILogger.get_logger()
+ db = create_mock_sqlite_database(configuration, logger)
+
+ return InvocationServices(
+ board_image_records=SqliteBoardImageRecordStorage(db=db),
+ board_images=None, # type: ignore
+ board_records=SqliteBoardRecordStorage(db=db),
+ boards=BoardService(),
+ bulk_download=BulkDownloadService(),
+ configuration=configuration,
+ events=TestEventService(),
+ image_files=None, # type: ignore
+ image_records=SqliteImageRecordStorage(db=db),
+ images=ImageService(),
+ invocation_cache=MemoryInvocationCache(max_cache_size=0),
+ logger=logging, # type: ignore
+ model_images=None, # type: ignore
+ model_manager=None, # type: ignore
+ download_queue=None, # type: ignore
+ names=None, # type: ignore
+ performance_statistics=InvocationStatsService(),
+ session_processor=None, # type: ignore
+ session_queue=None, # type: ignore
+ urls=None, # type: ignore
+ workflow_records=SqliteWorkflowRecordsStorage(db=db),
+ tensors=None, # type: ignore
+ conditioning=None, # type: ignore
+ style_preset_records=None, # type: ignore
+ style_preset_image_files=None, # type: ignore
+ system_prompt_records=SqliteSystemPromptRecordsStorage(db=db),
+ workflow_thumbnails=None, # type: ignore
+ model_relationship_records=None, # type: ignore
+ model_relationships=None, # type: ignore
+ client_state_persistence=ClientStatePersistenceSqlite(db=db),
+ users=UserService(db),
+ external_generation=None, # type: ignore
+ videos=None, # type: ignore
+ video_files=None, # type: ignore
+ video_records=SqliteVideoRecordStorage(db=db),
+ board_video_records=SqliteBoardVideoRecordStorage(db=db),
+ gallery=None, # type: ignore
++ wildcard_records=None, # type: ignore
++ project_records=None, # type: ignore
++ image_index_records=None, # type: ignore
++ image_index=None, # type: ignore
+ )
+
+
+ @pytest.fixture()
+ def mock_invoker(mock_services: InvocationServices) -> Invoker:
+ return Invoker(services=mock_services)
+
+
+ def _save_image(mock_invoker: Invoker, image_name: str, user_id: str) -> None:
+ from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+
+ mock_invoker.services.image_records.save(
+ image_name=image_name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=100,
+ height=100,
+ has_workflow=False,
+ user_id=user_id,
+ )
+
+
+ def _create_user(mock_invoker: Invoker, email: str, display_name: str, is_admin: bool = False) -> str:
+ user = mock_invoker.services.users.create(
+ UserCreateRequest(email=email, display_name=display_name, password="TestPass123", is_admin=is_admin)
+ )
+ return user.user_id
+
+
+ def _login(client: TestClient, email: str) -> str:
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "TestPass123", "remember_me": False})
+ assert r.status_code == 200
+ return r.json()["token"]
+
+
+ def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+ @pytest.fixture
+ def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker, setup_jwt_secret: None):
+ mock_invoker.services.configuration.multiuser = True
+
+ mock_board_images = MagicMock()
+ mock_board_images.get_all_board_image_names_for_board.return_value = []
+ mock_invoker.services.board_images = mock_board_images
+
+ mock_deps = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.routers.images.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.routers._access.ApiDependencies", mock_deps)
+ # The sliding-window middleware binds ApiDependencies at import time in api_app, so
+ # patching the defining module alone would not reach it. Patch both so refresh
+ # assertions exercise the real logic.
+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api_app.ApiDependencies", mock_deps)
+ yield
+
+
+ @pytest.fixture
+ def admin_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClient):
+ _create_user(mock_invoker, "[email protected]", "Admin", is_admin=True)
+ return _login(client, "[email protected]")
+
+
+ def _demote(client: TestClient, admin_token: str, mock_invoker: Invoker, email: str) -> None:
+ user = mock_invoker.services.users.get_by_email(email)
+ assert user is not None
+ r = client.patch(f"/api/v1/auth/users/{user.user_id}", json={"is_admin": False}, headers=_auth(admin_token))
+ assert r.status_code == 200
+
+
+ class TestLastAdminGuard:
+ """Because authorization is now DB-derived and takes effect immediately, removing the
+ last administrator would be unrecoverable — and would re-open unauthenticated setup."""
+
+ def _patch_self(self, client: TestClient, mock_invoker: Invoker, token: str, body: dict) -> Any:
+ user = mock_invoker.services.users.get_by_email("[email protected]")
+ assert user is not None
+ return client.patch(f"/api/v1/auth/users/{user.user_id}", json=body, headers=_auth(token))
+
+ def test_demoting_last_admin_is_rejected(self, client: TestClient, mock_invoker: Invoker, admin_token: str) -> None:
+ r = self._patch_self(client, mock_invoker, admin_token, {"is_admin": False})
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+ assert mock_invoker.services.users.has_admin() is True
+
+ def test_deactivating_last_admin_is_rejected(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ r = self._patch_self(client, mock_invoker, admin_token, {"is_active": False})
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+ assert mock_invoker.services.users.has_admin() is True
+
+ def test_setup_endpoint_stays_closed_after_rejected_demotion(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The unauthenticated setup endpoint must not become reachable again."""
+ self._patch_self(client, mock_invoker, admin_token, {"is_admin": False})
+
+ r = client.post(
+ "/api/v1/auth/setup",
+ json={"email": "[email protected]", "display_name": "Attacker", "password": "TestPass123"},
+ )
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_demoting_admin_is_allowed_when_another_admin_remains(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ _create_user(mock_invoker, "[email protected]", "Admin Two", is_admin=True)
+
+ r = self._patch_self(client, mock_invoker, admin_token, {"is_admin": False})
+
+ assert r.status_code == 200
+ assert r.json()["is_admin"] is False
+
+ def test_unrelated_update_to_last_admin_is_allowed(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The guard must only block the two fields that can remove admin access."""
+ r = self._patch_self(client, mock_invoker, admin_token, {"display_name": "Renamed"})
+
+ assert r.status_code == 200
+ assert r.json()["display_name"] == "Renamed"
+
+
+ class TestDbDerivedAuthorization:
+ """Authorization fields come from the database record, not the token's claims."""
+
+ def test_demoted_admin_old_token_gets_403_and_no_refresh(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ _create_user(mock_invoker, "[email protected]", "Admin Two", is_admin=True)
+ admin2_token = _login(client, "[email protected]")
+ _demote(client, admin_token, mock_invoker, "[email protected]")
+
+ # Admin-only mutation with the pre-demotion token: rejected, and the stale
+ # admin claim is not renewed (no refreshed bearer token, no media cookie).
+ r = client.post(
+ "/api/v1/auth/users",
+ json={"email": "[email protected]", "display_name": "New", "password": "TestPass123", "is_admin": False},
+ headers=_auth(admin2_token),
+ )
+ assert r.status_code == status.HTTP_403_FORBIDDEN
+ assert "X-Refreshed-Token" not in r.headers
+ assert "set-cookie" not in r.headers
+
+ def test_demoted_admin_old_token_cannot_read_other_users_private_image(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ _create_user(mock_invoker, "[email protected]", "Admin Two", is_admin=True)
+ _create_user(mock_invoker, "[email protected]", "User One")
+ admin2_token = _login(client, "[email protected]")
+ user1 = mock_invoker.services.users.get_by_email("[email protected]")
+ assert user1 is not None
+ _save_image(mock_invoker, "user1-private-img", user1.user_id)
+ # The DTO route resolves URLs through the urls service, which is None in
+ # the test harness.
+ mock_urls = MagicMock()
+ mock_urls.get_image_url.return_value = "http://test/image.png"
+ mock_invoker.services.urls = mock_urls
+
+ # Pre-demotion the token works (admin may read any image)...
+ r = client.get("/api/v1/images/i/user1-private-img", headers=_auth(admin2_token))
+ assert r.status_code == status.HTTP_200_OK
+
+ _demote(client, admin_token, mock_invoker, "[email protected]")
+
+ # ...post-demotion the same token is denied.
+ r = client.get("/api/v1/images/i/user1-private-img", headers=_auth(admin2_token))
+ assert r.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_promoted_user_old_token_gains_admin(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ _create_user(mock_invoker, "[email protected]", "User One")
+ user1_token = _login(client, "[email protected]")
+ user1 = mock_invoker.services.users.get_by_email("[email protected]")
+ assert user1 is not None
+
+ r = client.get("/api/v1/auth/users", headers=_auth(user1_token))
+ assert r.status_code == status.HTTP_403_FORBIDDEN
+
+ r = client.patch(f"/api/v1/auth/users/{user1.user_id}", json={"is_admin": True}, headers=_auth(admin_token))
+ assert r.status_code == 200
+
+ # The pre-promotion token now carries admin rights (derived from the DB).
+ r = client.get("/api/v1/auth/users", headers=_auth(user1_token))
+ assert r.status_code == status.HTTP_200_OK
+
+ def test_unchanged_admin_mutation_refreshes_with_admin_claim(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ r = client.post(
+ "/api/v1/auth/users",
+ json={"email": "[email protected]", "display_name": "New", "password": "TestPass123", "is_admin": False},
+ headers=_auth(admin_token),
+ )
+ assert r.status_code == status.HTTP_201_CREATED
+ refreshed = verify_token(r.headers["X-Refreshed-Token"])
+ assert refreshed is not None
+ assert refreshed.is_admin is True
+
+ def test_demoted_admin_allowed_mutation_refreshes_with_demoted_claim(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """A successful non-admin mutation by a demoted user renews the token with the
+ database's is_admin=False — the stale admin claim does not survive refresh."""
+ _create_user(mock_invoker, "[email protected]", "Admin Two", is_admin=True)
+ admin2_token = _login(client, "[email protected]")
+ _demote(client, admin_token, mock_invoker, "[email protected]")
+
+ r = client.patch("/api/v1/auth/me", json={"display_name": "Renamed"}, headers=_auth(admin2_token))
+ assert r.status_code == 200
+ refreshed = verify_token(r.headers["X-Refreshed-Token"])
+ assert refreshed is not None
+ assert refreshed.is_admin is False
+
+
+ class TestSystemUserIsProtected:
+ """The system user owns everything migrated from before multiuser support, so removing
+ it would strand that content rather than merely removing an account."""
+
+ def test_system_user_cannot_be_deleted(self, client: TestClient, admin_token: str) -> None:
+ r = client.delete("/api/v1/auth/users/system", headers=_auth(admin_token))
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_system_user_cannot_be_deactivated(self, client: TestClient, admin_token: str) -> None:
+ r = client.patch("/api/v1/auth/users/system", json={"is_active": False}, headers=_auth(admin_token))
+
+ assert r.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_system_user_survives_both_attempts(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ client.delete("/api/v1/auth/users/system", headers=_auth(admin_token))
+ client.patch("/api/v1/auth/users/system", json={"is_active": False}, headers=_auth(admin_token))
+
+ system = mock_invoker.services.users.get("system")
+ assert system is not None
+ assert system.is_active is True
+
+ def test_a_token_claiming_the_system_account_is_refused(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """Closing the login hole does not reach a token already in the wild.
+
+ An instance that set a password on the system row through the old
+ `PATCH /auth/users/system` and logged in holds a JWT that survives the upgrade:
+ the row is deliberately kept active and its epoch still matches, so nothing else
+ rejects it, and the sliding-window middleware would renew it indefinitely. It
+ grants read/write over every board, image, workflow, and queue item carried over
+ from before multiuser support, so `resolve_authorized_user` refuses the id itself.
+ """
+ _save_image(mock_invoker, "system-owned-img", "system")
+ system_token = create_access_token(
+ TokenData(user_id="system", email="[email protected]", is_admin=False),
+ timedelta(days=1),
+ )
+
+ assert client.get("/api/v1/auth/me", headers=_auth(system_token)).status_code == (status.HTTP_401_UNAUTHORIZED)
+ r = client.get("/api/v1/images/i/system-owned-img", headers=_auth(system_token))
+ assert r.status_code == status.HTTP_401_UNAUTHORIZED
+ assert "X-Refreshed-Token" not in r.headers
+
+ def test_an_admin_token_claiming_the_system_account_is_refused(self, client: TestClient, admin_token: str) -> None:
+ """The refusal is on the id, so forging the admin claim does not help either."""
+ system_token = create_access_token(
+ TokenData(user_id="system", email="[email protected]", is_admin=True),
+ timedelta(days=1),
+ )
+
+ r = client.post(
+ "/api/v1/auth/users",
+ json={"email": "[email protected]", "display_name": "New", "password": "TestPass123", "is_admin": True},
+ headers=_auth(system_token),
+ )
+ assert r.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_ordinary_user_deletion_still_works(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The guard must be specific to the system id, not a blanket block."""
+ user_id = _create_user(mock_invoker, "[email protected]", "User")
+
+ r = client.delete(f"/api/v1/auth/users/{user_id}", headers=_auth(admin_token))
+
+ assert r.status_code == status.HTTP_204_NO_CONTENT
+ assert mock_invoker.services.users.get(user_id) is None
+
+
+ class TestTokenEpochRevocation:
+ """A password change invalidates tokens issued before it.
+
+ A JWT is self-contained, so nothing in the database can make an already-issued token
+ stop verifying. The epoch claim is the missing revocation primitive: rotating the
+ password bumps it, and every token carrying the old value is rejected.
+ """
+
+ def _change_own_password(self, client: TestClient, token: str, current: str, new: str) -> Any:
+ return client.patch(
+ "/api/v1/auth/me",
+ json={"current_password": current, "new_password": new},
+ headers=_auth(token),
+ )
+
+ def test_password_change_revokes_other_sessions(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ _create_user(mock_invoker, "[email protected]", "User")
+ session_a = _login(client, "[email protected]")
+ session_b = _login(client, "[email protected]")
+
+ r = self._change_own_password(client, session_a, "TestPass123", "BrandNewPass456")
+ assert r.status_code == 200
+
+ # The other session's token is dead even though the account is still active.
+ assert client.get("/api/v1/auth/me", headers=_auth(session_b)).status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_password_change_keeps_the_calling_session(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """Changing your own password must not sign you out of the tab you did it from."""
+ _create_user(mock_invoker, "[email protected]", "User")
+ token = _login(client, "[email protected]")
+
+ r = self._change_own_password(client, token, "TestPass123", "BrandNewPass456")
+
+ assert r.status_code == 200
+ replacement = r.headers["X-Refreshed-Token"]
+ assert client.get("/api/v1/auth/me", headers=_auth(replacement)).status_code == 200
+
+ def test_admin_password_reset_revokes_the_targets_sessions(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ user_id = _create_user(mock_invoker, "[email protected]", "User")
+ victim_token = _login(client, "[email protected]")
+
+ r = client.patch(
+ f"/api/v1/auth/users/{user_id}", json={"password": "AdminReset789"}, headers=_auth(admin_token)
+ )
+ assert r.status_code == 200
+
+ assert client.get("/api/v1/auth/me", headers=_auth(victim_token)).status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_revoked_token_cannot_be_laundered_by_refresh(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The sliding window must not mint a fresh token from a revoked one.
+
+ The middleware runs after the route and refreshes on any 2xx mutation, so an
+ unauthenticated route would otherwise hand a stale-epoch bearer a valid token.
+ """
+ _create_user(mock_invoker, "[email protected]", "User")
+ stale = _login(client, "[email protected]")
+ _login(client, "[email protected]")
+ self._change_own_password(client, stale, "TestPass123", "BrandNewPass456")
+
+ # /auth/login requires no bearer and returns 200, but carries our stale header.
+ r = client.post(
+ "/api/v1/auth/login",
+ json={"email": "[email protected]", "password": "BrandNewPass456", "remember_me": False},
+ headers=_auth(stale),
+ )
+
+ assert r.status_code == 200
+ assert "X-Refreshed-Token" not in r.headers
+
+ def test_unrelated_profile_update_does_not_revoke(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """Only a password change bumps the epoch — renaming must not sign anyone out."""
+ _create_user(mock_invoker, "[email protected]", "User")
+ token = _login(client, "[email protected]")
+
+ r = client.patch("/api/v1/auth/me", json={"display_name": "Renamed"}, headers=_auth(token))
+
+ assert r.status_code == 200
+ assert client.get("/api/v1/auth/me", headers=_auth(token)).status_code == 200
+
+ def test_revoked_token_is_rejected_on_ordinary_routes(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The revocation must cover the dependency almost every route actually uses.
+
+ `/auth/*` routes take `CurrentUser`; the rest of the API takes
+ `CurrentUserOrDefault`. Checking only the former leaves the check absent
+ everywhere it matters, which is indistinguishable from having no check at all.
+ """
+ _create_user(mock_invoker, "[email protected]", "User")
+ stale = _login(client, "[email protected]")
+ _save_image(mock_invoker, "victim.png", mock_invoker.services.users.get_by_email("[email protected]").user_id)
+ second = _login(client, "[email protected]")
+ self._change_own_password(client, second, "TestPass123", "BrandNewPass456")
+
+ # A CurrentUserOrDefault route, not an /auth/* one.
+ r = client.get("/api/v1/images/i/victim.png", headers=_auth(stale))
+
+ assert r.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_admin_resetting_own_password_is_not_locked_out(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """The admin route bumps the epoch just like /auth/me, so it owes the caller a
+ replacement for the same reason — otherwise an admin who resets their own
+ password from the user-management screen locks themselves out."""
+ admin = mock_invoker.services.users.get_by_email("[email protected]")
+ assert admin is not None
+
+ r = client.patch(
+ f"/api/v1/auth/users/{admin.user_id}",
+ json={"password": "AdminNewPass789"},
+ headers=_auth(admin_token),
+ )
+
+ assert r.status_code == 200
+ replacement = r.headers["X-Refreshed-Token"]
+ assert client.get("/api/v1/auth/me", headers=_auth(replacement)).status_code == 200
+ assert client.get("/api/v1/auth/me", headers=_auth(admin_token)).status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_password_change_emits_access_event_for_live_sockets(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """HTTP revocation alone would leave already-open sockets streaming events."""
+ _create_user(mock_invoker, "[email protected]", "User")
+ token = _login(client, "[email protected]")
+
+ self._change_own_password(client, token, "TestPass123", "BrandNewPass456")
+
+ events = [e for e in mock_invoker.services.events.events if isinstance(e, UserAccessChangedEvent)]
+ assert len(events) == 1
+ assert events[0].is_active is True # not a deactivation — the epoch is the signal
+ assert events[0].token_epoch == 1
+
+ def test_tokens_predating_the_claim_still_work(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ """Upgrading must not log everyone out: no epoch claim decodes to 0, matching an
+ un-bumped record."""
+ from invokeai.app.services.auth.token_service import TokenData, create_access_token
+
+ user_id = _create_user(mock_invoker, "[email protected]", "User")
+ legacy = create_access_token(
+ TokenData(user_id=user_id, email="[email protected]", is_admin=False, remember_me=False)
+ )
+
+ assert client.get("/api/v1/auth/me", headers=_auth(legacy)).status_code == 200
+
+
+ class TestUserAccessChangedEmission:
+ """Role/status changes emit the internal event that re-authorizes live connections."""
+
+ def _access_events(self, mock_invoker: Invoker) -> list[UserAccessChangedEvent]:
+ return [e for e in mock_invoker.services.events.events if isinstance(e, UserAccessChangedEvent)]
+
+ def test_demotion_emits_event(self, client: TestClient, mock_invoker: Invoker, admin_token: str) -> None:
+ _create_user(mock_invoker, "[email protected]", "Admin Two", is_admin=True)
+ _demote(client, admin_token, mock_invoker, "[email protected]")
+
+ events = self._access_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].is_admin is False
+ assert events[0].is_active is True
+
+ def test_deactivation_emits_event(self, client: TestClient, mock_invoker: Invoker, admin_token: str) -> None:
+ user_id = _create_user(mock_invoker, "[email protected]", "User One")
+
+ r = client.patch(f"/api/v1/auth/users/{user_id}", json={"is_active": False}, headers=_auth(admin_token))
+ assert r.status_code == 200
+
+ events = self._access_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].user_id == user_id
+ assert events[0].is_active is False
+
+ def test_display_name_change_does_not_emit_event(
+ self, client: TestClient, mock_invoker: Invoker, admin_token: str
+ ) -> None:
+ user_id = _create_user(mock_invoker, "[email protected]", "User One")
+
+ r = client.patch(f"/api/v1/auth/users/{user_id}", json={"display_name": "Renamed"}, headers=_auth(admin_token))
+ assert r.status_code == 200
+
+ assert self._access_events(mock_invoker) == []
+
+ def test_deletion_emits_inactive_event(self, client: TestClient, mock_invoker: Invoker, admin_token: str) -> None:
+ user_id = _create_user(mock_invoker, "[email protected]", "User One")
+
+ r = client.delete(f"/api/v1/auth/users/{user_id}", headers=_auth(admin_token))
+ assert r.status_code == status.HTTP_204_NO_CONTENT
+
+ events = self._access_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].user_id == user_id
+ assert events[0].is_active is False
+ assert events[0].is_admin is False
diff --cc tests/app/routers/test_session_queue_sanitization.py
index 5acf67368e,e2b375585e..e68f42586d
--- a/tests/app/routers/test_session_queue_sanitization.py
+++ b/tests/app/routers/test_session_queue_sanitization.py
@@@ -4,11 -4,14 +4,15 @@@ from datetime import datetim
import pytest
-from invokeai.app.api.routers.session_queue import sanitize_queue_item_for_user
+from invokeai.app.api.routers.session_queue import sanitize_queue_item_for_user, strip_missing_image_results
from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output
-from invokeai.app.invocations.fields import InputField, OutputField
+from invokeai.app.invocations.fields import ImageField, InputField, OutputField, VideoField
+from invokeai.app.invocations.primitives import ImageCollectionOutput, ImageOutput, VideoOutput
- from invokeai.app.services.session_queue.session_queue_common import NodeFieldValue, SessionQueueItem
+ from invokeai.app.services.session_queue.session_queue_common import (
+ NodeFieldValue,
+ SessionQueueItem,
+ SessionQueueItemSummary,
+ )
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import InvocationContext
@@@ -192,123 -195,46 +196,154 @@@ def test_sanitize_system_user_item_for_
assert len(result.session.graph.nodes) == 1
+def test_sanitize_owner_strips_missing_image_results(monkeypatch, sample_session_queue_item):
+ sample_session_queue_item.session.results = {
+ "missing_node": ImageOutput(image=ImageField(image_name="missing.png"), width=64, height=64),
+ "kept_node": ImageOutput(image=ImageField(image_name="kept.png"), width=64, height=64),
+ }
+ monkeypatch.setattr(
+ "invokeai.app.api.routers.session_queue._image_record_exists",
+ lambda name: name == "kept.png",
+ )
+
+ result = sanitize_queue_item_for_user(
+ queue_item=sample_session_queue_item,
+ current_user_id="user_123",
+ is_admin=False,
+ )
+
+ assert "missing_node" not in result.session.results
+ assert "kept_node" in result.session.results
+
+
+def test_strip_missing_image_results_removes_deleted_single_image_output(sample_session_queue_item):
+ sample_session_queue_item.session.results = {
+ "missing_node": ImageOutput(image=ImageField(image_name="missing.png"), width=64, height=64),
+ "kept_node": ImageOutput(image=ImageField(image_name="kept.png"), width=64, height=64),
+ }
+
+ result = strip_missing_image_results(sample_session_queue_item, image_exists=lambda name: name == "kept.png")
+
+ assert "missing_node" not in result.session.results
+ assert "kept_node" in result.session.results
+ # The original queue item is not mutated; only the API response copy is sanitized.
+ assert "missing_node" in sample_session_queue_item.session.results
+
+
+def test_strip_missing_image_results_filters_deleted_collection_items(sample_session_queue_item):
+ sample_session_queue_item.session.results = {
+ "collection_node": ImageCollectionOutput(
+ collection=[ImageField(image_name="missing.png"), ImageField(image_name="kept.png")]
+ )
+ }
+
+ result = strip_missing_image_results(sample_session_queue_item, image_exists=lambda name: name == "kept.png")
+
+ output = result.session.results["collection_node"]
+ assert isinstance(output, ImageCollectionOutput)
+ assert output.collection == [ImageField(image_name="kept.png")]
+ assert sample_session_queue_item.session.results["collection_node"].collection == [
+ ImageField(image_name="missing.png"),
+ ImageField(image_name="kept.png"),
+ ]
+
+
- def test_sanitize_redacts_device_for_different_user(sample_session_queue_item):
- """`device` is upstream's per-GPU execution field. It postdates the fork's redaction list, so
- guard it explicitly: a non-admin must not learn where another user's work is placed."""
- sample_session_queue_item.device = "cuda:1"
-
- result = sanitize_queue_item_for_user(
- queue_item=sample_session_queue_item,
- current_user_id="different_user",
- is_admin=False,
- )
-
- assert result.device is None
-
-
+def test_sanitize_preserves_device_for_owner_and_admin(sample_session_queue_item):
+ sample_session_queue_item.device = "cuda:1"
+
+ owner_view = sanitize_queue_item_for_user(
+ queue_item=sample_session_queue_item, current_user_id="user_123", is_admin=False
+ )
+ admin_view = sanitize_queue_item_for_user(
+ queue_item=sample_session_queue_item, current_user_id="someone_else", is_admin=True
+ )
+
+ assert owner_view.device == "cuda:1"
+ assert admin_view.device == "cuda:1"
+
+
+def test_strip_missing_image_results_removes_deleted_video_output(sample_session_queue_item):
+ """Video outputs go stale exactly like image outputs. Clients hydrate `session.results`, so a
+ deleted video advertised in completed history produces the same 404 loop this helper exists to
+ prevent."""
+ sample_session_queue_item.session.results = {
+ "missing_node": VideoOutput(
+ video=VideoField(video_name="missing.mp4"), width=64, height=64, num_frames=8, fps=8.0, duration=1.0
+ ),
+ "kept_node": VideoOutput(
+ video=VideoField(video_name="kept.mp4"), width=64, height=64, num_frames=8, fps=8.0, duration=1.0
+ ),
+ }
+
+ result = strip_missing_image_results(
+ sample_session_queue_item,
+ video_exists=lambda name: name == "kept.mp4",
+ )
+
+ assert "missing_node" not in result.session.results
+ assert "kept_node" in result.session.results
+ assert "missing_node" in sample_session_queue_item.session.results
+
+
+def test_strip_missing_image_results_checks_images_and_videos_independently(sample_session_queue_item):
+ """A video and an image may share a stem; each must be resolved against its own record store."""
+ sample_session_queue_item.session.results = {
+ "image_node": ImageOutput(image=ImageField(image_name="asset"), width=64, height=64),
+ "video_node": VideoOutput(
+ video=VideoField(video_name="asset"), width=64, height=64, num_frames=8, fps=8.0, duration=1.0
+ ),
+ }
+
+ result = strip_missing_image_results(
+ sample_session_queue_item,
+ image_exists=lambda name: True,
+ video_exists=lambda name: False,
+ )
+
+ assert "image_node" in result.session.results
+ assert "video_node" not in result.session.results
++
++
+ def test_sanitize_queue_item_summary_for_different_user(sample_session_queue_item: SessionQueueItem) -> None:
+ summary = SessionQueueItemSummary(**sample_session_queue_item.model_copy(update={"device": "cuda:1"}).model_dump())
+
+ result = sanitize_queue_item_for_user(summary, current_user_id="different_user", is_admin=False)
+
+ assert result.item_id == summary.item_id
+ assert result.created_at == summary.created_at
+ assert result.status == summary.status
+ assert result.started_at == summary.started_at
+ assert result.completed_at == summary.completed_at
+ # The GPU is a property of the instance's hardware, not of the other user's work, and the
+ # queue list has always shown it. Redacting it here would also make the list disagree with
+ # the detail view, which does not redact it.
+ assert result.device == "cuda:1"
+ assert result.origin is None
+ assert result.destination is None
+ assert result.batch_id == "redacted"
+ assert result.user_id == "redacted"
+ assert result.user_display_name is None
+ assert result.user_email is None
+ assert result.field_values is None
+ assert result.parent_item_id is None
+
+
+ def test_summary_and_full_item_redact_shared_fields_identically(sample_session_queue_item: SessionQueueItem) -> None:
+ """The list summary and the full item are two projections of the same row.
+
+ A field redacted in one and left in the other is leaked anyway, so both must go through the
+ same redaction. This pins that they do — it is what fails if a future field is added to one
+ sanitization path and forgotten in the other.
+ """
+ item = sample_session_queue_item.model_copy(update={"device": "cuda:1"})
+ summary = SessionQueueItemSummary(**item.model_dump())
+
+ sanitized_item = sanitize_queue_item_for_user(item, current_user_id="different_user", is_admin=False)
+ sanitized_summary = sanitize_queue_item_for_user(summary, current_user_id="different_user", is_admin=False)
+
+ shared_fields = set(SessionQueueItemSummary.model_fields) & set(SessionQueueItem.model_fields)
+ assert "user_id" in shared_fields # guards against the intersection silently going empty
+ for field in sorted(shared_fields):
+ assert getattr(sanitized_summary, field) == getattr(sanitized_item, field), (
+ f"'{field}' is redacted differently in the summary than in the full item"
+ )
diff --cc tests/app/services/gallery/test_gallery_default.py
index f8bc0cc6b3,8c4a480299..5764f5b474
--- a/tests/app/services/gallery/test_gallery_default.py
+++ b/tests/app/services/gallery/test_gallery_default.py
@@@ -278,61 -249,6 +278,79 @@@ class TestListItemNamesByCreatedDate
assert [(item.kind, item.name) for item in result.items] == [(GalleryItemKind.VIDEO, "alice-day.mp4")]
+class TestCreatedRangeFiltering:
+ def test_list_items_includes_utc_day_bounds_and_reports_total(self, services) -> None:
+ _seed_created_range(services)
+ _start_gallery_for_item_results(services)
+
+ result = services["gallery"].list_items(
+ limit=10,
+ user_id="alice",
+ is_admin=False,
+ created_from="2026-03-10",
+ created_to="2026-03-11",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.IMAGE, "range-end.png"),
+ (GalleryItemKind.VIDEO, "range-video-end.mp4"),
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total == 4
+
+ def test_list_item_names_created_range_matches_item_order_and_counts(self, services) -> None:
+ _seed_created_range(services)
+
+ result = services["gallery"].list_item_names(
+ user_id="alice",
+ is_admin=False,
+ created_from="2026-03-10",
+ created_to="2026-03-11",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.IMAGE, "range-end.png"),
+ (GalleryItemKind.VIDEO, "range-video-end.mp4"),
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total_count == 4
+
++ def test_get_item_names_created_range_matches_legacy_result(self, services) -> None:
++ _seed_created_range(services)
++
++ result = services["gallery"].get_item_names(
++ user_id="alice",
++ is_admin=False,
++ created_from="2026-03-10",
++ created_to="2026-03-11",
++ )
++
++ assert result.item_names == [
++ "range-end.png",
++ "range-video-end.mp4",
++ "range-video.mp4",
++ "range-start.png",
++ ]
++ assert result.total_count == 4
++
+ def test_created_date_remains_an_exact_day_filter_without_ranges(self, services) -> None:
+ _seed_created_range(services)
+
+ result = services["gallery"].list_item_names(
+ user_id="alice",
+ is_admin=False,
+ created_date="2026-03-10",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total_count == 2
+
+
class TestGetBoardMediaSummaries:
def test_returns_counts_and_deterministic_covers_in_one_result(self, services) -> None:
populated = services["boards"].save("Populated", "alice")