Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(api): stop synchronous route work from stalling the whole server (#9436)
Alexander Eichhorn43da95177a45
diff --git a/docs/src/content/docs/contributing/blocking-work-in-api-routes.md b/docs/src/content/docs/contributing/blocking-work-in-api-routes.mdnew file mode 100644index 0000000000..97ccdbe000--- /dev/null+++ b/docs/src/content/docs/contributing/blocking-work-in-api-routes.md@@ -0,0 +1,104 @@+---+title: Blocking Work in API Routes+---++Almost every service in the backend is synchronous — the database layer, the model+manager, the file stores. The API layer in front of them is asynchronous. Getting the+boundary between the two wrong does not produce a slow endpoint; it produces a server+that stops answering entirely.++## The rule++**A route handler that only calls synchronous services must be declared `def`, not+`async def`.**++```python+# Correct — Starlette runs this in a worker thread.+@gallery_router.get("/items/names")+def get_gallery_item_names(current_user: CurrentUserOrDefault) -> GalleryItemNamesResult:+ return ApiDependencies.invoker.services.gallery.list_item_names(...)+```++```python+# Wrong — the database query runs on the event loop.+@gallery_router.get("/items/names")+async def get_gallery_item_names(current_user: CurrentUserOrDefault) -> GalleryItemNamesResult:+ return ApiDependencies.invoker.services.gallery.list_item_names(...)+```++The same rule applies to **dependencies**, not just handlers. A dependency declared+`async def` that performs a synchronous database lookup blocks the loop on every request+that uses it.++## Why it matters++The server runs as a single process with a single event loop. Anything executed directly+on that loop has the whole process to itself until it returns. Blocking work on the loop+therefore does not just delay its own response — for its entire duration the process+serves **no** other HTTP request and delivers **no** socket.io event. Users do not+experience this as one slow endpoint; they experience it as the application freezing,+typically mid-generation, because progress events stop arriving too.++The cost scales with the user's library, not with the developer's. A gallery query that+returns in milliseconds against a test database can take minutes against a multi-gigabyte+one — for example a metadata search, which has to read every row's metadata blob.++Declaring the handler `def` makes FastAPI dispatch it to a worker thread instead, leaving+the loop free to serve everything else.++## When `async def` is right++Use `async def` when the body actually awaits something — streaming a response, awaiting+another async API, or coordinating tasks. If such a handler *also* performs blocking work,+that work must be wrapped explicitly:++```python+from starlette.concurrency import run_in_threadpool++user = await run_in_threadpool(ApiDependencies.invoker.services.users.get, user_id)+```++`async def` with no `await` in the body is always a mistake: it gains nothing and costs+the loop.++## What this does not fix++Moving work to the threadpool does not make it faster, and it does not make it parallel.+The SQLite layer uses a single connection behind a process-wide lock, so database work+remains serialized regardless of which thread requests it. The benefit is confined to —+and this is the point — keeping everything *else* responsive while it runs.++It also does not make the responsiveness unbounded. Starlette dispatches `def` handlers+through anyio's thread limiter, which holds **40 tokens by default**. Forty concurrent+blocking requests occupy every worker, and the forty-first waits for a free one — as does+anything else that needs a thread, including the synchronous auth dependency that runs+before a handler is even reached. So the stall does not vanish past that point, it moves:+from "one slow request freezes the server" to "the server keeps up until forty of them are+in flight at once". Note that `test_event_loop_blocking.py` probes `/api/v1/app/version`,+which has no auth dependency and no database access, so it would not show this.++Getting past that bound is not a matter of raising the token count — the single-connection+lock below it is the real ceiling. It is the reason a route that can block for minutes+(model conversion, a git clone) is worth serializing explicitly rather than letting an+arbitrary number of them pile into the pool.++## Testing it++Two tests cover this, and they do different jobs.++`tests/app/routers/test_no_blocking_async_routes.py` **enforces the rule**: it parses every+router module and fails if any route handler is `async def` without awaiting anything. This+is the one that catches a new route — a per-route test cannot, because the route does not+exist when the test is written.++`tests/app/routers/test_event_loop_blocking.py` **proves the effect** for a few+representative routes. It stubs a service method to block synchronously, issues a request+against the route under test, and asserts that an unrelated trivial route still answers+while that request is in flight.++Note what the second one measures: not the slow request's own duration, which the fix does+not change, but the latency of other requests during it. A benchmark of the slow endpoint+alone will show no improvement and is the wrong instrument here.++If you call a route handler directly from a test, call it like the plain function it now is+— no `await`, no `asyncio.run`.diff --git a/invokeai/app/api/auth_dependencies.py b/invokeai/app/api/auth_dependencies.pyindex 1ba768a94c..42b27d8ad0 100644--- a/invokeai/app/api/auth_dependencies.py+++ b/invokeai/app/api/auth_dependencies.py@@ -27,7 +27,7 @@ def _validate_token(token: str, invalid_detail: str) -> TokenData:return token_data-async def get_current_user(+def get_current_user(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],) -> TokenData:"""Get current authenticated user from Bearer token.@@ -76,7 +76,7 @@ async def get_current_user(return token_data-async def get_current_user_or_default(+def get_current_user_or_default(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],) -> TokenData:"""Get current authenticated user from Bearer token, or return a default system user if not authenticated.@@ -128,7 +128,7 @@ async def get_current_user_or_default(return token_data-async def get_current_media_user_or_default(+def get_current_media_user_or_default(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],media_token: Annotated[str | None, Cookie(alias=MEDIA_TOKEN_COOKIE)] = None,) -> TokenData:@@ -146,6 +146,11 @@ async def require_admin() -> TokenData:"""Require admin role for the current user.+ Stays `async def`, unlike the dependencies it builds on: this only reads a field off the+ already-resolved token data. Declaring it `def` would buy a threadpool round-trip per admin+ request and nothing else. The `users.get` that can block lives in `get_current_user`, which+ is synchronous for that reason.+Args:current_user: The current authenticated user's token data@@ -165,6 +170,8 @@ async def require_admin_or_default() -> TokenData:"""Require admin role for the current user, or return default system admin in single-user mode.+ `async def` for the same reason as `require_admin`: it does no blocking work of its own.+This dependency is useful for admin-only endpoints that should work in both single-user and multiuser modes.When multiuser mode is disabled (default), this always returns a system user with admin privileges.diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.pyindex 75ef2dea75..3564e296b1 100644--- a/invokeai/app/api/routers/app_info.py+++ b/invokeai/app/api/routers/app_info.py@@ -52,12 +52,12 @@ class AppVersion(BaseModel):@app_router.get("/version", operation_id="app_version", status_code=200, response_model=AppVersion)-async def get_version() -> AppVersion:+def get_version() -> AppVersion:return AppVersion(version=__version__)@app_router.get("/app_deps", operation_id="get_app_deps", status_code=200, response_model=dict[str, str])-async def get_app_deps(current_user: CurrentUserOrDefault) -> dict[str, str]:+def get_app_deps(current_user: CurrentUserOrDefault) -> dict[str, str]:deps: dict[str, str] = {dist.metadata["Name"]: dist.version for dist in distributions()}try:cuda = getattr(getattr(torch, "version", None), "cuda", None) or "N/A" # pyright: ignore[reportAttributeAccessIssue]@@ -72,7 +72,7 @@ async def get_app_deps(current_user: CurrentUserOrDefault) -> dict[str, str]:@app_router.get("/patchmatch_status", operation_id="get_patchmatch_status", status_code=200, response_model=bool)-async def get_patchmatch_status(current_user: CurrentUserOrDefault) -> bool:+def get_patchmatch_status(current_user: CurrentUserOrDefault) -> bool:return PatchMatch.patchmatch_available()@@ -217,7 +217,7 @@ def _redact_config_secrets(config: InvokeAIAppConfig) -> InvokeAIAppConfig:status_code=200,response_model=list[GenerationDeviceOption],)-async def get_generation_device_options(current_user: CurrentUserOrDefault) -> list[GenerationDeviceOption]:+def get_generation_device_options(current_user: CurrentUserOrDefault) -> list[GenerationDeviceOption]:"""List the devices available for generation, for use with the `generation_devices` setting."""options: list[GenerationDeviceOption] = []if torch.cuda.is_available():@@ -246,7 +246,7 @@ async def get_generation_device_options(current_user: CurrentUserOrDefault) -> l@app_router.get("/runtime_config", operation_id="get_runtime_config", status_code=200, response_model=InvokeAIAppConfigWithSetFields)-async def get_runtime_config(current_admin: AdminUserOrDefault) -> InvokeAIAppConfigWithSetFields:+def get_runtime_config(current_admin: AdminUserOrDefault) -> InvokeAIAppConfigWithSetFields:config = get_config()return InvokeAIAppConfigWithSetFields(set_fields=config.model_fields_set, config=_redact_config_secrets(config))@@ -257,7 +257,7 @@ async def get_runtime_config(current_admin: AdminUserOrDefault) -> InvokeAIAppCostatus_code=200,response_model=InvokeAIAppConfigWithSetFields,)-async def update_runtime_config(+def update_runtime_config(_: AdminUserOrDefault,changes: UpdateAppGenerationSettingsRequest = Body(description="Writable runtime configuration changes"),) -> InvokeAIAppConfigWithSetFields:@@ -290,7 +290,7 @@ async def update_runtime_config(status_code=200,response_model=list[ExternalProviderStatusModel],)-async def get_external_provider_statuses(current_user: CurrentUserOrDefault) -> list[ExternalProviderStatusModel]:+def get_external_provider_statuses(current_user: CurrentUserOrDefault) -> list[ExternalProviderStatusModel]:statuses = ApiDependencies.invoker.services.external_generation.get_provider_statuses()return [status_to_model(status) for status in statuses.values()]@@ -301,7 +301,7 @@ async def get_external_provider_statuses(current_user: CurrentUserOrDefault) ->status_code=200,response_model=list[ExternalProviderConfigModel],)-async def get_external_provider_configs(current_admin: AdminUserOrDefault) -> list[ExternalProviderConfigModel]:+def get_external_provider_configs(current_admin: AdminUserOrDefault) -> list[ExternalProviderConfigModel]:config = get_config()return [_build_external_provider_config(provider_id, config) for provider_id in EXTERNAL_PROVIDER_FIELDS]@@ -312,7 +312,7 @@ async def get_external_provider_configs(current_admin: AdminUserOrDefault) -> listatus_code=200,response_model=ExternalProviderConfigModel,)-async def set_external_provider_config(+def set_external_provider_config(_: AdminUserOrDefault,provider_id: str = Path(description="The external provider identifier"),update: ExternalProviderConfigUpdate = Body(description="External provider configuration settings"),@@ -343,7 +343,7 @@ async def set_external_provider_config(status_code=200,response_model=ExternalProviderConfigModel,)-async def reset_external_provider_config(+def reset_external_provider_config(_: AdminUserOrDefault,provider_id: str = Path(description="The external provider identifier"),) -> ExternalProviderConfigModel:@@ -452,7 +452,7 @@ def _remove_external_models_for_provider(provider_id: str) -> None:responses={200: {"description": "The operation was successful"}},response_model=LogLevel,)-async def get_log_level(current_admin: AdminUserOrDefault) -> LogLevel:+def get_log_level(current_admin: AdminUserOrDefault) -> LogLevel:"""Returns the log level"""return LogLevel(ApiDependencies.invoker.services.logger.level)@@ -463,7 +463,7 @@ async def get_log_level(current_admin: AdminUserOrDefault) -> LogLevel:responses={200: {"description": "The operation was successful"}},response_model=LogLevel,)-async def set_log_level(+def set_log_level(current_admin: AdminUserOrDefault,level: LogLevel = Body(description="New log verbosity level"),) -> LogLevel:@@ -477,7 +477,7 @@ async def set_log_level(operation_id="clear_invocation_cache",responses={200: {"description": "The operation was successful"}},)-async def clear_invocation_cache(current_admin: AdminUserOrDefault) -> None:+def clear_invocation_cache(current_admin: AdminUserOrDefault) -> None:"""Clears the invocation cache"""ApiDependencies.invoker.services.invocation_cache.clear()@@ -487,7 +487,7 @@ async def clear_invocation_cache(current_admin: AdminUserOrDefault) -> None:operation_id="enable_invocation_cache",responses={200: {"description": "The operation was successful"}},)-async def enable_invocation_cache(current_admin: AdminUserOrDefault) -> None:+def enable_invocation_cache(current_admin: AdminUserOrDefault) -> None:"""Clears the invocation cache"""ApiDependencies.invoker.services.invocation_cache.enable()@@ -497,7 +497,7 @@ async def enable_invocation_cache(current_admin: AdminUserOrDefault) -> None:operation_id="disable_invocation_cache",responses={200: {"description": "The operation was successful"}},)-async def disable_invocation_cache(current_admin: AdminUserOrDefault) -> None:+def disable_invocation_cache(current_admin: AdminUserOrDefault) -> None:"""Clears the invocation cache"""ApiDependencies.invoker.services.invocation_cache.disable()@@ -507,6 +507,6 @@ async def disable_invocation_cache(current_admin: AdminUserOrDefault) -> None:operation_id="get_invocation_cache_status",responses={200: {"model": InvocationCacheStatus}},)-async def get_invocation_cache_status(current_admin: AdminUserOrDefault) -> InvocationCacheStatus:+def get_invocation_cache_status(current_admin: AdminUserOrDefault) -> InvocationCacheStatus:"""Clears the invocation cache"""return ApiDependencies.invoker.services.invocation_cache.get_status()diff --git a/invokeai/app/api/routers/auth.py b/invokeai/app/api/routers/auth.pyindex f6a767c7c8..ec6f3146c7 100644--- a/invokeai/app/api/routers/auth.py+++ b/invokeai/app/api/routers/auth.py@@ -129,7 +129,7 @@ class SetupStatusResponse(BaseModel):@auth_router.get("/status", response_model=SetupStatusResponse)-async def get_setup_status() -> SetupStatusResponse:+def get_setup_status() -> SetupStatusResponse:"""Check if initial administrator setup is required.Returns:@@ -163,7 +163,7 @@ async def get_setup_status() -> SetupStatusResponse:@auth_router.post("/login", response_model=LoginResponse)-async def login(+def login(login_request: Annotated[LoginRequest, Body(description="Login credentials")],request: Request,response: Response,@@ -223,7 +223,7 @@ async def login(@auth_router.post("/logout", response_model=LogoutResponse)-async def logout(+def logout(current_user: CurrentUser,request: Request,response: Response,@@ -250,7 +250,7 @@ async def logout(@auth_router.post("/media-cookie", response_model=MediaCookieResponse)-async def refresh_media_cookie(+def refresh_media_cookie(request: Request,response: Response,_current_user: CurrentUserOrDefault,@@ -297,7 +297,7 @@ async def refresh_media_cookie(@auth_router.get("/me", response_model=UserDTO)-async def get_current_user_info(+def get_current_user_info(current_user: CurrentUser,) -> UserDTO:"""Get current authenticated user's information.@@ -321,7 +321,7 @@ async def get_current_user_info(@auth_router.post("/setup", response_model=SetupResponse)-async def setup_admin(+def setup_admin(request: Annotated[SetupRequest, Body(description="Admin account details")],) -> SetupResponse:"""Set up initial administrator account.@@ -423,7 +423,7 @@ class GeneratePasswordResponse(BaseModel):@auth_router.get("/generate-password", response_model=GeneratePasswordResponse)-async def generate_password(+def generate_password(current_user: CurrentUser,) -> GeneratePasswordResponse:"""Generate a strong random password.@@ -444,7 +444,7 @@ async def generate_password(@auth_router.get("/users", response_model=list[UserDTO])-async def list_users(+def list_users(current_user: AdminUser,) -> list[UserDTO]:"""List all users. Requires admin privileges.@@ -460,7 +460,7 @@ async def list_users(@auth_router.post("/users", response_model=UserDTO, status_code=status.HTTP_201_CREATED)-async def create_user(+def create_user(request: Annotated[AdminUserCreateRequest, Body(description="New user details")],current_user: AdminUser,) -> UserDTO:@@ -490,7 +490,7 @@ async def create_user(@auth_router.get("/users/{user_id}", response_model=UserDTO)-async def get_user(+def get_user(user_id: Annotated[str, Path(description="User ID")],current_user: AdminUser,) -> UserDTO:@@ -513,7 +513,7 @@ async def get_user(@auth_router.patch("/users/{user_id}", response_model=UserDTO)-async def update_user(+def update_user(user_id: Annotated[str, Path(description="User ID")],request: Annotated[AdminUserUpdateRequest, Body(description="User fields to update")],current_user: AdminUser,@@ -546,7 +546,7 @@ async def update_user(@auth_router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)-async def delete_user(+def delete_user(user_id: Annotated[str, Path(description="User ID")],current_user: AdminUser,) -> None:@@ -581,7 +581,7 @@ async def delete_user(@auth_router.patch("/me", response_model=UserDTO)-async def update_current_user(+def update_current_user(request: Annotated[UserProfileUpdateRequest, Body(description="Profile fields to update")],current_user: CurrentUser,) -> UserDTO:diff --git a/invokeai/app/api/routers/board_images.py b/invokeai/app/api/routers/board_images.pyindex ea0273f02d..00c5c3a9be 100644--- a/invokeai/app/api/routers/board_images.py+++ b/invokeai/app/api/routers/board_images.py@@ -58,7 +58,7 @@ def _assert_image_direct_owner(image_name: str, current_user: CurrentUserOrDefaustatus_code=201,response_model=AddImagesToBoardResult,)-async def add_image_to_board(+def add_image_to_board(current_user: CurrentUserOrDefault,board_id: str = Body(description="The id of the board to add to"),image_name: str = Body(description="The name of the image to add"),@@ -93,7 +93,7 @@ async def add_image_to_board(status_code=201,response_model=RemoveImagesFromBoardResult,)-async def remove_image_from_board(+def remove_image_from_board(current_user: CurrentUserOrDefault,image_name: str = Body(description="The name of the image to remove", embed=True),) -> RemoveImagesFromBoardResult:@@ -129,7 +129,7 @@ async def remove_image_from_board(status_code=201,response_model=AddImagesToBoardResult,)-async def add_images_to_board(+def add_images_to_board(current_user: CurrentUserOrDefault,board_id: str = Body(description="The id of the board to add to"),image_names: list[str] = Body(description="The names of the images to add", embed=True),@@ -183,7 +183,7 @@ async def add_images_to_board(status_code=201,response_model=RemoveImagesFromBoardResult,)-async def remove_images_from_board(+def remove_images_from_board(current_user: CurrentUserOrDefault,image_names: list[str] = Body(description="The names of the images to remove", embed=True),) -> RemoveImagesFromBoardResult:diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.pyindex c6adeab850..895f73b73c 100644--- a/invokeai/app/api/routers/boards.py+++ b/invokeai/app/api/routers/boards.py@@ -49,7 +49,7 @@ class DeleteBoardResult(BaseModel):status_code=201,response_model=BoardDTO,)-async def create_board(+def create_board(current_user: CurrentUserOrDefault,board_name: str = Query(description="The name of the board to create", max_length=300),) -> BoardDTO:@@ -62,7 +62,7 @@ async def create_board(@boards_router.get("/{board_id}", operation_id="get_board", response_model=BoardDTO)-async def get_board(+def get_board(current_user: CurrentUserOrDefault,board_id: str = Path(description="The id of board to get"),) -> BoardDTO:@@ -97,7 +97,7 @@ async def get_board(status_code=201,response_model=BoardDTO,)-async def update_board(+def update_board(current_user: CurrentUserOrDefault,board_id: str = Path(description="The id of board to update"),changes: BoardChanges = Body(description="The changes to apply to the board"),@@ -209,7 +209,7 @@ def delete_board(operation_id="list_boards",response_model=Union[OffsetPaginatedResults[BoardDTO], list[BoardDTO]],)-async def list_boards(+def list_boards(current_user: CurrentUserOrDefault,order_by: BoardRecordOrderBy = Query(default=BoardRecordOrderBy.CreatedAt, description="The attribute to order by"),direction: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The direction to order by"),@@ -239,7 +239,7 @@ async def list_boards(operation_id="list_all_board_image_names",response_model=list[str],)-async def list_all_board_image_names(+def list_all_board_image_names(current_user: CurrentUserOrDefault,board_id: str = Path(description="The id of the board or 'none' for uncategorized images"),categories: list[ImageCategory] | None = Query(default=None, description="The categories of image to include."),diff --git a/invokeai/app/api/routers/client_state.py b/invokeai/app/api/routers/client_state.pyindex cd92263f97..07790c7182 100644--- a/invokeai/app/api/routers/client_state.py+++ b/invokeai/app/api/routers/client_state.py@@ -13,7 +13,7 @@ client_state_router = APIRouter(prefix="/v1/client_state", tags=["client_state"]operation_id="get_client_state_by_key",response_model=str | None,)-async def get_client_state_by_key(+def get_client_state_by_key(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id (ignored, kept for backwards compatibility)"),key: str = Query(..., description="Key to get"),@@ -31,7 +31,7 @@ async def get_client_state_by_key(operation_id="set_client_state",response_model=str,)-async def set_client_state(+def set_client_state(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id (ignored, kept for backwards compatibility)"),key: str = Query(..., description="Key to set"),@@ -50,7 +50,7 @@ async def set_client_state(operation_id="get_client_state_keys_by_prefix",response_model=list[str],)-async def get_client_state_keys_by_prefix(+def get_client_state_keys_by_prefix(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id (ignored, kept for backwards compatibility)"),prefix: str = Query(..., description="Prefix to filter keys by"),@@ -70,7 +70,7 @@ async def get_client_state_keys_by_prefix(operation_id="delete_client_state_by_key",responses={204: {"description": "Client state key deleted"}},)-async def delete_client_state_by_key(+def delete_client_state_by_key(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id (ignored, kept for backwards compatibility)"),key: str = Query(..., description="Key to delete"),@@ -88,7 +88,7 @@ async def delete_client_state_by_key(operation_id="delete_client_state",responses={204: {"description": "Client state deleted"}},)-async def delete_client_state(+def delete_client_state(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id (ignored, kept for backwards compatibility)"),) -> None:diff --git a/invokeai/app/api/routers/custom_nodes.py b/invokeai/app/api/routers/custom_nodes.pyindex 35f6107d56..77794ef1ef 100644--- a/invokeai/app/api/routers/custom_nodes.py+++ b/invokeai/app/api/routers/custom_nodes.py@@ -5,6 +5,7 @@ import reimport shutilimport subprocessimport sys+import threadingimport tracebackfrom importlib.util import module_from_spec, spec_from_file_locationfrom pathlib import Path@@ -31,6 +32,17 @@ logger = InvokeAILogger.get_logger()PACK_MANIFEST_FILENAME = ".invokeai_pack_manifest.json"PACK_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")+# 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."""@@ -154,7 +166,7 @@ def _get_installed_packs() -> list[NodePackInfo]:operation_id="list_custom_node_packs",response_model=NodePackListResponse,)-async def list_custom_node_packs(current_admin: AdminUserOrDefault) -> NodePackListResponse:+def list_custom_node_packs(current_admin: AdminUserOrDefault) -> NodePackListResponse:"""Lists all installed custom node packs.Admin-only: the response includes absolute filesystem paths, and non-admins have no@@ -169,7 +181,7 @@ async def list_custom_node_packs(current_admin: AdminUserOrDefault) -> NodePackLoperation_id="install_custom_node_pack",response_model=InstallNodePackResponse,)-async def install_custom_node_pack(+def install_custom_node_pack(current_admin: AdminUserOrDefault,request: InstallNodePackRequest = Body(description="The source URL to install from."),) -> InstallNodePackResponse:@@ -191,6 +203,17 @@ async def install_custom_node_pack(target_dir = custom_nodes_path / pack_name+ with _PACK_MUTATION_LOCK:+ return _install_pack(source, pack_name, target_dir, owner_user_id=current_admin.user_id)+++def _install_pack(source: str, pack_name: str, target_dir: Path, owner_user_id: str) -> InstallNodePackResponse:+ """Clones and loads a pack. Callers must hold `_PACK_MUTATION_LOCK`.++ The exists-check and the cleanup `rmtree` in the failure paths below are only safe as a pair+ while no other pack operation can run: without the lock two installs of the same pack both+ pass the check, and the one whose clone fails deletes the other's freshly cloned directory.+ """if target_dir.exists():return InstallNodePackResponse(name=pack_name,@@ -241,7 +264,7 @@ async def install_custom_node_pack(_load_node_pack(pack_name, target_dir)# Import any workflows found in the pack, owned by the installing admin and shared with all users- imported_workflow_ids = _import_workflows_from_pack(target_dir, pack_name, owner_user_id=current_admin.user_id)+ imported_workflow_ids = _import_workflows_from_pack(target_dir, pack_name, owner_user_id=owner_user_id)_write_pack_manifest(target_dir, imported_workflow_ids)workflows_imported = len(imported_workflow_ids)workflow_msg = f" Imported {workflows_imported} workflow(s)." if workflows_imported > 0 else ""@@ -285,7 +308,7 @@ async def install_custom_node_pack(operation_id="uninstall_custom_node_pack",response_model=UninstallNodePackResponse,)-async def uninstall_custom_node_pack(+def uninstall_custom_node_pack(current_admin: AdminUserOrDefault,pack_name: str,) -> UninstallNodePackResponse:@@ -302,6 +325,12 @@ async def uninstall_custom_node_pack(custom_nodes_path = _get_custom_nodes_path()target_dir = custom_nodes_path / pack_name+ with _PACK_MUTATION_LOCK:+ return _uninstall_pack(pack_name, target_dir)+++def _uninstall_pack(pack_name: str, target_dir: Path) -> UninstallNodePackResponse:+ """Removes a pack and its imported workflows. Callers must hold `_PACK_MUTATION_LOCK`."""if not target_dir.exists():return UninstallNodePackResponse(name=pack_name,@@ -357,7 +386,7 @@ async def uninstall_custom_node_pack("/reload",operation_id="reload_custom_nodes",)-async def reload_custom_nodes(current_admin: AdminUserOrDefault) -> dict[str, str]:+def reload_custom_nodes(current_admin: AdminUserOrDefault) -> dict[str, str]:"""Triggers a reload of all custom nodes.This re-scans the nodes directory and loads any new node packs.@@ -371,12 +400,15 @@ async def reload_custom_nodes(current_admin: AdminUserOrDefault) -> dict[str, stfrom invokeai.app.invocations.load_custom_nodes import load_custom_nodes- load_custom_nodes(custom_nodes_path, logger)+ # Imports pack modules and registers their invocations, so it must not run alongside an+ # install or uninstall doing the same to the same directory.+ with _PACK_MUTATION_LOCK:+ load_custom_nodes(custom_nodes_path, logger)- # Invalidate the OpenAPI schema cache so the frontend gets updated node definitions- from invokeai.app.api_app import app+ # Invalidate the OpenAPI schema cache so the frontend gets updated node definitions+ from invokeai.app.api_app import app- app.openapi_schema = None+ app.openapi_schema = Nonereturn {"status": "Custom nodes reloaded successfully."}diff --git a/invokeai/app/api/routers/gallery.py b/invokeai/app/api/routers/gallery.pyindex a70822c5af..1b63d31c43 100644--- a/invokeai/app/api/routers/gallery.py+++ b/invokeai/app/api/routers/gallery.py@@ -6,7 +6,7 @@ from fastapi.routing import APIRouterfrom invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers.images import _assert_board_read_access-from invokeai.app.services.gallery.gallery_common import GalleryItem, GalleryItemNamesResult+from invokeai.app.services.gallery.gallery_common import GalleryItem, GalleryItemNames, GalleryItemNamesResultfrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatedResultsfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection@@ -19,7 +19,7 @@ gallery_router = APIRouter(prefix="/v1/gallery", tags=["gallery"])operation_id="list_gallery_items",response_model=OffsetPaginatedResults[GalleryItem],)-async def list_gallery_items(+def list_gallery_items(current_user: CurrentUserOrDefault,origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of items to list."),categories: Optional[list[ImageCategory]] = Query(@@ -58,12 +58,63 @@ async 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.",+ ),+ 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,+ )+ 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",response_model=GalleryItemNamesResult,+ deprecated=True,)-async def get_gallery_item_names(+def get_gallery_item_names(current_user: CurrentUserOrDefault,origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of items to list."),categories: Optional[list[ImageCategory]] = Query(@@ -79,7 +130,12 @@ async def get_gallery_item_names(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"),) -> 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 --git a/invokeai/app/api/routers/image_moves.py b/invokeai/app/api/routers/image_moves.pyindex 0fe328ea9e..ecbebc2074 100644--- a/invokeai/app/api/routers/image_moves.py+++ b/invokeai/app/api/routers/image_moves.py@@ -65,7 +65,7 @@ def _status_to_response(service_status: ImageMoveBackgroundStatus | dict) -> Imaresponse_model=ImageMoveStatusResponse,status_code=status.HTTP_202_ACCEPTED,)-async def start_image_move(_: AdminUserOrDefault) -> ImageMoveStatusResponse:+def start_image_move(_: AdminUserOrDefault) -> ImageMoveStatusResponse:try:return _status_to_response(_get_image_move_service().start_background_move_all())except (ImageMoveJobAlreadyRunning, ImageMoveQueueActive) as e:@@ -78,7 +78,7 @@ async def start_image_move(_: AdminUserOrDefault) -> ImageMoveStatusResponse:response_model=ImageMoveStatusResponse,status_code=status.HTTP_202_ACCEPTED,)-async def start_image_move_recovery(_: AdminUserOrDefault) -> ImageMoveStatusResponse:+def start_image_move_recovery(_: AdminUserOrDefault) -> ImageMoveStatusResponse:try:return _status_to_response(_get_image_move_service().start_background_recovery())except ImageMoveJobAlreadyRunning as e:@@ -90,5 +90,5 @@ async def start_image_move_recovery(_: AdminUserOrDefault) -> ImageMoveStatusResoperation_id="get_image_move_status",response_model=ImageMoveStatusResponse,)-async def get_image_move_status(_: AdminUserOrDefault) -> ImageMoveStatusResponse:+def get_image_move_status(_: AdminUserOrDefault) -> ImageMoveStatusResponse:return _status_to_response(_get_image_move_service().get_background_status())diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.pyindex b9e06befb9..d352b7bd77 100644--- a/invokeai/app/api/routers/images.py+++ b/invokeai/app/api/routers/images.py@@ -1,3 +1,4 @@+import asyncioimport ioimport jsonimport traceback@@ -105,7 +106,7 @@ async def upload_image(from invokeai.app.services.board_records.board_records_common import BoardVisibilitytry:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ 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 (@@ -115,22 +116,25 @@ async def upload_image():raise HTTPException(status_code=403, detail="Not authorized to upload to this board")- 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")contents = await file.read()try:- pil_image = Image.open(io.BytesIO(contents))+ pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))except Exception:ApiDependencies.invoker.services.logger.error(traceback.format_exc())raise HTTPException(status_code=415, detail="Failed to read image")if crop_visible:try:- bbox = pil_image.getbbox()- pil_image = pil_image.crop(bbox)++ def _crop() -> Image.Image:+ return pil_image.crop(pil_image.getbbox())++ pil_image = await asyncio.to_thread(_crop)except Exception:raise HTTPException(status_code=500, detail="Failed to crop image")@@ -143,14 +147,18 @@ async def upload_image(try:# heuristic_resize_fast expects an RGB or RGBA image- pil_rgba = pil_image.convert("RGBA")- np_image = pil_to_np(pil_rgba)- np_image = heuristic_resize_fast(np_image, (resize_dims.width, resize_dims.height))- pil_image = np_to_pil(np_image)+ def _resize() -> Image.Image:+ pil_rgba = pil_image.convert("RGBA")+ np_image = pil_to_np(pil_rgba)+ resized_np_image = heuristic_resize_fast(np_image, (resize_dims.width, resize_dims.height))+ return np_to_pil(resized_np_image)++ pil_image = await asyncio.to_thread(_resize)except Exception:raise HTTPException(status_code=500, detail="Failed to resize image")- extracted_metadata = extract_metadata_from_image(+ extracted_metadata = await asyncio.to_thread(+ extract_metadata_from_image,pil_image=pil_image,invokeai_metadata_override=metadata,invokeai_workflow_override=None,@@ -159,7 +167,8 @@ async def upload_image()try:- image_dto = ApiDependencies.invoker.services.images.create(+ image_dto = await asyncio.to_thread(+ ApiDependencies.invoker.services.images.create,image=pil_image,image_origin=ResourceOrigin.EXTERNAL,image_category=image_category,@@ -187,7 +196,7 @@ class ImageUploadEntry(BaseModel):@images_router.post("/", operation_id="create_image_upload_entry")-async def create_image_upload_entry(+def create_image_upload_entry(_: CurrentUserOrDefault,width: int = Body(description="The width of the image"),height: int = Body(description="The height of the image"),@@ -199,7 +208,7 @@ async def create_image_upload_entry(@images_router.delete("/i/{image_name}", operation_id="delete_image", response_model=DeleteImagesResult)-async def delete_image(+def delete_image(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of the image to delete"),) -> DeleteImagesResult:@@ -227,7 +236,7 @@ async def delete_image(@images_router.delete("/intermediates", operation_id="clear_intermediates")-async def clear_intermediates(+def clear_intermediates(current_user: CurrentUserOrDefault,) -> int:"""Clears all intermediates. Requires admin."""@@ -243,7 +252,7 @@ async def clear_intermediates(@images_router.get("/intermediates", operation_id="get_intermediates_count")-async def get_intermediates_count(+def get_intermediates_count(current_user: CurrentUserOrDefault,) -> int:"""Gets the count of intermediate images. Non-admin users only see their own intermediates."""@@ -260,7 +269,7 @@ async def get_intermediates_count(operation_id="update_image",response_model=ImageDTO,)-async def update_image(+def update_image(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of the image to update"),image_changes: ImageRecordChanges = Body(description="The changes to apply to the image"),@@ -280,7 +289,7 @@ async def update_image(operation_id="get_image_dto",response_model=ImageDTO,)-async def get_image_dto(+def get_image_dto(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of image to get"),) -> ImageDTO:@@ -298,7 +307,7 @@ async def get_image_dto(operation_id="get_image_metadata",response_model=Optional[MetadataField],)-async def get_image_metadata(+def get_image_metadata(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of image to get"),) -> Optional[MetadataField]:@@ -319,7 +328,7 @@ class WorkflowAndGraphResponse(BaseModel):@images_router.get("/i/{image_name}/workflow", operation_id="get_image_workflow", response_model=WorkflowAndGraphResponse)-async def get_image_workflow(+def get_image_workflow(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of image whose workflow to get"),) -> WorkflowAndGraphResponse:@@ -358,7 +367,7 @@ async def get_image_workflow(404: {"description": "Image not found"},},)-async def get_image_full(+def get_image_full(current_user: CurrentMediaUserOrDefault,image_name: str = Path(description="The name of full-resolution image file to get"),) -> Response:@@ -394,7 +403,7 @@ async def get_image_full(404: {"description": "Image not found"},},)-async def get_image_thumbnail(+def get_image_thumbnail(current_user: CurrentMediaUserOrDefault,image_name: str = Path(description="The name of thumbnail image file to get"),) -> Response:@@ -422,7 +431,7 @@ async def get_image_thumbnail(operation_id="get_image_urls",response_model=ImageUrlsDTO,)-async def get_image_urls(+def get_image_urls(current_user: CurrentUserOrDefault,image_name: str = Path(description="The name of the image whose URL to get"),) -> ImageUrlsDTO:@@ -446,7 +455,7 @@ async def get_image_urls(operation_id="list_image_dtos",response_model=OffsetPaginatedResults[ImageDTO],)-async def list_image_dtos(+def list_image_dtos(current_user: CurrentUserOrDefault,image_origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of images to list."),categories: Optional[list[ImageCategory]] = Query(default=None, description="The categories of image to include."),@@ -486,7 +495,7 @@ async def list_image_dtos(@images_router.post("/delete", operation_id="delete_images_from_list", response_model=DeleteImagesResult)-async def delete_images_from_list(+def delete_images_from_list(current_user: CurrentUserOrDefault,image_names: list[str] = Body(description="The list of names of images to delete", embed=True),) -> DeleteImagesResult:@@ -534,7 +543,7 @@ async def delete_images_from_list(@images_router.delete("/uncategorized", operation_id="delete_uncategorized_images", response_model=DeleteImagesResult)-async def delete_uncategorized_images(+def delete_uncategorized_images(current_user: CurrentUserOrDefault,) -> DeleteImagesResult:"""Deletes all uncategorized images owned by the current user (or all if admin)"""@@ -573,7 +582,7 @@ class ImagesUpdatedFromListResult(BaseModel):@images_router.post("/star", operation_id="star_images_in_list", response_model=StarredImagesResult)-async def star_images_in_list(+def star_images_in_list(current_user: CurrentUserOrDefault,image_names: list[str] = Body(description="The list of names of images to star", embed=True),) -> StarredImagesResult:@@ -610,7 +619,7 @@ async def star_images_in_list(@images_router.post("/unstar", operation_id="unstar_images_in_list", response_model=UnstarredImagesResult)-async def unstar_images_in_list(+def unstar_images_in_list(current_user: CurrentUserOrDefault,image_names: list[str] = Body(description="The list of names of images to unstar", embed=True),) -> UnstarredImagesResult:@@ -658,7 +667,7 @@ class ImagesDownloaded(BaseModel):@images_router.post("/download", operation_id="download_images_from_list", response_model=ImagesDownloaded, status_code=202)-async def download_images_from_list(+def download_images_from_list(current_user: CurrentUserOrDefault,background_tasks: BackgroundTasks,image_names: Optional[list[str]] = Body(@@ -707,7 +716,7 @@ async def download_images_from_list(404: {"description": "Image not found"},},)-async def get_bulk_download_item(+def get_bulk_download_item(current_user: CurrentUserOrDefault,background_tasks: BackgroundTasks,bulk_download_item_name: str = Path(description="The bulk_download_item_name of the bulk download item to get"),@@ -740,8 +749,8 @@ async def get_bulk_download_item(raise HTTPException(status_code=404)-@images_router.get("/names", operation_id="get_image_names")-async def get_image_names(+@images_router.get("/names", operation_id="get_image_names", deprecated=True)+def get_image_names(current_user: CurrentUserOrDefault,image_origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of images to list."),categories: Optional[list[ImageCategory]] = Query(default=None, description="The categories of image to include."),@@ -754,7 +763,11 @@ async def get_image_names(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"),) -> 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":@@ -782,7 +795,7 @@ async def get_image_names(operation_id="get_images_by_names",responses={200: {"model": list[ImageDTO]}},)-async def get_images_by_names(+def get_images_by_names(current_user: CurrentUserOrDefault,image_names: list[str] = Body(embed=True, description="Object containing list of image names to fetch DTOs for"),) -> list[ImageDTO]:diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.pyindex 09c9a8bca0..52f6544e30 100644--- a/invokeai/app/api/routers/model_manager.py+++ b/invokeai/app/api/routers/model_manager.py@@ -5,11 +5,13 @@ import asyncioimport contextlibimport ioimport pathlib+import threadingimport traceback+from collections.abc import Generatorfrom copy import deepcopyfrom enum import Enumfrom tempfile import TemporaryDirectory-from typing import List, Optional, Type+from typing import Any, List, Optional, Typeimport huggingface_hubfrom fastapi import Body, Path, Query, Response, UploadFile@@ -30,7 +32,7 @@ from invokeai.app.services.model_records import (ModelRecordOrderBy,UnknownModelException,)-from invokeai.app.services.orphaned_models import OrphanedModelInfo+from invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelInfofrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionfrom invokeai.app.util.suppress_output import SuppressOutputfrom invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig@@ -58,6 +60,76 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat,model_manager_router = APIRouter(prefix="/v2/models", tags=["model_manager"])+# Conversion loads a model, writes a diffusers copy, then swaps the record. As an `async def`+# body with no `await` it could not overlap with another request; running in the threadpool it+# can, and two conversions in flight means two models resident at once with nothing bounding the+# RAM/VRAM that takes. Held non-blocking: an admin gets a 409 telling them to wait rather than+# an HTTP request that hangs for the minutes a conversion takes.+_MODEL_CONVERSION_LOCK = threading.Lock()++# Bounding conversions against each other is not enough: deletion runs in the threadpool too, and+# conversion is a read-modify-replace spanning many service calls. Interleaved on one key, a+# delete removes the source a conversion is still reading, the conversion's own final+# `installer.delete` then fails, and the converted copy it already installed survives - so the+# admin is told 204 and the model reappears under a new key. Claiming the key makes operations on+# one model serialize while leaving different models free to run in parallel.+_MODEL_KEY_CLAIM_LOCK = threading.Lock()+_CLAIMED_MODEL_KEYS: set[str] = set()+++def _claim_model_key(key: str) -> Generator[None, None, None]:+ """Hold the exclusive claim on one model key, or raise 409 if another request holds it."""+ # The lock also guards the short install-and-register transition used by conversion. Do not+ # block a worker thread behind that transition: reject the request and let the caller retry.+ if not _MODEL_KEY_CLAIM_LOCK.acquire(blocking=False):+ raise HTTPException(+ status_code=409,+ detail="Another model operation is already in progress. Wait for it to finish and try again.",+ )+ try:+ if key in _CLAIMED_MODEL_KEYS:+ raise HTTPException(+ status_code=409,+ detail=f"Another operation on model {key} is already in progress. Wait for it to finish and try again.",+ )+ _CLAIMED_MODEL_KEYS.add(key)+ finally:+ _MODEL_KEY_CLAIM_LOCK.release()+ try:+ yield+ finally:+ with _MODEL_KEY_CLAIM_LOCK:+ _CLAIMED_MODEL_KEYS.discard(key)+++def _install_and_claim_model(+ installer: Any, model_path: pathlib.Path, config: ModelRecordChanges+) -> Generator[str, None, None]:+ """Install a model and claim its key before another request can observe it."""+ # install_path computes and registers the key internally. Serialize that registration with+ # request claims so a delete cannot observe the new record before its key is claimed.+ with _MODEL_KEY_CLAIM_LOCK:+ new_key = installer.install_path(model_path, config=config)+ if new_key in _CLAIMED_MODEL_KEYS:+ raise HTTPException(+ status_code=409,+ detail=f"Another operation on model {new_key} is already in progress. Wait for it to finish and try again.",+ )+ _CLAIMED_MODEL_KEYS.add(new_key)+ try:+ yield new_key+ finally:+ with _MODEL_KEY_CLAIM_LOCK:+ _CLAIMED_MODEL_KEYS.discard(new_key)+++# The HF token is process-global state backed by a file in the HF cache. Concurrent writers would+# interleave set/reset with the status read that follows it, so the reported status need not+# describe the token that was just written.+_HF_TOKEN_LOCK = threading.Lock()+# images are immutable; set a high max-ageIMAGE_MAX_AGE = 31536000@@ -156,7 +228,7 @@ example_model_input = {"/",operation_id="list_model_records",)-async def list_model_records(+def list_model_records(current_user: CurrentUserOrDefault,base_models: Optional[List[BaseModelType]] = Query(default=None, description="Base models to include"),model_type: Optional[ModelType] = Query(default=None, description="The type of model to get"),@@ -202,7 +274,7 @@ async def list_model_records(operation_id="list_missing_models",responses={200: {"description": "List of models with missing files"}},)-async def list_missing_models(current_user: CurrentUserOrDefault) -> ModelsList:+def list_missing_models(current_user: CurrentUserOrDefault) -> ModelsList:"""Get models whose files are missing from disk.These are models that have database entries but their corresponding@@ -229,7 +301,7 @@ async def list_missing_models(current_user: CurrentUserOrDefault) -> ModelsList:operation_id="get_model_records_by_attrs",response_model=AnyModelConfig,)-async def get_model_records_by_attrs(+def get_model_records_by_attrs(current_user: CurrentUserOrDefault,name: str = Query(description="The name of the model"),type: ModelType = Query(description="The type of the model"),@@ -251,7 +323,7 @@ async def get_model_records_by_attrs(operation_id="get_model_records_by_hash",response_model=AnyModelConfig,)-async def get_model_records_by_hash(+def get_model_records_by_hash(current_user: CurrentUserOrDefault,hash: str = Query(description="The hash of the model"),) -> AnyModelConfig:@@ -276,7 +348,7 @@ async def get_model_records_by_hash(404: {"description": "The model could not be found"},},)-async def get_model_record(+def get_model_record(current_user: CurrentUserOrDefault,key: str = Path(description="Key of the model record to fetch."),) -> AnyModelConfig:@@ -298,40 +370,48 @@ async def get_model_record(},400: {"description": "Bad request"},404: {"description": "The model could not be found"},+ 409: {"description": "Another operation on this model is already in progress"},},)-async def reidentify_model(+def reidentify_model(key: Annotated[str, Path(description="Key of the model to reidentify.")],current_admin: AdminUserOrDefault,) -> AnyModelConfig:"""Attempt to reidentify a model by re-probing its weights file."""try:- config = ApiDependencies.invoker.services.model_manager.store.get_model(key)- models_path = ApiDependencies.invoker.services.configuration.models_path- if pathlib.Path(config.path).is_relative_to(models_path):- model_path = pathlib.Path(config.path)- else:- model_path = models_path / config.path- mod = ModelOnDisk(model_path)- result = ModelConfigFactory.from_model_on_disk(mod)- if result.config is None:- raise InvalidModelException("Unable to identify model format")-- # Retain user-editable fields from the original config- result.config.path = config.path- result.config.key = config.key- result.config.name = config.name- result.config.description = config.description- result.config.cover_image = config.cover_image- if hasattr(result.config, "trigger_phrases") and hasattr(config, "trigger_phrases"):- result.config.trigger_phrases = config.trigger_phrases- result.config.source = config.source- result.config.source_type = config.source_type-- new_config = ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)- return new_config+ with _claim_model_key(key):+ return _reidentify_model(key)except UnknownModelException as e:raise HTTPException(status_code=404, detail=str(e))+ except InvalidModelException as e:+ raise HTTPException(status_code=400, detail=str(e))+++def _reidentify_model(key: str) -> AnyModelConfig:+ """Re-probe one model and rewrite its record. Callers must hold the key claim."""+ config = ApiDependencies.invoker.services.model_manager.store.get_model(key)+ models_path = ApiDependencies.invoker.services.configuration.models_path+ if pathlib.Path(config.path).is_relative_to(models_path):+ model_path = pathlib.Path(config.path)+ else:+ model_path = models_path / config.path+ mod = ModelOnDisk(model_path)+ result = ModelConfigFactory.from_model_on_disk(mod)+ if result.config is None:+ raise InvalidModelException("Unable to identify model format")++ # Retain user-editable fields from the original config+ result.config.path = config.path+ result.config.key = config.key+ result.config.name = config.name+ result.config.description = config.description+ result.config.cover_image = config.cover_image+ if hasattr(result.config, "trigger_phrases") and hasattr(config, "trigger_phrases"):+ result.config.trigger_phrases = config.trigger_phrases+ result.config.source = config.source+ result.config.source_type = config.source_type++ return ApiDependencies.invoker.services.model_manager.store.replace_model(config.key, result.config)class FoundModel(BaseModel):@@ -349,7 +429,7 @@ class FoundModel(BaseModel):status_code=200,response_model=List[FoundModel],)-async def scan_for_models(+def scan_for_models(current_admin: AdminUserOrDefault,scan_path: str = Query(description="Directory path to search for models", default=None),) -> List[FoundModel]:@@ -415,7 +495,7 @@ class HuggingFaceModels(BaseModel):status_code=200,response_model=HuggingFaceModels,)-async def get_hugging_face_models(+def get_hugging_face_models(current_admin: AdminUserOrDefault,hugging_face_repo: str = Query(description="Hugging face repo to search for models", default=None),) -> HuggingFaceModels:@@ -435,6 +515,51 @@ async def get_hugging_face_models()+def _update_model_record(key: str, changes: ModelRecordChanges) -> AnyModelConfig:+ """Update a model record and invalidate any cache affected by the change.++ Keep the complete claim and synchronous service work in one worker-thread operation. This+ route needs to await cache invalidation, but that must not leave the database read/write and+ response preparation on the event loop before and after that await.+ """+ logger = ApiDependencies.invoker.services.logger+ record_store = ApiDependencies.invoker.services.model_manager.store++ # Claimed for the whole update: a conversion running on this key carries a snapshot of the+ # record taken before it started and writes it into the replacement, so an edit accepted+ # meanwhile would be reported as saved and then silently dropped.+ with _claim_model_key(key):+ try:+ previous_config = record_store.get_model(key)+ config = record_store.update_model(key, changes=changes, allow_class_change=True)+ # Settings that change how the model loads (e.g. fp8_storage, cpu_only) are baked into the cached+ # nn.Module at load time, so toggling them on a cached model is otherwise silently a no-op until+ # the entry is evicted. Drop any unlocked cached entries for this model so the next load rebuilds.+ if _load_settings_changed(previous_config, config):+ # Drop the model from every per-device cache so the next load on any GPU rebuilds it.+ # Hold the model-load write lock so no worker is mid-construction while we invalidate:+ # a concurrent load could otherwise peek the old shared CPU weights before the drop and+ # re-register them as canonical after it. Acquiring the lock can wait on an in-flight+ # load/VRAM transfer, but this entire helper already runs off the event loop.+ with MODEL_LOAD_LOCK.write_lock():+ dropped = sum(+ cache.drop_model(key)+ for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values()+ )+ if dropped:+ logger.info(+ f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."+ )+ config = prepare_model_config_for_response(config, ApiDependencies)+ logger.info(f"Updated model: {key}")+ except UnknownModelException as e:+ raise HTTPException(status_code=404, detail=str(e))+ except ValueError as e:+ logger.error(str(e))+ raise HTTPException(status_code=409, detail=str(e))+ return config++@model_manager_router.patch("/i/{key}",operation_id="update_model_record",@@ -455,40 +580,7 @@ async def update_model_record(current_admin: AdminUserOrDefault,) -> AnyModelConfig:"""Update a model's config."""- logger = ApiDependencies.invoker.services.logger- record_store = ApiDependencies.invoker.services.model_manager.store- try:- previous_config = record_store.get_model(key)- config = record_store.update_model(key, changes=changes, allow_class_change=True)- # Settings that change how the model loads (e.g. fp8_storage, cpu_only) are baked into the cached- # nn.Module at load time, so toggling them on a cached model is otherwise silently a no-op until- # the entry is evicted. Drop any unlocked cached entries for this model so the next load rebuilds.- if _load_settings_changed(previous_config, config):- # Drop the model from every per-device cache so the next load on any GPU rebuilds it.- # Hold the model-load write lock so no worker is mid-construction while we invalidate:- # a concurrent load could otherwise peek the old shared CPU weights before the drop and- # re-register them as canonical after it. Acquiring the lock can wait on an in-flight- # load/VRAM transfer, so do it off the event loop.- def _drop_from_all_caches() -> int:- with MODEL_LOAD_LOCK.write_lock():- return sum(- cache.drop_model(key)- for cache in ApiDependencies.invoker.services.model_manager.load.ram_caches.values()- )-- dropped = await asyncio.to_thread(_drop_from_all_caches)- if dropped:- logger.info(- f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."- )- config = prepare_model_config_for_response(config, ApiDependencies)- logger.info(f"Updated model: {key}")- except UnknownModelException as e:- raise HTTPException(status_code=404, detail=str(e))- except ValueError as e:- logger.error(str(e))- raise HTTPException(status_code=409, detail=str(e))- return config+ return await asyncio.to_thread(_update_model_record, key, changes)_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")@@ -523,7 +615,7 @@ def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) ->},status_code=200,)-async def get_model_image(+def get_model_image(key: str = Path(description="The name of model image file to get"),) -> FileResponse:"""Gets an image file that previews the model"""@@ -551,6 +643,7 @@ async def get_model_image("description": "The model image was updated successfully",},400: {"description": "Bad request"},+ 409: {"description": "Another operation on this model is already in progress"},},status_code=200,)@@ -562,22 +655,25 @@ async def update_model_image(if not image.content_type or not image.content_type.startswith("image"):raise HTTPException(status_code=415, detail="Not an image")- contents = await image.read()- try:- pil_image = Image.open(io.BytesIO(contents))-- except Exception:- ApiDependencies.invoker.services.logger.error(traceback.format_exc())- raise HTTPException(status_code=415, detail="Failed to read image")-logger = ApiDependencies.invoker.services.loggermodel_images = ApiDependencies.invoker.services.model_images- try:- model_images.save(pil_image, key)- logger.info(f"Updated image for model: {key}")- except ValueError as e:- logger.error(str(e))- raise HTTPException(status_code=409, detail=str(e))+ # A conversion moves this model's image to the replacement's key when it finishes, so claim+ # the key before reading the upload and hold it until the image is saved.+ with _claim_model_key(key):+ contents = await image.read()+ try:+ pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))++ except Exception:+ logger.error(traceback.format_exc())+ raise HTTPException(status_code=415, detail="Failed to read image")++ try:+ await asyncio.to_thread(model_images.save, pil_image, key)+ logger.info(f"Updated image for model: {key}")+ except ValueError as e:+ logger.error(str(e))+ raise HTTPException(status_code=409, detail=str(e))return@@ -587,10 +683,11 @@ async def update_model_image(responses={204: {"description": "Model deleted successfully"},404: {"description": "Model not found"},+ 409: {"description": "Another operation on this model is already in progress"},},status_code=204,)-async def delete_model(+def delete_model(current_admin: AdminUserOrDefault,key: str = Path(description="Unique key of model to remove from model registry."),) -> Response:@@ -602,14 +699,15 @@ async def delete_model("""logger = ApiDependencies.invoker.services.logger- try:- installer = ApiDependencies.invoker.services.model_manager.install- installer.delete(key)- logger.info(f"Deleted model: {key}")- return Response(status_code=204)- except UnknownModelException as e:- logger.error(str(e))- raise HTTPException(status_code=404, detail=str(e))+ with _claim_model_key(key):+ try:+ installer = ApiDependencies.invoker.services.model_manager.install+ installer.delete(key)+ logger.info(f"Deleted model: {key}")+ return Response(status_code=204)+ except UnknownModelException as e:+ logger.error(str(e))+ raise HTTPException(status_code=404, detail=str(e))class BulkDeleteModelsRequest(BaseModel):@@ -646,7 +744,7 @@ class BulkReidentifyModelsResponse(BaseModel):},status_code=200,)-async def bulk_delete_models(+def bulk_delete_models(current_admin: AdminUserOrDefault,request: BulkDeleteModelsRequest = Body(description="List of model keys to delete"),) -> BulkDeleteModelsResponse:@@ -665,9 +763,15 @@ async def bulk_delete_models(for key in request.keys:try:- installer.delete(key)+ # Per key, so one model busy elsewhere is reported as a failure for that key rather+ # than aborting the whole request or racing the operation that holds it.+ with _claim_model_key(key):+ installer.delete(key)deleted.append(key)logger.info(f"Deleted model: {key}")+ except HTTPException as e:+ logger.error(f"Failed to delete model {key}: {e.detail}")+ failed.append({"key": key, "error": e.detail})except UnknownModelException as e:logger.error(f"Failed to delete model {key}: {str(e)}")failed.append({"key": key, "error": str(e)})@@ -687,7 +791,7 @@ async def bulk_delete_models(},status_code=200,)-async def bulk_reidentify_models(+def bulk_reidentify_models(current_admin: AdminUserOrDefault,request: BulkReidentifyModelsRequest = Body(description="List of model keys to reidentify"),) -> BulkReidentifyModelsResponse:@@ -697,38 +801,22 @@ async def bulk_reidentify_models(Returns a list of successfully reidentified keys and failed reidentifications with error messages."""logger = ApiDependencies.invoker.services.logger- store = ApiDependencies.invoker.services.model_manager.store- models_path = ApiDependencies.invoker.services.configuration.models_pathsucceeded = []failed = []for key in request.keys:try:- config = store.get_model(key)- if pathlib.Path(config.path).is_relative_to(models_path):- model_path = pathlib.Path(config.path)- else:- model_path = models_path / config.path- mod = ModelOnDisk(model_path)- result = ModelConfigFactory.from_model_on_disk(mod)- if result.config is None:- raise InvalidModelException("Unable to identify model format")-- # Retain user-editable fields from the original config- result.config.path = config.path- result.config.key = config.key- result.config.name = config.name- result.config.description = config.description- result.config.cover_image = config.cover_image- if hasattr(config, "trigger_phrases") and hasattr(result.config, "trigger_phrases"):- result.config.trigger_phrases = config.trigger_phrases- result.config.source = config.source- result.config.source_type = config.source_type-- store.replace_model(config.key, result.config)+ # Same claim and the same implementation as the single-model route: this loop used to+ # carry its own copy of the retain-these-fields logic, which is one edit away from the+ # two disagreeing about what a reidentification preserves.+ with _claim_model_key(key):+ _reidentify_model(key)succeeded.append(key)logger.info(f"Reidentified model: {key}")+ except HTTPException as e:+ logger.error(f"Failed to reidentify model {key}: {e.detail}")+ failed.append({"key": key, "error": e.detail})except UnknownModelException as e:logger.error(f"Failed to reidentify model {key}: {str(e)}")failed.append({"key": key, "error": str(e)})@@ -746,22 +834,26 @@ async def bulk_reidentify_models(responses={204: {"description": "Model image deleted successfully"},404: {"description": "Model image not found"},+ 409: {"description": "Another operation on this model is already in progress"},},status_code=204,)-async def delete_model_image(+def delete_model_image(current_admin: AdminUserOrDefault,key: str = Path(description="Unique key of model image to remove from model_images directory."),) -> None:logger = ApiDependencies.invoker.services.loggermodel_images = ApiDependencies.invoker.services.model_images- try:- model_images.delete(key)- logger.info(f"Deleted model image: {key}")- return- except UnknownModelException as e:- logger.error(str(e))- raise HTTPException(status_code=404, detail=str(e))+ # Claimed for the same reason as the upload: a conversion carries this model's image over to+ # the replacement's key, so a delete accepted meanwhile is undone by that copy.+ with _claim_model_key(key):+ try:+ model_images.delete(key)+ logger.info(f"Deleted model image: {key}")+ return+ except UnknownModelException as e:+ logger.error(str(e))+ raise HTTPException(status_code=404, detail=str(e))@model_manager_router.post(@@ -775,7 +867,7 @@ async def delete_model_image(},status_code=201,)-async def install_model(+def install_model(current_admin: AdminUserOrDefault,source: str = Query(description="Model source to install, can be a local path, repo_id, or remote URL"),inplace: Optional[bool] = Query(description="Whether or not to install a local model in place", default=False),@@ -846,7 +938,7 @@ async def install_model(status_code=201,response_class=HTMLResponse,)-async def install_hugging_face_model(+def install_hugging_face_model(current_admin: AdminUserOrDefault,source: str = Query(description="HuggingFace repo_id to install"),) -> HTMLResponse:@@ -967,7 +1059,7 @@ async def install_hugging_face_model("/install",operation_id="list_model_installs",)-async def list_model_installs(current_admin: AdminUserOrDefault) -> List[ModelInstallJob]:+def list_model_installs(current_admin: AdminUserOrDefault) -> List[ModelInstallJob]:"""Return the list of model install jobs.Install jobs have a numeric `id`, a `status`, and other fields that provide information on@@ -999,7 +1091,7 @@ async def list_model_installs(current_admin: AdminUserOrDefault) -> List[ModelIn404: {"description": "No such job"},},)-async def get_model_install_job(+def get_model_install_job(current_admin: AdminUserOrDefault, id: int = Path(description="Model install id")) -> ModelInstallJob:"""@@ -1022,7 +1114,7 @@ async def get_model_install_job(},status_code=201,)-async def cancel_model_install_job(+def cancel_model_install_job(current_admin: AdminUserOrDefault,id: int = Path(description="Model install job ID"),) -> None:@@ -1044,7 +1136,7 @@ async def cancel_model_install_job(},status_code=201,)-async def pause_model_install_job(+def pause_model_install_job(current_admin: AdminUserOrDefault, id: int = Path(description="Model install job ID")) -> ModelInstallJob:"""Pause the model install job corresponding to the given job ID."""@@ -1066,7 +1158,7 @@ async def pause_model_install_job(},status_code=201,)-async def resume_model_install_job(+def resume_model_install_job(current_admin: AdminUserOrDefault, id: int = Path(description="Model install job ID")) -> ModelInstallJob:"""Resume a paused model install job corresponding to the given job ID."""@@ -1088,7 +1180,7 @@ async def resume_model_install_job(},status_code=201,)-async def restart_failed_model_install_job(+def restart_failed_model_install_job(current_admin: AdminUserOrDefault, id: int = Path(description="Model install job ID")) -> ModelInstallJob:"""Restart failed or non-resumable file downloads for the given job."""@@ -1110,7 +1202,7 @@ async def restart_failed_model_install_job(},status_code=201,)-async def restart_model_install_file(+def restart_model_install_file(current_admin: AdminUserOrDefault,id: int = Path(description="Model install job ID"),file_source: AnyHttpUrl = Body(description="File download URL to restart"),@@ -1133,7 +1225,7 @@ async def restart_model_install_file(400: {"description": "Bad request"},},)-async def prune_model_install_jobs(current_admin: AdminUserOrDefault) -> Response:+def prune_model_install_jobs(current_admin: AdminUserOrDefault) -> Response:"""Prune all completed and errored jobs from the install job list."""ApiDependencies.invoker.services.model_manager.install.prune_jobs()return Response(status_code=204)@@ -1152,7 +1244,7 @@ async def prune_model_install_jobs(current_admin: AdminUserOrDefault) -> Respons409: {"description": "There is already a model registered at this location"},},)-async def convert_model(+def convert_model(current_admin: AdminUserOrDefault,key: str = Path(description="Unique key of the safetensors main model to convert to diffusers format."),) -> AnyModelConfig:@@ -1161,6 +1253,23 @@ async def convert_model(Note that during the conversion process the key and model hash will change.The return value is the model configuration for the converted model."""+ if not _MODEL_CONVERSION_LOCK.acquire(blocking=False):+ raise HTTPException(+ status_code=409,+ detail="Another model conversion is already in progress. Wait for it to finish and try again.",+ )+ try:+ # Claimed for the whole conversion, so a delete arriving mid-way is refused rather than+ # pulling the source out from under it. Deletion never takes the conversion lock, so the+ # two are ordered consistently and cannot deadlock.+ with _claim_model_key(key):+ return _convert_model(key, user_id=current_admin.user_id)+ finally:+ _MODEL_CONVERSION_LOCK.release()+++def _convert_model(key: str, user_id: str) -> AnyModelConfig:+ """Converts one model. Callers must hold `_MODEL_CONVERSION_LOCK`."""model_manager = ApiDependencies.invoker.services.model_managerloader = model_manager.loadlogger = ApiDependencies.invoker.services.logger@@ -1186,9 +1295,16 @@ async def convert_model(logger.error(msg)raise HTTPException(400, msg)- with TemporaryDirectory(dir=ApiDependencies.invoker.services.configuration.models_path) as tmpdir:+ # Under the models root so `install_path` below moves the result rather than copying it across+ # a filesystem boundary, but inside the scratch directory the orphan scan skips: a half-written+ # diffusers copy is model files with no database record, which is exactly what that scan hunts+ # for, and `DELETE /sync/orphaned` would rmtree it while it is still being written.+ scratch_dir = ApiDependencies.invoker.services.configuration.models_path / CONVERSION_SCRATCH_DIRNAME+ scratch_dir.mkdir(parents=True, exist_ok=True)++ with TemporaryDirectory(dir=scratch_dir) as tmpdir:convert_path = pathlib.Path(tmpdir) / pathlib.Path(model_config.path).stem- converted_model = loader.load_model(model_config, user_id=current_admin.user_id)+ converted_model = loader.load_model(model_config, user_id=user_id)# write the converted file to the convert pathraw_model = converted_model.modelassert hasattr(raw_model, "save_pretrained")@@ -1201,40 +1317,41 @@ async def convert_model(changes = ModelRecordChanges(name=model_config.name)store.update_model(key, changes=changes)- # install the diffusers- try:- new_key = installer.install_path(- convert_path,- config=ModelRecordChanges(- name=original_name,- description=model_config.description,- hash=model_config.hash,- source=model_config.source,- ),- )- except Exception as e:- logger.error(str(e))- store.update_model(key, changes=ModelRecordChanges(name=original_name))- raise HTTPException(status_code=409, detail=str(e))-- # Update the model image if the model had one- try:- model_image = ApiDependencies.invoker.services.model_images.get(key)- ApiDependencies.invoker.services.model_images.save(model_image, new_key)- ApiDependencies.invoker.services.model_images.delete(key)- except ModelImageFileNotFoundException:- pass-- # delete the original safetensors file- installer.delete(key)-- # delete the temporary directory- # shutil.rmtree(cache_path)+ # Install and claim the diffusers before allowing another request to observe its key.+ with contextlib.ExitStack() as conversion_stack:+ try:+ new_key = conversion_stack.enter_context(+ _install_and_claim_model(+ installer,+ convert_path,+ config=ModelRecordChanges(+ name=original_name,+ description=model_config.description,+ hash=model_config.hash,+ source=model_config.source,+ ),+ )+ )+ except Exception as e:+ logger.error(str(e))+ store.update_model(key, changes=ModelRecordChanges(name=original_name))+ raise HTTPException(status_code=409, detail=str(e))++ # Update the model image if the model had one.+ try:+ model_image = ApiDependencies.invoker.services.model_images.get(key)+ ApiDependencies.invoker.services.model_images.save(model_image, new_key)+ ApiDependencies.invoker.services.model_images.delete(key)+ except ModelImageFileNotFoundException:+ pass++ # Delete the original safetensors file.+ installer.delete(key)- # return the config record for the new diffusers directory- new_config = store.get_model(new_key)- new_config = prepare_model_config_for_response(new_config, ApiDependencies)- return new_config+ # Return the config record for the new diffusers directory.+ new_config = store.get_model(new_key)+ new_config = prepare_model_config_for_response(new_config, ApiDependencies)+ return new_configclass StarterModelResponse(BaseModel):@@ -1291,7 +1408,7 @@ def get_is_installed(@model_manager_router.get("/starter_models", operation_id="get_starter_models", response_model=StarterModelResponse)-async def get_starter_models(current_admin: AdminUserOrDefault) -> StarterModelResponse:+def get_starter_models(current_admin: AdminUserOrDefault) -> StarterModelResponse:installed_models = ApiDependencies.invoker.services.model_manager.store.search_by_attr()starter_models = deepcopy(STARTER_MODELS)starter_bundles = deepcopy(STARTER_BUNDLES)@@ -1324,7 +1441,7 @@ async def get_starter_models(current_admin: AdminUserOrDefault) -> StarterModelRresponse_model=Optional[CacheStats],summary="Get model manager RAM cache performance statistics.",)-async def get_stats(current_admin: AdminUserOrDefault) -> Optional[CacheStats]:+def get_stats(current_admin: AdminUserOrDefault) -> Optional[CacheStats]:"""Return performance statistics on the model manager's RAM cache. In multi-GPU mode there isone cache per generation device; their statistics are aggregated. Will return null if no modelshave been loaded."""@@ -1364,7 +1481,7 @@ async def get_stats(current_admin: AdminUserOrDefault) -> Optional[CacheStats]:operation_id="empty_model_cache",status_code=200,)-async def empty_model_cache(current_admin: AdminUserOrDefault) -> None:+def empty_model_cache(current_admin: AdminUserOrDefault) -> None:"""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.")@@ -1404,7 +1521,7 @@ class HFTokenHelper:@model_manager_router.get("/hf_login", operation_id="get_hf_login_status", response_model=HFTokenStatus)-async def get_hf_login_status(current_admin: AdminUserOrDefault) -> HFTokenStatus:+def get_hf_login_status(current_admin: AdminUserOrDefault) -> HFTokenStatus:token_status = HFTokenHelper.get_status()if token_status is HFTokenStatus.UNKNOWN:@@ -1414,12 +1531,14 @@ async def get_hf_login_status(current_admin: AdminUserOrDefault) -> HFTokenStatu@model_manager_router.post("/hf_login", operation_id="do_hf_login", response_model=HFTokenStatus)-async def do_hf_login(+def do_hf_login(current_admin: AdminUserOrDefault,token: str = Body(description="Hugging Face token to use for login", embed=True),) -> HFTokenStatus:- HFTokenHelper.set_token(token)- token_status = HFTokenHelper.get_status()+ # Write and read-back as one step; see _HF_TOKEN_LOCK.+ with _HF_TOKEN_LOCK:+ HFTokenHelper.set_token(token)+ token_status = HFTokenHelper.get_status()if token_status is HFTokenStatus.UNKNOWN:ApiDependencies.invoker.services.logger.warning("Unable to verify HF token")@@ -1428,8 +1547,9 @@ async def do_hf_login(@model_manager_router.delete("/hf_login", operation_id="reset_hf_token", response_model=HFTokenStatus)-async def reset_hf_token(current_admin: AdminUserOrDefault) -> HFTokenStatus:- return HFTokenHelper.reset_token()+def reset_hf_token(current_admin: AdminUserOrDefault) -> HFTokenStatus:+ with _HF_TOKEN_LOCK:+ return HFTokenHelper.reset_token()# Orphaned Models Management Routes@@ -1453,7 +1573,7 @@ class DeleteOrphanedModelsResponse(BaseModel):operation_id="get_orphaned_models",response_model=list[OrphanedModelInfo],)-async def get_orphaned_models(_: AdminUserOrDefault) -> list[OrphanedModelInfo]:+def get_orphaned_models(_: AdminUserOrDefault) -> list[OrphanedModelInfo]:"""Find orphaned model directories.Orphaned models are directories in the models folder that contain model files@@ -1480,9 +1600,7 @@ async def get_orphaned_models(_: AdminUserOrDefault) -> list[OrphanedModelInfo]:operation_id="delete_orphaned_models",response_model=DeleteOrphanedModelsResponse,)-async def delete_orphaned_models(- request: DeleteOrphanedModelsRequest, _: AdminUserOrDefault-) -> DeleteOrphanedModelsResponse:+def delete_orphaned_models(request: DeleteOrphanedModelsRequest, _: AdminUserOrDefault) -> DeleteOrphanedModelsResponse:"""Delete specified orphaned model directories.Args:diff --git a/invokeai/app/api/routers/model_relationships.py b/invokeai/app/api/routers/model_relationships.pyindex 0ec4507095..3a882038c0 100644--- a/invokeai/app/api/routers/model_relationships.py+++ b/invokeai/app/api/routers/model_relationships.py@@ -85,7 +85,7 @@ class ModelRelationshipBatchRequest(BaseModel):422: {"description": "Validation error"},},)-async def get_related_models(+def get_related_models(current_user: CurrentUserOrDefault,model_key: str = Path(..., description="The key of the model to get relationships for"),) -> list[str]:@@ -108,7 +108,7 @@ async def get_related_models(summary="Add Model Relationship",description="Creates a **bidirectional** relationship between two models, allowing each to reference the other as related.",)-async def add_model_relationship(+def add_model_relationship(current_user: AdminUserOrDefault,req: ModelRelationshipCreateRequest = Body(..., description="The model keys to relate"),) -> None:@@ -145,7 +145,7 @@ async def add_model_relationship(summary="Remove Model Relationship",description="Removes a **bidirectional** relationship between two models. The relationship must already exist.",)-async def remove_model_relationship(+def remove_model_relationship(current_user: AdminUserOrDefault,req: ModelRelationshipCreateRequest = Body(..., description="The model keys to disconnect"),) -> None:@@ -194,7 +194,7 @@ async def remove_model_relationship(summary="Get Related Model Keys (Batch)",description="Retrieves all **unique related model keys** for a list of given models. This is useful for contextual suggestions or filtering.",)-async def get_related_models_batch(+def get_related_models_batch(current_user: CurrentUserOrDefault,req: ModelRelationshipBatchRequest = Body(..., description="Model keys to check for related connections"),) -> list[str]:diff --git a/invokeai/app/api/routers/recall_parameters.py b/invokeai/app/api/routers/recall_parameters.pyindex 1f96280f4f..44ba5e05a4 100644--- a/invokeai/app/api/routers/recall_parameters.py+++ b/invokeai/app/api/routers/recall_parameters.py@@ -399,7 +399,7 @@ def _assert_recall_image_access(parameters: "RecallParameter", current_user: Curoperation_id="update_recall_parameters",response_model=dict[str, Any],)-async def update_recall_parameters(+def update_recall_parameters(current_user: CurrentUserOrDefault,queue_id: str = Path(..., description="The queue id to perform this operation on"),parameters: RecallParameter = Body(..., description="Recall parameters to update"),@@ -585,7 +585,7 @@ async def update_recall_parameters(operation_id="get_recall_parameters",response_model=dict[str, Any],)-async def get_recall_parameters(+def get_recall_parameters(current_user: CurrentUserOrDefault,queue_id: str = Path(..., description="The queue id to retrieve parameters for"),) -> dict[str, Any]:diff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.pyindex f2ec8f7cb6..e0cde55fbd 100644--- a/invokeai/app/api/routers/session_queue.py+++ b/invokeai/app/api/routers/session_queue.py@@ -1,4 +1,6 @@-from typing import Optional+import asyncio+from collections.abc import Callable+from typing import Any, Optional, TypeVarfrom fastapi import Body, HTTPException, Path, Queryfrom fastapi.routing import APIRouter@@ -24,6 +26,7 @@ from invokeai.app.services.session_queue.session_queue_common import (SessionQueueCountsByDestination,SessionQueueItem,SessionQueueItemNotFoundError,+ SessionQueueItemSummary,SessionQueueStatus,)from invokeai.app.services.shared.graph import Graph, GraphExecutionState@@ -31,6 +34,12 @@ from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionsession_queue_router = APIRouter(prefix="/v1/queue", tags=["queue"])+# Upper bound on the number of item ids a client may ask about in one request. Without it a+# caller can post tens of thousands of ids, which the SQLite layer would either expand past the+# per-statement bind limit or grind through in a long-running query. The list is meant to cover+# the rows a client actually has on screen, so this is far above any legitimate use.+MAX_QUEUE_ITEM_IDS_PER_REQUEST = 1000+class SessionQueueAndProcessorStatus(BaseModel):"""The overall status of session queue and processor"""@@ -45,54 +54,67 @@ def _get_workflow_call_root_queue_item(queue_item: SessionQueueItem) -> SessionQreturn ApiDependencies.invoker.services.session_queue.get_queue_item(queue_item.root_item_id)-def sanitize_queue_item_for_user(- queue_item: SessionQueueItem, current_user_id: str, is_admin: bool-) -> SessionQueueItem:- """Sanitize queue item for non-admin users viewing other users' items.-- For non-admin users viewing queue items belonging to other users,- only timestamps, status, and error information are exposed. All other- fields (user identity, generation parameters, graphs, workflows) are stripped.+# What a non-admin must not see on another user's queue item, and what each field is replaced+# with. One table for both the full item and the list summary: the two are different projections+# of the same row, and a second redaction list is how they drift apart - a field stripped from the+# list but left on the detail view is still leaked. Fields absent from a model are skipped, so the+# full-item-only entries below simply do not apply to the summary.+#+# Replacements are built per call so that no two sanitized items share one mutable object.+#+# `device` is deliberately not redacted: it names the GPU the instance ran the job on, which is a+# property of the hardware rather than of the other user's work, and the queue list has always+# shown it.+_REDACTIONS: dict[str, Callable[[], Any]] = {+ "user_id": lambda: "redacted",+ "user_display_name": lambda: None,+ "user_email": lambda: None,+ "batch_id": lambda: "redacted",+ "session_id": lambda: "redacted",+ "origin": lambda: None,+ "destination": lambda: None,+ "priority": lambda: 0,+ "field_values": lambda: None,+ "retried_from_item_id": lambda: None,+ "workflow_call_id": lambda: None,+ "parent_item_id": lambda: None,+ "parent_session_id": lambda: None,+ "root_item_id": lambda: None,+ "workflow_call_depth": lambda: None,+ "workflow": lambda: None,+ "error_type": lambda: None,+ "error_message": lambda: None,+ "error_traceback": lambda: None,+ "session": lambda: GraphExecutionState(id="redacted", graph=Graph()),+}++AnyQueueItem = TypeVar("AnyQueueItem", SessionQueueItem, SessionQueueItemSummary)+++def sanitize_queue_item_for_user(queue_item: AnyQueueItem, current_user_id: str, is_admin: bool) -> AnyQueueItem:+ """Sanitize a queue item, or a queue item summary, for a non-admin viewing another user's item.++ Only item_id, queue_id, status, device and the timestamps survive; identity, generation+ parameters, graphs and workflows are stripped. Admins and the item's owner see everything.Args:- queue_item: The queue item to sanitize+ queue_item: The queue item or summary to sanitizecurrent_user_id: The ID of the current user viewing the itemis_admin: Whether the current user is an adminReturns:- The sanitized queue item (sensitive fields cleared if necessary)+ The sanitized item (sensitive fields cleared if necessary)"""# Admins and item owners can see everythingif is_admin or queue_item.user_id == current_user_id:return 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- sanitized_item.session = GraphExecutionState(- id="redacted",- graph=Graph(),- )- return sanitized_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)@session_queue_router.post(@@ -109,7 +131,7 @@ async def enqueue_batch(prepend: bool = Body(default=False, description="Whether or not to prepend this batch in the queue"),) -> EnqueueBatchResult:"""Processes a batch and enqueues the output graphs for execution for the current user."""- assert_image_move_maintenance_inactive()+ await asyncio.to_thread(assert_image_move_maintenance_inactive)try:return await ApiDependencies.invoker.services.session_queue.enqueue_batch(@@ -126,7 +148,7 @@ async def enqueue_batch(200: {"model": list[SessionQueueItem]},},)-async def list_all_queue_items(+def list_all_queue_items(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),destination: Optional[str] = Query(default=None, description="The destination of queue items to fetch"),@@ -150,7 +172,7 @@ async def list_all_queue_items(200: {"model": ItemIdsResult},},)-async def get_queue_item_ids(+def get_queue_item_ids(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),@@ -176,14 +198,21 @@ async def get_queue_item_ids(operation_id="get_queue_items_by_item_ids",responses={200: {"model": list[SessionQueueItem]}},)-async def get_queue_items_by_item_ids(+def get_queue_items_by_item_ids(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),item_ids: list[int] = Body(- embed=True, description="Object containing list of queue item ids to fetch queue items for"+ embed=True,+ max_length=MAX_QUEUE_ITEM_IDS_PER_REQUEST,+ description="Object containing list of queue item ids to fetch queue items for",),) -> list[SessionQueueItem]:- """Gets queue items for the specified queue item ids. Maintains order of item ids."""+ """Gets queue items for the specified queue item ids. Maintains order of item ids.++ Bound the legacy full-item endpoint as well as the summary endpoint: callers can otherwise+ force one graph deserialization and response copy per supplied id, defeating the queue-list+ optimization with an authenticated memory/CPU exhaustion request.+ """try:session_queue_service = ApiDependencies.invoker.services.session_queue@@ -206,12 +235,36 @@ async def get_queue_items_by_item_ids(raise HTTPException(status_code=500, detail="Failed to get queue items")+@session_queue_router.post(+ "/{queue_id}/item_summaries_by_ids",+ operation_id="get_queue_item_summaries_by_ids",+ responses={200: {"model": list[SessionQueueItemSummary]}},+)+def get_queue_item_summaries_by_ids(+ current_user: CurrentUserOrDefault,+ queue_id: str = Path(description="The queue id to perform this operation on"),+ item_ids: list[int] = Body(+ embed=True,+ max_length=MAX_QUEUE_ITEM_IDS_PER_REQUEST,+ description="Object containing list of queue item ids to fetch summaries for",+ ),+) -> list[SessionQueueItemSummary]:+ """Gets lightweight queue item summaries for specified IDs in requested order."""+ try:+ summaries = ApiDependencies.invoker.services.session_queue.get_queue_item_summaries_by_ids(+ queue_id=queue_id, item_ids=item_ids+ )+ return [sanitize_queue_item_for_user(item, current_user.user_id, current_user.is_admin) for item in summaries]+ except Exception:+ raise HTTPException(status_code=500, detail="Failed to get queue item summaries")++@session_queue_router.put("/{queue_id}/processor/resume",operation_id="resume",responses={200: {"model": SessionProcessorStatus}},)-async def resume(+def resume(current_user: AdminUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> SessionProcessorStatus:@@ -227,7 +280,7 @@ async def resume(operation_id="pause",responses={200: {"model": SessionProcessorStatus}},)-async def pause(+def pause(current_user: AdminUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> SessionProcessorStatus:@@ -243,7 +296,7 @@ async def pause(operation_id="cancel_all_except_current",responses={200: {"model": CancelAllExceptCurrentResult}},)-async def cancel_all_except_current(+def cancel_all_except_current(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> CancelAllExceptCurrentResult:@@ -263,7 +316,7 @@ async def cancel_all_except_current(operation_id="delete_all_except_current",responses={200: {"model": DeleteAllExceptCurrentResult}},)-async def delete_all_except_current(+def delete_all_except_current(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> DeleteAllExceptCurrentResult:@@ -283,7 +336,7 @@ async def delete_all_except_current(operation_id="cancel_by_batch_ids",responses={200: {"model": CancelByBatchIDsResult}},)-async def cancel_by_batch_ids(+def cancel_by_batch_ids(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),batch_ids: list[str] = Body(description="The list of batch_ids to cancel all queue items for", embed=True),@@ -304,7 +357,7 @@ async def cancel_by_batch_ids(operation_id="cancel_by_destination",responses={200: {"model": CancelByDestinationResult}},)-async def cancel_by_destination(+def cancel_by_destination(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),destination: str = Query(description="The destination to cancel all queue items for"),@@ -325,7 +378,7 @@ async def cancel_by_destination(operation_id="retry_items_by_id",responses={200: {"model": RetryItemsResult}},)-async def retry_items_by_id(+def retry_items_by_id(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),item_ids: list[int] = Body(description="The queue item ids to retry"),@@ -371,7 +424,7 @@ async def retry_items_by_id(200: {"model": ClearResult},},)-async def clear(+def clear(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> ClearResult:@@ -398,7 +451,7 @@ async def clear(200: {"model": PruneResult},},)-async def prune(+def prune(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),) -> PruneResult:@@ -418,7 +471,7 @@ async 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"),) -> Optional[SessionQueueItem]:@@ -439,7 +492,7 @@ async def get_current_queue_item(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"),) -> Optional[SessionQueueItem]:@@ -460,7 +513,7 @@ async def get_next_queue_item(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"),) -> SessionQueueAndProcessorStatus:@@ -485,7 +538,7 @@ async def get_queue_status(200: {"model": BatchStatus},},)-async def get_batch_status(+def get_batch_status(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),batch_id: str = Path(description="The batch to get the status of"),@@ -508,7 +561,7 @@ async def get_batch_status(},response_model_exclude_none=True,)-async def get_queue_item(+def get_queue_item(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),item_id: int = Path(description="The queue item to get"),@@ -530,7 +583,7 @@ async def get_queue_item("/{queue_id}/i/{item_id}",operation_id="delete_queue_item",)-async def delete_queue_item(+def delete_queue_item(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),item_id: int = Path(description="The queue item to delete"),@@ -566,7 +619,7 @@ async def delete_queue_item(200: {"model": SessionQueueItem},},)-async def cancel_queue_item(+def cancel_queue_item(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to perform this operation on"),item_id: int = Path(description="The queue item to cancel"),@@ -596,7 +649,7 @@ async def cancel_queue_item(operation_id="counts_by_destination",responses={200: {"model": SessionQueueCountsByDestination}},)-async def counts_by_destination(+def counts_by_destination(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to query"),destination: str = Query(description="The destination to query"),@@ -616,7 +669,7 @@ async def counts_by_destination(operation_id="delete_by_destination",responses={200: {"model": DeleteByDestinationResult}},)-async def delete_by_destination(+def delete_by_destination(current_user: CurrentUserOrDefault,queue_id: str = Path(description="The queue id to query"),destination: str = Path(description="The destination to query"),diff --git a/invokeai/app/api/routers/style_presets.py b/invokeai/app/api/routers/style_presets.pyindex 91acf8e7a6..3ae52e5eeb 100644--- a/invokeai/app/api/routers/style_presets.py+++ b/invokeai/app/api/routers/style_presets.py@@ -1,3 +1,4 @@+import asyncioimport csvimport ioimport json@@ -78,7 +79,7 @@ def _load_record_or_404(style_preset_id: str) -> StylePresetRecordDTO:200: {"model": StylePresetRecordWithImage},},)-async def get_style_preset(+def get_style_preset(current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The style preset to get"),) -> StylePresetRecordWithImage:@@ -118,7 +119,7 @@ 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:@@ -127,28 +128,34 @@ async def update_style_preset(contents = await image.read()try:- pil_image = Image.open(io.BytesIO(contents))+ pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))except Exception:ApiDependencies.invoker.services.logger.error(traceback.format_exc())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: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:passpreset_data = PresetData(positive_prompt=positive_prompt, negative_prompt=negative_prompt)changes = StylePresetChanges(name=name, preset_data=preset_data, type=type, is_public=is_public)- style_preset_image = ApiDependencies.invoker.services.style_preset_image_files.get_url(style_preset_id)- style_preset = ApiDependencies.invoker.services.style_preset_records.update(- style_preset_id=style_preset_id, changes=changes+ style_preset_image = await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_image_files.get_url, style_preset_id+ )+ style_preset = await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_records.update,+ style_preset_id=style_preset_id,+ changes=changes,)return StylePresetRecordWithImage(image=style_preset_image, **style_preset.model_dump())@@ -157,7 +164,7 @@ async def update_style_preset("/i/{style_preset_id}",operation_id="delete_style_preset",)-async def delete_style_preset(+def delete_style_preset(current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The style preset to delete"),) -> None:@@ -204,30 +211,38 @@ async def create_style_preset(if type == PresetType.Default and not current_user.is_admin:raise HTTPException(status_code=403, detail="Only admins can create default presets")- preset_data = PresetData(positive_prompt=positive_prompt, negative_prompt=negative_prompt)- style_preset = StylePresetWithoutId(name=name, preset_data=preset_data, type=type, is_public=is_public)- new_style_preset = ApiDependencies.invoker.services.style_preset_records.create(- style_preset=style_preset, user_id=current_user.user_id- )-+ pil_image = Noneif 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")contents = await image.read()try:- pil_image = Image.open(io.BytesIO(contents))+ pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))except Exception:ApiDependencies.invoker.services.logger.error(traceback.format_exc())raise HTTPException(status_code=415, detail="Failed to read image")+ preset_data = PresetData(positive_prompt=positive_prompt, negative_prompt=negative_prompt)+ style_preset = StylePresetWithoutId(name=name, preset_data=preset_data, type=type, is_public=is_public)+ new_style_preset = await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_records.create,+ style_preset=style_preset,+ user_id=current_user.user_id,+ )++ if pil_image is not None:try:- ApiDependencies.invoker.services.style_preset_image_files.save(new_style_preset.id, pil_image)+ await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_image_files.save, new_style_preset.id, pil_image+ )except ValueError as e:raise HTTPException(status_code=409, detail=str(e))- preset_image = ApiDependencies.invoker.services.style_preset_image_files.get_url(new_style_preset.id)+ preset_image = await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_image_files.get_url, new_style_preset.id+ )return StylePresetRecordWithImage(image=preset_image, **new_style_preset.model_dump())@@ -238,7 +253,7 @@ async def create_style_preset(200: {"model": list[StylePresetRecordWithImage]},},)-async def list_style_presets(current_user: CurrentUserOrDefault) -> list[StylePresetRecordWithImage]:+def list_style_presets(current_user: CurrentUserOrDefault) -> list[StylePresetRecordWithImage]:"""Gets the style presets visible to the current user."""style_presets_with_image: list[StylePresetRecordWithImage] = []style_presets = ApiDependencies.invoker.services.style_preset_records.get_many(@@ -265,7 +280,7 @@ async def list_style_presets(current_user: CurrentUserOrDefault) -> list[StylePr},status_code=200,)-async def get_style_preset_image(+def get_style_preset_image(current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The id of the style preset image to get"),) -> FileResponse:@@ -294,7 +309,7 @@ async def get_style_preset_image(responses={200: {"content": {"text/csv": {}}, "description": "A CSV file with the requested data."}},status_code=200,)-async def export_style_presets(current_user: AdminUserOrDefault):+def export_style_presets(current_user: AdminUserOrDefault):# Admin-only export covers every user preset.output = io.StringIO()writer = csv.writer(output)@@ -330,7 +345,11 @@ async def import_style_presets():try:style_presets = await parse_presets_from_file(file)- ApiDependencies.invoker.services.style_preset_records.create_many(style_presets, user_id=current_user.user_id)+ await asyncio.to_thread(+ ApiDependencies.invoker.services.style_preset_records.create_many,+ style_presets,+ user_id=current_user.user_id,+ )except InvalidPresetImportDataError as e:ApiDependencies.invoker.services.logger.error(traceback.format_exc())raise HTTPException(status_code=400, detail=str(e))diff --git a/invokeai/app/api/routers/system_prompts.py b/invokeai/app/api/routers/system_prompts.pyindex f0fa9ac7b5..6bfbba7ab5 100644--- a/invokeai/app/api/routers/system_prompts.py+++ b/invokeai/app/api/routers/system_prompts.py@@ -19,7 +19,7 @@ system_prompts_router = APIRouter(prefix="/v1/system_prompts", tags=["system_prooperation_id="list_system_prompts",responses={200: {"model": list[SystemPromptRecordDTO]}},)-async def list_system_prompts(current_user: CurrentUserOrDefault) -> list[SystemPromptRecordDTO]:+def list_system_prompts(current_user: CurrentUserOrDefault) -> list[SystemPromptRecordDTO]:"""Lists system prompts visible to the current user (own + public)."""config = ApiDependencies.invoker.services.configuration# Admins (and single-user installs) see everything; multiuser non-admins are scoped to own + public.@@ -34,7 +34,7 @@ async def list_system_prompts(current_user: CurrentUserOrDefault) -> list[Systemoperation_id="get_system_prompt",responses={200: {"model": SystemPromptRecordDTO}},)-async def get_system_prompt(+def get_system_prompt(current_user: CurrentUserOrDefault,system_prompt_id: str = Path(description="The id of the system prompt to get"),) -> SystemPromptRecordDTO:@@ -57,7 +57,7 @@ async def get_system_prompt(operation_id="create_system_prompt",responses={200: {"model": SystemPromptRecordDTO}},)-async def create_system_prompt(+def create_system_prompt(current_user: CurrentUserOrDefault,system_prompt: SystemPromptWithoutId = Body(description="The system prompt to create"),) -> SystemPromptRecordDTO:@@ -75,7 +75,7 @@ async def create_system_prompt(operation_id="update_system_prompt",responses={200: {"model": SystemPromptRecordDTO}},)-async def update_system_prompt(+def update_system_prompt(current_user: CurrentUserOrDefault,system_prompt_id: str = Path(description="The id of the system prompt to update"),changes: SystemPromptChanges = Body(description="The changes to apply"),@@ -100,7 +100,7 @@ async def update_system_prompt("/i/{system_prompt_id}",operation_id="delete_system_prompt",)-async def delete_system_prompt(+def delete_system_prompt(current_user: CurrentUserOrDefault,system_prompt_id: str = Path(description="The id of the system prompt to delete"),) -> None:diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex 0ede5441c4..9f5ff7201f 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -46,7 +46,7 @@ class DynamicPromptsResponse(BaseModel):200: {"model": DynamicPromptsResponse},},)-async def parse_dynamicprompts(+def parse_dynamicprompts(current_user: CurrentUserOrDefault,prompt: str = Body(description="The prompt to parse with dynamicprompts"),max_prompts: int = Body(ge=1, le=10000, default=1000, description="The max number of prompts to generate"),@@ -295,11 +295,11 @@ def _run_image_to_prompt()async def image_to_prompt(current_user: CurrentUserOrDefault, body: ImageToPromptRequest) -> ImageToPromptResponse:"""Generate a descriptive prompt from an image using a vision-language model."""- assert_image_move_maintenance_inactive()+ await asyncio.to_thread(assert_image_move_maintenance_inactive)# Reuse the image-read access check so non-owners can't probe stored images# via this endpoint (mirrors the policy in routers/images.py).- assert_image_read_access(body.image_name, current_user)+ await asyncio.to_thread(assert_image_read_access, body.image_name, current_user)events = ApiDependencies.invoker.services.eventstry:diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.pyindex 29e8b99cdf..0604befb25 100644--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@ -258,7 +258,7 @@ async def upload_video(from invokeai.app.services.board_records.board_records_common import BoardVisibilitytry:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ 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 (@@ -470,7 +470,7 @@ def update_video(@videos_router.get("/i/{video_name}", operation_id="get_video_dto", response_model=VideoDTO)-async def get_video_dto(+def get_video_dto(current_user: CurrentUserOrDefault,video_name: str = PathParam(description="The name of video to get"),) -> VideoDTO:@@ -484,7 +484,7 @@ async def get_video_dto(@videos_router.get("/i/{video_name}/metadata", operation_id="get_video_metadata", response_model=Optional[MetadataField])-async def get_video_metadata(+def get_video_metadata(current_user: CurrentUserOrDefault,video_name: str = PathParam(description="The name of video to get"),) -> Optional[MetadataField]:@@ -498,7 +498,7 @@ async def get_video_metadata(@videos_router.get("/i/{video_name}/workflow", operation_id="get_video_workflow", response_model=WorkflowAndGraphResponse)-async def get_video_workflow(+def get_video_workflow(current_user: CurrentUserOrDefault,video_name: str = PathParam(description="The name of video whose workflow to get"),) -> WorkflowAndGraphResponse:@@ -572,7 +572,7 @@ def _parse_range_header(range_header: str, file_size: int) -> Optional[tuple[int404: {"description": "Video not found"},},)-async def get_video_full(+def get_video_full(request: Request,current_user: CurrentMediaUserOrDefault,video_name: str = PathParam(description="The name of video file to get"),@@ -675,7 +675,7 @@ async def get_video_full(404: {"description": "Video not found"},},)-async def get_video_thumbnail(+def get_video_thumbnail(current_user: CurrentMediaUserOrDefault,video_name: str = PathParam(description="The name of thumbnail file to get"),) -> Response:@@ -699,7 +699,7 @@ async def get_video_thumbnail(@videos_router.get("/i/{video_name}/urls", operation_id="get_video_urls", response_model=VideoUrlsDTO)-async def get_video_urls(+def get_video_urls(current_user: CurrentUserOrDefault,video_name: str = PathParam(description="The name of the video whose URL to get"),) -> VideoUrlsDTO:@@ -713,7 +713,7 @@ async def get_video_urls(@videos_router.get("/", operation_id="list_video_dtos", response_model=OffsetPaginatedResults[VideoDTO])-async def list_video_dtos(+def list_video_dtos(current_user: CurrentUserOrDefault,video_origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of videos to list."),categories: Optional[list[ImageCategory]] = Query(default=None, description="The categories of video to include."),@@ -750,8 +750,8 @@ async def list_video_dtos()-@videos_router.get("/names", operation_id="get_video_names")-async def get_video_names(+@videos_router.get("/names", operation_id="get_video_names", deprecated=True)+def get_video_names(current_user: CurrentUserOrDefault,video_origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of videos to list."),categories: Optional[list[ImageCategory]] = Query(default=None, description="The categories of video to include."),@@ -764,7 +764,11 @@ async def get_video_names(starred_first: bool = Query(default=True, description="Whether to sort by starred videos first"),search_term: Optional[str] = Query(default=None, description="The term to search for"),) -> VideoNamesResult:- """Gets ordered list of video names with metadata for optimistic updates."""+ """Gets ordered list of video names with metadata for optimistic updates.++ Deprecated: use `GET /v1/gallery/item_names`, which returns images and videos interleaved+ in one ordered list. This video-only endpoint predates the polymorphic gallery.+ """# Validate that the caller can read from this board. "none" is handled by the SQL layer.if board_id is not None and board_id != "none":_assert_board_read_access(board_id, current_user)@@ -854,7 +858,7 @@ class VideoBoardArg(BaseModel):operation_id="add_video_to_board",response_model=AddVideosToBoardResult,)-async def add_video_to_board(+def add_video_to_board(current_user: CurrentUserOrDefault,arg: VideoBoardArg = Body(),) -> AddVideosToBoardResult:@@ -882,7 +886,7 @@ async def add_video_to_board(operation_id="remove_video_from_board",response_model=RemoveVideosFromBoardResult,)-async def remove_video_from_board(+def remove_video_from_board(current_user: CurrentUserOrDefault,video_name: str = Body(description="The name of the video to remove from its board", embed=True),) -> RemoveVideosFromBoardResult:diff --git a/invokeai/app/api/routers/virtual_boards.py b/invokeai/app/api/routers/virtual_boards.pyindex 78902dd5de..9837cbd899 100644--- a/invokeai/app/api/routers/virtual_boards.py+++ b/invokeai/app/api/routers/virtual_boards.py@@ -16,7 +16,7 @@ virtual_boards_router = APIRouter(prefix="/v1/virtual_boards", tags=["virtual_booperation_id="list_virtual_boards_by_date",response_model=list[VirtualSubBoardDTO],)-async def list_virtual_boards_by_date(+def list_virtual_boards_by_date(current_user: CurrentUserOrDefault,) -> list[VirtualSubBoardDTO]:"""Gets a list of virtual sub-boards grouped by date. Covers both images and videos."""@@ -33,8 +33,9 @@ async def list_virtual_boards_by_date("/by_date/{date}/image_names",operation_id="list_virtual_board_image_names_by_date",response_model=ImageNamesResult,+ deprecated=True,)-async def list_virtual_board_image_names_by_date(+def list_virtual_board_image_names_by_date(current_user: CurrentUserOrDefault,date: str = Path(description="The ISO date string, e.g. '2026-03-18'"),starred_first: bool = Query(default=True, description="Whether to sort starred images first"),@@ -42,8 +43,11 @@ async def list_virtual_board_image_names_by_date(categories: list[ImageCategory] | None = Query(default=None, description="The categories of images to include"),search_term: str | None = Query(default=None, description="Search term to filter images"),) -> ImageNamesResult:- """Gets ordered image names for a specific date. Image-only; kept for API compatibility —- the UI uses the polymorphic `/by_date/{date}/item_names` endpoint."""+ """Gets ordered image names for a specific date. Image-only.++ Deprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which covers images and+ videos in one ordered list.+ """try:return ApiDependencies.invoker.services.image_records.get_image_names_by_date(date=date,@@ -62,8 +66,9 @@ async def list_virtual_board_image_names_by_date("/by_date/{date}/item_names",operation_id="list_virtual_board_item_names_by_date",response_model=GalleryItemNamesResult,+ deprecated=True,)-async def list_virtual_board_item_names_by_date(+def list_virtual_board_item_names_by_date(current_user: CurrentUserOrDefault,date: str = Path(description="The ISO date string, e.g. '2026-03-18'"),starred_first: bool = Query(default=True, description="Whether to sort starred items first"),@@ -71,7 +76,11 @@ async def list_virtual_board_item_names_by_date(categories: list[ImageCategory] | None = Query(default=None, description="The categories of items to include"),search_term: str | None = Query(default=None, description="Search term to filter items"),) -> GalleryItemNamesResult:- """Gets ordered polymorphic (image + video) item refs for a specific date."""+ """Gets ordered polymorphic (image + video) item refs for a specific date.++ Deprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which returns the same+ order as a flat name list instead of one model per item.+ """try:return ApiDependencies.invoker.services.gallery.list_item_names(starred_first=starred_first,diff --git a/invokeai/app/api/routers/workflows.py b/invokeai/app/api/routers/workflows.pyindex 768a8f4e8d..110fa01b25 100644--- a/invokeai/app/api/routers/workflows.py+++ b/invokeai/app/api/routers/workflows.py@@ -1,3 +1,4 @@+import asyncioimport ioimport mathimport traceback@@ -35,7 +36,7 @@ workflows_router = APIRouter(prefix="/v1/workflows", tags=["workflows"])200: {"model": WorkflowRecordWithThumbnailDTO},},)-async def get_workflow(+def get_workflow(current_user: CurrentUserOrDefault,workflow_id: str = Path(description="The workflow to get"),) -> WorkflowRecordWithThumbnailDTO:@@ -74,7 +75,7 @@ async def get_workflow(200: {"model": WorkflowRecordDTO},},)-async def update_workflow(+def update_workflow(current_user: CurrentUserOrDefault,workflow: Workflow = Body(description="The updated workflow", embed=True),) -> WorkflowRecordDTO:@@ -103,7 +104,7 @@ async def update_workflow("/i/{workflow_id}",operation_id="delete_workflow",)-async def delete_workflow(+def delete_workflow(current_user: CurrentUserOrDefault,workflow_id: str = Path(description="The workflow to delete"),) -> None:@@ -138,7 +139,7 @@ async def delete_workflow(200: {"model": WorkflowRecordDTO},},)-async def create_workflow(+def create_workflow(current_user: CurrentUserOrDefault,workflow: WorkflowWithoutID = Body(description="The workflow to create", embed=True),) -> WorkflowRecordDTO:@@ -165,7 +166,7 @@ async def create_workflow(200: {"model": PaginatedResults[WorkflowRecordListItemWithThumbnailDTO]},},)-async def list_workflows(+def list_workflows(current_user: CurrentUserOrDefault,page: int = Query(default=0, description="The page to get"),per_page: Optional[int] = Query(default=None, description="The number of workflows per page"),@@ -274,7 +275,7 @@ async def set_workflow_thumbnail():"""Sets a workflow's thumbnail image"""try:- existing = ApiDependencies.invoker.services.workflow_records.get(workflow_id)+ existing = await asyncio.to_thread(ApiDependencies.invoker.services.workflow_records.get, workflow_id)except WorkflowNotFoundError:raise HTTPException(status_code=404, detail="Workflow not found")@@ -287,14 +288,14 @@ async def set_workflow_thumbnail(contents = await image.read()try:- pil_image = Image.open(io.BytesIO(contents))+ pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))except Exception:ApiDependencies.invoker.services.logger.error(traceback.format_exc())raise HTTPException(status_code=415, detail="Failed to read image")try:- ApiDependencies.invoker.services.workflow_thumbnails.save(workflow_id, pil_image)+ await asyncio.to_thread(ApiDependencies.invoker.services.workflow_thumbnails.save, workflow_id, pil_image)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -306,7 +307,7 @@ async def set_workflow_thumbnail(200: {"model": WorkflowRecordDTO},},)-async def delete_workflow_thumbnail(+def delete_workflow_thumbnail(current_user: CurrentUserOrDefault,workflow_id: str = Path(description="The workflow to update"),):@@ -338,7 +339,7 @@ async def delete_workflow_thumbnail(},status_code=200,)-async def get_workflow_thumbnail(+def get_workflow_thumbnail(workflow_id: str = Path(description="The id of the workflow thumbnail to get"),) -> FileResponse:"""Gets a workflow's thumbnail image.@@ -369,7 +370,7 @@ async def get_workflow_thumbnail(200: {"model": WorkflowRecordDTO},},)-async def update_workflow_is_public(+def update_workflow_is_public(current_user: CurrentUserOrDefault,workflow_id: str = Path(description="The workflow to update"),is_public: bool = Body(description="Whether the workflow should be shared publicly", embed=True),@@ -398,7 +399,7 @@ async def update_workflow_is_public(@workflows_router.get("/tags", operation_id="get_all_tags")-async def get_all_tags(+def get_all_tags(current_user: CurrentUserOrDefault,categories: Optional[list[WorkflowCategory]] = Query(default=None, description="The categories to include"),is_public: Optional[bool] = Query(default=None, description="Filter by public/shared status"),@@ -417,7 +418,7 @@ async def get_all_tags(@workflows_router.get("/counts_by_tag", operation_id="get_counts_by_tag")-async def get_counts_by_tag(+def get_counts_by_tag(current_user: CurrentUserOrDefault,tags: list[str] = Query(description="The tags to get counts for"),categories: Optional[list[WorkflowCategory]] = Query(default=None, description="The categories to include"),@@ -438,7 +439,7 @@ async def get_counts_by_tag(@workflows_router.get("/counts_by_category", operation_id="counts_by_category")-async def counts_by_category(+def counts_by_category(current_user: CurrentUserOrDefault,categories: list[WorkflowCategory] = Query(description="The categories to include"),has_been_opened: Optional[bool] = Query(default=None, description="Whether to include/exclude recent workflows"),@@ -461,7 +462,7 @@ async def counts_by_category("/i/{workflow_id}/opened_at",operation_id="update_opened_at",)-async def update_opened_at(+def update_opened_at(current_user: CurrentUserOrDefault,workflow_id: str = Path(description="The workflow to update"),) -> None:diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.pyindex b89746dcac..b8b6a5fe44 100644--- a/invokeai/app/api_app.py+++ b/invokeai/app/api_app.py@@ -7,7 +7,6 @@ from pathlib import Pathfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddleware-from fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.openapi.docs import get_redoc_html, get_swagger_ui_htmlfrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponsefrom fastapi.security.utils import get_authorization_scheme_param@@ -16,6 +15,7 @@ from fastapi_events.middleware import EventHandlerASGIMiddlewarefrom starlette.concurrency import run_in_threadpoolfrom starlette.datastructures import Headersfrom starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint+from starlette.middleware.gzip import GZipMiddleware, GZipResponder, IdentityResponderfrom starlette.types import ASGIApp, Message, Receive, Scope, Sendimport invokeai.frontend.web as web_dir@@ -158,6 +158,77 @@ class SlidingWindowTokenMiddleware(BaseHTTPMiddleware):return response+# Response types worth compressing. Everything else is passed through untouched.+#+# This is an allowlist rather than a blocklist of media types on purpose: a type missing from+# this list only loses compression it would barely have benefited from, whereas a binary type+# missing from a blocklist costs real CPU on the event loop. The app serves a small, known set+# of compressible things — the UI bundle, the API's JSON, SVG icons.+COMPRESSIBLE_CONTENT_TYPES = (+ "text/",+ "application/json",+ "application/javascript",+ "application/xml",+ "application/xhtml+xml",+ "application/manifest+json",+ "image/svg+xml",+)++# `text/` would otherwise match this, and compressing an event stream defeats its purpose by+# withholding events until the compressor flushes. Starlette excludes it by default too.+UNCOMPRESSIBLE_CONTENT_TYPES = ("text/event-stream",)+++def _is_compressible(content_type: str) -> bool:+ if content_type.startswith(UNCOMPRESSIBLE_CONTENT_TYPES):+ return False+ return content_type.startswith(COMPRESSIBLE_CONTENT_TYPES)+++class _ContentTypeAwareGZipResponder(GZipResponder):+ """Skips compression for response types that are already compressed.++ `content_type_is_excluded` is computed when the response starts and only read once the+ body arrives, so widening it right after the base class has set it is enough — no need to+ reimplement Starlette's streaming/pathsend handling.+ """++ async def send_with_compression(self, message: Message) -> None:+ await super().send_with_compression(message)+ if message["type"] == "http.response.start" and not self.content_type_is_excluded:+ self.content_type_is_excluded = not _is_compressible(+ Headers(raw=message["headers"]).get("content-type", "")+ )+++class ContentTypeAwareGZipMiddleware(GZipMiddleware):+ """GZip, but only for content types that actually compress.++ Starlette's GZipMiddleware compresses every response type except `text/event-stream`. The+ gallery serves PNG, WebP and MP4 bytes, which are already compressed: a 3 MB PNG costs+ ~52ms of event-loop time to gzip and comes back *larger* than it went in. With auto-switch+ enabled the UI fetches the full image after every generated image, so that cost lands+ repeatedly during a batch — exactly when the server can least afford to stall.++ Lowering `compresslevel` does not help here: on incompressible input, level 1 costs+ essentially the same as level 9 because deflate still has to scan the data.+ """++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return++ if "gzip" in Headers(scope=scope).get("Accept-Encoding", ""):+ responder: ASGIApp = _ContentTypeAwareGZipResponder(+ self.app, self.minimum_size, compresslevel=self.compresslevel+ )+ else:+ responder = IdentityResponder(self.app, self.minimum_size)++ await responder(scope, receive, send)++class RedirectRootWithQueryStringMiddleware(BaseHTTPMiddleware):"""When a request is made to the root path with a query string, redirect to the root path without the query string.@@ -399,7 +470,7 @@ app.add_middleware(expose_headers=["X-Refreshed-Token"],)-app.add_middleware(GZipMiddleware, minimum_size=1000)+app.add_middleware(ContentTypeAwareGZipMiddleware, minimum_size=1000)# Include all routersdiff --git a/invokeai/app/services/gallery/gallery_base.py b/invokeai/app/services/gallery/gallery_base.pyindex bd6591884d..a2679aba7a 100644--- a/invokeai/app/services/gallery/gallery_base.py+++ b/invokeai/app/services/gallery/gallery_base.py@@ -1,7 +1,12 @@from abc import ABC, abstractmethodfrom typing import Optional-from invokeai.app.services.gallery.gallery_common import BoardMediaSummary, GalleryItem, GalleryItemNamesResult+from invokeai.app.services.gallery.gallery_common import (+ BoardMediaSummary,+ GalleryItem,+ GalleryItemNames,+ GalleryItemNamesResult,+)from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.shared.pagination import OffsetPaginatedResultsfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection@@ -45,6 +50,27 @@ 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,+ ) -> 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 bydate-based virtual boards."""diff --git a/invokeai/app/services/gallery/gallery_common.py b/invokeai/app/services/gallery/gallery_common.pyindex 85753c958c..00a3befdb8 100644--- a/invokeai/app/services/gallery/gallery_common.py+++ b/invokeai/app/services/gallery/gallery_common.py@@ -49,13 +49,31 @@ class GalleryItem(BaseModelExcludeNull):class GalleryItemNamesResult(BaseModel):- """Ordered list of gallery item references plus counts for optimistic UI."""+ """Ordered list of gallery item references plus counts for optimistic UI.++ Deprecated in favour of :class:`GalleryItemNames`. Wrapping every name in an object to+ carry a `kind` discriminator costs ~800ms of model construction on a 200k-item library,+ for a field callers derive from the filename extension anyway.+ """items: list[GalleryItemRef] = Field(description="Ordered list of (kind, name) references.")starred_count: int = Field(description="Number of starred items (when starred_first=True).")total_count: int = Field(description="Total number of items matching the query.")+class GalleryItemNames(BaseModel):+ """Ordered flat list of gallery item names plus counts for optimistic UI.++ Names are polymorphic — images and videos are interleaved by `created_at`. The kind of a+ given name is its file extension (`.mp4` is a video), which is how every consumer already+ discriminates. Mirrors the shape of the image-only `ImageNamesResult`.+ """++ item_names: list[str] = Field(description="Ordered list of image and video names.")+ starred_count: int = Field(description="Number of starred items (when starred_first=True).")+ total_count: int = Field(description="Total number of items matching the query.")++@dataclass(frozen=True)class BoardMediaSummary:cover_image_name: Optional[str] = Nonediff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.pyindex 0a23717eb8..0fdeaca48c 100644--- a/invokeai/app/services/gallery/gallery_default.py+++ b/invokeai/app/services/gallery/gallery_default.py@@ -6,6 +6,7 @@ from invokeai.app.services.gallery.gallery_common import (BoardMediaSummary,GalleryItem,GalleryItemKind,+ GalleryItemNames,GalleryItemNamesResult,GalleryItemRef,)@@ -100,19 +101,24 @@ class SqliteGalleryService(GalleryServiceABC):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,- ) -> 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],+ ) -> 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,@@ -158,9 +164,66 @@ class SqliteGalleryService(GalleryServiceABC):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,+ ) -> 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,+ )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,+ ) -> 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,+ )+ # 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 --git a/invokeai/app/services/orphaned_models/__init__.py b/invokeai/app/services/orphaned_models/__init__.pyindex db9eaae7bb..edbab30e3f 100644--- a/invokeai/app/services/orphaned_models/__init__.py+++ b/invokeai/app/services/orphaned_models/__init__.py@@ -1,5 +1,9 @@"""Service for finding and removing orphaned model files."""-from invokeai.app.services.orphaned_models.orphaned_models_service import OrphanedModelInfo, OrphanedModelsService+from invokeai.app.services.orphaned_models.orphaned_models_service import (+ CONVERSION_SCRATCH_DIRNAME,+ OrphanedModelInfo,+ OrphanedModelsService,+)-__all__ = ["OrphanedModelsService", "OrphanedModelInfo"]+__all__ = ["OrphanedModelsService", "OrphanedModelInfo", "CONVERSION_SCRATCH_DIRNAME"]diff --git a/invokeai/app/services/orphaned_models/orphaned_models_service.py b/invokeai/app/services/orphaned_models/orphaned_models_service.pyindex 8d2894c867..fd1b1053b9 100644--- a/invokeai/app/services/orphaned_models/orphaned_models_service.py+++ b/invokeai/app/services/orphaned_models/orphaned_models_service.py@@ -14,6 +14,12 @@ from pydantic import BaseModel, Fieldfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+# Scratch area for operations that must build a model on the models volume before registering it -+# model conversion writes its diffusers copy here. It lives under the models root so the finished+# result can be moved into place without crossing a filesystem boundary, and it is hidden from the+# orphan scan by name (see SKIP_DIRS below).+CONVERSION_SCRATCH_DIRNAME = ".convert_tmp"+class OrphanedModelInfo(BaseModel):"""Information about an orphaned model directory."""@@ -38,10 +44,14 @@ class OrphanedModelsService:".gguf",}- # Directories to skip during scan+ # Directories to skip during scan. An "orphan" is a model file with no database record, which+ # is also an exact description of a model an operation is midway through writing - so any+ # scratch area under the models root has to be listed here, or a scan taken during that+ # operation reports its working directory and the delete route rmtrees it mid-write.SKIP_DIRS = {".download_cache",".convert_cache",+ CONVERSION_SCRATCH_DIRNAME,"__pycache__",".git",}@@ -131,23 +141,32 @@ class OrphanedModelsService:Returns:Dictionary mapping paths to status messages ("deleted" or error message)"""- models_path = self._config.models_path+ models_path = self._config.models_path.resolve()+ conversion_scratch_path = (models_path / CONVERSION_SCRATCH_DIRNAME).resolve()results = {}for rel_path in orphaned_paths:try:- full_path = models_path / rel_path- if not full_path.exists():- results[rel_path] = "error: path does not exist"- continue-# Safety check: ensure path is under models directory+ full_path = (models_path / rel_path).resolve()try:full_path.relative_to(models_path)except ValueError:results[rel_path] = "error: path is not under models directory"continue+ try:+ full_path.relative_to(conversion_scratch_path)+ except ValueError:+ pass+ else:+ results[rel_path] = "error: path is reserved for active conversion"+ continue++ if not full_path.exists():+ results[rel_path] = "error: path does not exist"+ continue+# Delete the directoryshutil.rmtree(full_path)results[rel_path] = "deleted"diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.pyindex 52b6d7bd75..1872ab7759 100644--- a/invokeai/app/services/session_queue/session_queue_base.py+++ b/invokeai/app/services/session_queue/session_queue_base.py@@ -21,6 +21,7 @@ from invokeai.app.services.session_queue.session_queue_common import (RetryItemsResult,SessionQueueCountsByDestination,SessionQueueItem,+ SessionQueueItemSummary,SessionQueueStatus,)from invokeai.app.services.shared.graph import GraphExecutionState@@ -223,6 +224,11 @@ class SessionQueueBase(ABC):"""Gets all queue item ids that match the given parameters. If user_id is provided, only returns items for that user."""pass+ @abstractmethod+ def get_queue_item_summaries_by_ids(self, queue_id: str, item_ids: list[int]) -> list[SessionQueueItemSummary]:+ """Gets lightweight queue item summaries in the requested item ID order."""+ pass+@abstractmethoddef get_queue_item(self, item_id: int) -> SessionQueueItem:"""Gets a session queue item by ID for a given queue"""diff --git a/invokeai/app/services/session_queue/session_queue_common.py b/invokeai/app/services/session_queue/session_queue_common.pyindex 1509ea611b..9f0e00c920 100644--- a/invokeai/app/services/session_queue/session_queue_common.py+++ b/invokeai/app/services/session_queue/session_queue_common.py@@ -313,6 +313,35 @@ class SessionQueueItem(BaseModel):)+class SessionQueueItemSummary(BaseModel):+ """Queue item fields needed to render the queue list."""++ item_id: int = Field(description="The identifier of the session queue item")+ created_at: Union[datetime.datetime, str] = Field(description="When this queue item was created")+ status: QUEUE_ITEM_STATUS = Field(description="The status of this queue item")+ device: Optional[str] = Field(+ default=None,+ description="The device that processed this queue item, e.g. 'cuda:1'",+ )+ started_at: Optional[Union[datetime.datetime, str]] = Field(description="When this queue item was started")+ completed_at: Optional[Union[datetime.datetime, str]] = Field(description="When this queue item was completed")+ origin: str | None = Field(description="The origin of this queue item")+ destination: str | None = Field(description="The destination of this queue item")+ batch_id: str = Field(description="The ID of the batch associated with this queue item")+ user_id: str = Field(description="The ID of the user who created this queue item")+ user_display_name: Optional[str] = Field(description="The display name of the user who created this queue item")+ user_email: Optional[str] = Field(description="The email of the user who created this queue item")+ field_values: Optional[list[NodeFieldValue]] = Field(description="The batch field values used for this queue item")+ # Carried because the list rows decide from it whether to offer a retry: a child item of a+ # workflow call cannot be retried on its own.+ parent_item_id: Optional[int] = Field(description="The ID of the parent queue item, if this is a child item")++ @classmethod+ def queue_item_summary_from_dict(cls, queue_item_dict: dict) -> "SessionQueueItemSummary":+ queue_item_dict["field_values"] = get_field_values(queue_item_dict)+ return cls(**queue_item_dict)++# endregion Queue Items# region Query Resultsdiff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.pyindex 6b63141a5a..b301250a53 100644--- a/invokeai/app/services/session_queue/session_queue_sqlite.py+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py@@ -31,6 +31,7 @@ from invokeai.app.services.session_queue.session_queue_common import (SessionQueueCountsByDestination,SessionQueueItem,SessionQueueItemNotFoundError,+ SessionQueueItemSummary,SessionQueueStatus,TooManySessionsError,ValueToInsertTuple,@@ -42,6 +43,11 @@ from invokeai.app.services.shared.pagination import CursorPaginatedResultsfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+# Maximum number of ids bound into a single `IN (...)` clause. SQLite's compile-time bind limit is+# 999 on builds older than 3.32 and 32766 on newer ones; staying under the lower figure (leaving+# room for the other bind params in the statement) keeps the queries portable across both.+SQLITE_MAX_BIND_PARAMS_PER_CHUNK = 900+# Round-robin dequeue (multiuser fairness): pick the next pending item from the user who was# least-recently served.#@@ -263,6 +269,13 @@ class SqliteSessionQueue(SessionQueueBase):async def enqueue_batch(self, queue_id: str, batch: Batch, prepend: bool, user_id: str = "system") -> EnqueueBatchResult:+ # The route awaits this method, but every operation below is synchronous SQLite/CPU+ # work. Keep the complete transaction in one worker operation; otherwise the queue-size+ # check before the first await and the insert/event work after later awaits execute on the+ # event loop.+ return await asyncio.to_thread(self._enqueue_batch, queue_id, batch, prepend, user_id)++ def _enqueue_batch(self, queue_id: str, batch: Batch, prepend: bool, user_id: str) -> EnqueueBatchResult:current_queue_size = self._get_current_queue_size(queue_id)max_queue_size = self.__invoker.services.configuration.max_queue_sizemax_new_queue_items = max_queue_size - current_queue_size@@ -271,12 +284,8 @@ class SqliteSessionQueue(SessionQueueBase):if prepend:priority = self._get_highest_priority(queue_id) + 1- requested_count = await asyncio.to_thread(- calc_session_count,- batch=batch,- )- values_to_insert = await asyncio.to_thread(- prepare_values_to_insert,+ requested_count = calc_session_count(batch=batch)+ values_to_insert = prepare_values_to_insert(queue_id=queue_id,batch=batch,priority=priority,@@ -1397,6 +1406,48 @@ class SqliteSessionQueue(SessionQueueBase):return ItemIdsResult(item_ids=item_ids, total_count=len(item_ids))+ def get_queue_item_summaries_by_ids(self, queue_id: str, item_ids: list[int]) -> list[SessionQueueItemSummary]:+ if not item_ids:+ return []++ rows: list[sqlite3.Row] = []+ with self._db.transaction() as cursor:+ # Each id becomes one bind parameter, so a single IN (...) would blow past SQLite's+ # per-statement variable limit for large id lists. Query in chunks instead - callers+ # are bounded at the API layer, but this keeps any caller from hitting that ceiling.+ for chunk_start in range(0, len(item_ids), SQLITE_MAX_BIND_PARAMS_PER_CHUNK):+ chunk = item_ids[chunk_start : chunk_start + SQLITE_MAX_BIND_PARAMS_PER_CHUNK]+ placeholders = ", ".join("?" for _ in chunk)+ cursor.execute(+ f"""--sql+ SELECT+ sq.item_id,+ sq.created_at,+ sq.status,+ sq.device,+ sq.started_at,+ sq.completed_at,+ sq.origin,+ sq.destination,+ sq.batch_id,+ sq.user_id,+ u.display_name AS user_display_name,+ u.email AS user_email,+ sq.field_values,+ sq.parent_item_id+ FROM session_queue sq+ LEFT JOIN users u ON sq.user_id = u.user_id+ WHERE sq.queue_id = ? AND sq.item_id IN ({placeholders})+ """,+ (queue_id, *chunk),+ )+ rows.extend(cast(list[sqlite3.Row], cursor.fetchall()))++ summaries_by_id = {+ row["item_id"]: SessionQueueItemSummary.queue_item_summary_from_dict(dict(row)) for row in rows+ }+ return [summaries_by_id[item_id] for item_id in item_ids if item_id in summaries_by_id]+def get_queue_status(self,queue_id: str,diff --git a/invokeai/app/services/style_preset_records/style_preset_records_common.py b/invokeai/app/services/style_preset_records/style_preset_records_common.pyindex 9e6df88c98..7e465128f3 100644--- a/invokeai/app/services/style_preset_records/style_preset_records_common.py+++ b/invokeai/app/services/style_preset_records/style_preset_records_common.py@@ -1,3 +1,4 @@+import asyncioimport codecsimport csvimport json@@ -113,23 +114,15 @@ async def parse_presets_from_file(file: UploadFile) -> list[StylePresetWithoutIdif file.content_type not in ["text/csv", "application/json"]:raise UnsupportedFileTypeError()- if file.content_type == "text/csv":- csv_reader = csv.DictReader(codecs.iterdecode(file.file, "utf-8"))- data = list(csv_reader)- else: # file.content_type == "application/json":- json_data = await file.read()- data = json.loads(json_data)-try:- imported_presets = StylePresetImportListTypeAdapter.validate_python(data)-- style_presets: list[StylePresetWithoutId] = []+ if file.content_type == "text/csv":+ data = await asyncio.to_thread(_read_csv_rows, file.file)+ else: # file.content_type == "application/json":+ json_data = await file.read()+ data = await asyncio.to_thread(json.loads, json_data)- for imported in imported_presets:- preset_data = PresetData(positive_prompt=imported.positive_prompt, negative_prompt=imported.negative_prompt)- style_preset = StylePresetWithoutId(name=imported.name, preset_data=preset_data, type=PresetType.User)- style_presets.append(style_preset)- except pydantic.ValidationError as e:+ return await asyncio.to_thread(_build_style_presets, data)+ except (json.JSONDecodeError, pydantic.ValidationError) as e:if file.content_type == "text/csv":msg = "Invalid CSV format: must include columns 'name', 'prompt', and 'negative_prompt' and name cannot be blank"else: # file.content_type == "application/json":@@ -138,4 +131,18 @@ async def parse_presets_from_file(file: UploadFile) -> list[StylePresetWithoutIdfinally:file.file.close()++def _read_csv_rows(file: Any) -> list[dict[str, str]]:+ csv_reader = csv.DictReader(codecs.iterdecode(file, "utf-8"))+ return list(csv_reader)+++def _build_style_presets(data: Any) -> list[StylePresetWithoutId]:+ imported_presets = StylePresetImportListTypeAdapter.validate_python(data)+ style_presets: list[StylePresetWithoutId] = []++ for imported in imported_presets:+ preset_data = PresetData(positive_prompt=imported.positive_prompt, negative_prompt=imported.negative_prompt)+ style_preset = StylePresetWithoutId(name=imported.name, preset_data=preset_data, type=PresetType.User)+ style_presets.append(style_preset)return style_presetsdiff --git a/invokeai/app/services/users/users_default.py b/invokeai/app/services/users/users_default.pyindex 3ddc1a0327..8e57f21ab4 100644--- a/invokeai/app/services/users/users_default.py+++ b/invokeai/app/services/users/users_default.py@@ -28,6 +28,19 @@ class UserService(UserServiceBase):def create(self, user_data: UserCreateRequest, strict_password_checking: bool = True) -> UserDTO:"""Create a new user."""+ return self._create(user_data, strict_password_checking=strict_password_checking, require_no_admin=False)++ def _create(+ self,+ user_data: UserCreateRequest,+ strict_password_checking: bool,+ require_no_admin: bool,+ ) -> UserDTO:+ """Insert a user, optionally conditional on no administrator existing yet.++ `require_no_admin` is evaluated on the cursor that performs the INSERT so that the check+ and the write are one atomic step - see `create_admin` for why that matters.+ """# Validate password strengthif strict_password_checking:is_valid, error_msg = validate_password_strength(user_data.password)@@ -41,9 +54,22 @@ class UserService(UserServiceBase):raise ValueError(f"User with email {user_data.email} already exists")user_id = str(uuid4())+ # Hash before opening the transaction: hashing is deliberately slow, and the database is a+ # single connection behind a process-wide lock.password_hash = hash_password(user_data.password)with self._db.transaction() as cursor:+ if require_no_admin:+ # BEGIN IMMEDIATE takes the write lock up front, so this count cannot change+ # before the INSERT below commits. In-process callers are additionally+ # serialized by the database's shared RLock; the explicit lock also covers a+ # second process (invoke-useradd --admin) writing during the setup window.+ cursor.execute("BEGIN IMMEDIATE")+ # Same predicate as has_admin(), read on the cursor that performs the write.+ cursor.execute("SELECT COUNT(*) FROM users WHERE is_admin = TRUE AND is_active = TRUE")+ row = cursor.fetchone()+ if row and row[0] > 0:+ raise ValueError("Admin user already exists")try:cursor.execute("""@@ -255,10 +281,14 @@ class UserService(UserServiceBase):return bool(count > 0)def create_admin(self, user_data: UserCreateRequest, strict_password_checking: bool = True) -> UserDTO:- """Create an admin user (for initial setup)."""- if self.has_admin():- raise ValueError("Admin user already exists")+ """Create the first admin user (for initial setup).+ The "no admin exists yet" condition is enforced inside the INSERT's own transaction rather+ than by a preceding has_admin() call. `POST /auth/setup` is necessarily unauthenticated+ during the first-run window and runs in the threadpool, so two concurrent requests can both+ pass a check made in a separate transaction and both create an administrator. Callers may+ still check has_admin() first for a friendly error; this is the backstop that decides.+ """# Force is_admin to Trueadmin_data = UserCreateRequest(email=user_data.email,@@ -266,7 +296,7 @@ class UserService(UserServiceBase):password=user_data.password,is_admin=True,)- return self.create(admin_data, strict_password_checking=strict_password_checking)+ return self._create(admin_data, strict_password_checking=strict_password_checking, require_no_admin=True)def list_users(self, limit: int = 100, offset: int = 0) -> list[UserDTO]:"""List all users."""diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 92d3e561c2..1c49fd5392 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -2572,6 +2572,9 @@"404": {"description": "Model not found"},+ "409": {+ "description": "Another operation on this model is already in progress"+ },"422": {"description": "Validation Error","content": {@@ -3018,6 +3021,9 @@"404": {"description": "The model could not be found"},+ "409": {+ "description": "Another operation on this model is already in progress"+ },"422": {"description": "Validation Error","content": {@@ -3225,6 +3231,9 @@"400": {"description": "Bad request"},+ "409": {+ "description": "Another operation on this model is already in progress"+ },"422": {"description": "Validation Error","content": {@@ -3266,6 +3275,9 @@"404": {"description": "Model image not found"},+ "409": {+ "description": "Another operation on this model is already in progress"+ },"422": {"description": "Validation Error","content": {@@ -5803,8 +5815,9 @@"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": []@@ -6852,8 +6865,9 @@"get": {"tags": ["videos"],"summary": "Get Video Names",- "description": "Gets ordered list of video names with metadata for optimistic updates.",+ "description": "Gets ordered list of video 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 video-only endpoint predates the polymorphic gallery.","operationId": "get_video_names",+ "deprecated": true,"security": [{"HTTPBearer": []@@ -7355,12 +7369,184 @@}}},+ "/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": "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"],"summary": "Get Gallery Item Names",- "description": "Returns an ordered (kind, name) list \u2014 used to drive virtualized gallery selection.",+ "description": "Returns an ordered (kind, name) list \u2014 used to drive virtualized gallery selection.\n\nDeprecated: use `GET /v1/gallery/item_names`, which returns the same order as a flat name\nlist. The `kind` discriminator here costs a model per row \u2014 ~800ms on a 200k-item library \u2014\nfor a value callers already derive from the file extension.","operationId": "get_gallery_item_names",+ "deprecated": true,"security": [{"HTTPBearer": []@@ -8163,8 +8349,9 @@"get": {"tags": ["virtual_boards"],"summary": "List Virtual Board Image Names By Date",- "description": "Gets ordered image names for a specific date. Image-only; kept for API compatibility \u2014\nthe UI uses the polymorphic `/by_date/{date}/item_names` endpoint.",+ "description": "Gets ordered image names for a specific date. Image-only.\n\nDeprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which covers images and\nvideos in one ordered list.","operationId": "list_virtual_board_image_names_by_date",+ "deprecated": true,"security": [{"HTTPBearer": []@@ -8273,8 +8460,9 @@"get": {"tags": ["virtual_boards"],"summary": "List Virtual Board Item Names By Date",- "description": "Gets ordered polymorphic (image + video) item refs for a specific date.",+ "description": "Gets ordered polymorphic (image + video) item refs for a specific date.\n\nDeprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which returns the same\norder as a flat name list instead of one model per item.","operationId": "list_virtual_board_item_names_by_date",+ "deprecated": true,"security": [{"HTTPBearer": []@@ -9258,7 +9446,7 @@"post": {"tags": ["queue"],"summary": "Get Queue Items By Item Ids",- "description": "Gets queue items for the specified queue item ids. Maintains order of item ids.",+ "description": "Gets queue items for the specified queue item ids. Maintains order of item ids.\n\nBound the legacy full-item endpoint as well as the summary endpoint: callers can otherwise\nforce one graph deserialization and response copy per supplied id, defeating the queue-list\noptimization with an authenticated memory/CPU exhaustion request.","operationId": "get_queue_items_by_item_ids","security": [{@@ -9316,6 +9504,68 @@}}},+ "/api/v1/queue/{queue_id}/item_summaries_by_ids": {+ "post": {+ "tags": ["queue"],+ "summary": "Get Queue Item Summaries By Ids",+ "description": "Gets lightweight queue item summaries for specified IDs in requested order.",+ "operationId": "get_queue_item_summaries_by_ids",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "queue_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "The queue id to perform this operation on",+ "title": "Queue Id"+ },+ "description": "The queue id to perform this operation on"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Body_get_queue_item_summaries_by_ids"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/SessionQueueItemSummary"+ },+ "title": "Response 200 Get Queue Item Summaries By Ids"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v1/queue/{queue_id}/processor/resume": {"put": {"tags": ["queue"],@@ -15623,7 +15873,7 @@"anyOf": [{"type": "string",- "format": "binary"+ "contentMediaType": "application/octet-stream"},{"type": "null"@@ -15745,6 +15995,22 @@"required": ["image_names"],"title": "Body_get_images_by_names"},+ "Body_get_queue_item_summaries_by_ids": {+ "properties": {+ "item_ids": {+ "items": {+ "type": "integer"+ },+ "type": "array",+ "maxItems": 1000,+ "title": "Item Ids",+ "description": "Object containing list of queue item ids to fetch summaries for"+ }+ },+ "type": "object",+ "required": ["item_ids"],+ "title": "Body_get_queue_item_summaries_by_ids"+ },"Body_get_queue_items_by_item_ids": {"properties": {"item_ids": {@@ -15752,6 +16018,7 @@"type": "integer"},"type": "array",+ "maxItems": 1000,"title": "Item Ids","description": "Object containing list of queue item ids to fetch queue items for"}@@ -15764,7 +16031,7 @@"properties": {"file": {"type": "string",- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","description": "The file to import"}@@ -15854,7 +16121,7 @@"properties": {"image": {"type": "string",- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "Image","description": "The image file to upload"}@@ -15897,7 +16164,7 @@"properties": {"image": {"type": "string",- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "Image"}},@@ -15911,7 +16178,7 @@"anyOf": [{"type": "string",- "format": "binary"+ "contentMediaType": "application/octet-stream"},{"type": "null"@@ -15957,7 +16224,7 @@"properties": {"file": {"type": "string",- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File"},"resize_to": {@@ -15994,7 +16261,7 @@"properties": {"file": {"type": "string",- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File"},"metadata": {@@ -33481,6 +33748,32 @@"title": "GalleryItemKind","description": "Discriminator for polymorphic gallery items."},+ "GalleryItemNames": {+ "properties": {+ "item_names": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Item Names",+ "description": "Ordered list of image and video names."+ },+ "starred_count": {+ "type": "integer",+ "title": "Starred Count",+ "description": "Number of starred items (when starred_first=True)."+ },+ "total_count": {+ "type": "integer",+ "title": "Total Count",+ "description": "Total number of items matching the query."+ }+ },+ "type": "object",+ "required": ["item_names", "starred_count", "total_count"],+ "title": "GalleryItemNames",+ "description": "Ordered flat list of gallery item names plus counts for optimistic UI.\n\nNames are polymorphic \u2014 images and videos are interleaved by `created_at`. The kind of a\ngiven name is its file extension (`.mp4` is a video), which is how every consumer already\ndiscriminates. Mirrors the shape of the image-only `ImageNamesResult`."+ },"GalleryItemNamesResult": {"properties": {"items": {@@ -33505,7 +33798,7 @@"type": "object","required": ["items", "starred_count", "total_count"],"title": "GalleryItemNamesResult",- "description": "Ordered list of gallery item references plus counts for optimistic UI."+ "description": "Ordered list of gallery item references plus counts for optimistic UI.\n\nDeprecated in favour of :class:`GalleryItemNames`. Wrapping every name in an object to\ncarry a `kind` discriminator costs ~800ms of model construction on a 200k-item library,\nfor a field callers derive from the filename extension anyway."},"GalleryItemRef": {"properties": {@@ -62251,6 +62544,513 @@"title": "Main_SDNQ_Diffusers_ZImage_Config","description": "Model config for SDNQ-quantized Z-Image models in diffusers format (full ZImagePipeline folder)."},+ "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"+ ],+ "title": "Main_SDNQ_FLUX_Config",+ "description": "Model config for SDNQ-quantized FLUX transformer models."+ },+ "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"+ }+ },+ "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"+ ],+ "title": "Main_SDNQ_Flux2_Config",+ "description": "Model config for SDNQ-quantized FLUX.2 transformer models (e.g. Klein 4B / 9B)."+ },+ "Main_SDNQ_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": "z-image",+ "title": "Base",+ "default": "z-image"+ },+ "format": {+ "type": "string",+ "const": "sdnq_quantized",+ "title": "Format",+ "default": "sdnq_quantized"+ },+ "variant": {+ "$ref": "#/components/schemas/ZImageVariantType"+ }+ },+ "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"+ ],+ "title": "Main_SDNQ_ZImage_Config",+ "description": "Model config for SDNQ-quantized Z-Image transformer models."+ },"MaskCombineInvocation": {"category": "mask","class": "invocation",@@ -72981,149 +73781,303 @@"cpu_only","variant"],- "title": "Qwen3Encoder_GGUF_Config",- "description": "Configuration for GGUF-quantized Qwen3 Encoder models."- },- "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"- },- "base": {- "type": "string",- "const": "any",- "title": "Base",- "default": "any"- },- "type": {- "type": "string",- "const": "qwen3_encoder",- "title": "Type",- "default": "qwen3_encoder"- },- "format": {- "type": "string",- "const": "qwen3_encoder",- "title": "Format",- "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",- "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_GGUF_Config",+ "description": "Configuration for GGUF-quantized Qwen3 Encoder models."+ },+ "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"+ },+ "base": {+ "type": "string",+ "const": "any",+ "title": "Base",+ "default": "any"+ },+ "type": {+ "type": "string",+ "const": "qwen3_encoder",+ "title": "Type",+ "default": "qwen3_encoder"+ },+ "format": {+ "type": "string",+ "const": "qwen3_encoder",+ "title": "Format",+ "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",+ "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."+ },+ "Qwen3Encoder_SDNQ_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": "sdnq_quantized",+ "title": "Format",+ "default": "sdnq_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",+ "base",+ "type",+ "format",+ "cpu_only",+ "variant"+ ],+ "title": "Qwen3Encoder_SDNQ_Config",+ "description": "Configuration for SDNQ-quantized Qwen3 Encoder models (single file)."},"Qwen3Encoder_SDNQ_Folder_Config": {"properties": {@@ -79834,6 +80788,181 @@"title": "SessionQueueItem","description": "Session queue item without the full graph. Used for serialization."},+ "SessionQueueItemSummary": {+ "properties": {+ "item_id": {+ "type": "integer",+ "title": "Item Id",+ "description": "The identifier of the session queue item"+ },+ "created_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "string"+ }+ ],+ "title": "Created At",+ "description": "When this queue item was created"+ },+ "status": {+ "type": "string",+ "enum": ["pending", "in_progress", "waiting", "completed", "failed", "canceled"],+ "title": "Status",+ "description": "The status of this queue item"+ },+ "device": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Device",+ "description": "The device that processed this queue item, e.g. 'cuda:1'"+ },+ "started_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Started At",+ "description": "When this queue item was started"+ },+ "completed_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Completed At",+ "description": "When this queue item was completed"+ },+ "origin": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Origin",+ "description": "The origin of this queue item"+ },+ "destination": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Destination",+ "description": "The destination of this queue item"+ },+ "batch_id": {+ "type": "string",+ "title": "Batch Id",+ "description": "The ID of the batch associated with this queue item"+ },+ "user_id": {+ "type": "string",+ "title": "User Id",+ "description": "The ID of the user who created this queue item"+ },+ "user_display_name": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "User Display Name",+ "description": "The display name of the user who created this queue item"+ },+ "user_email": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "User Email",+ "description": "The email of the user who created this queue item"+ },+ "field_values": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/NodeFieldValue"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Field Values",+ "description": "The batch field values used for this queue item"+ },+ "parent_item_id": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Parent Item Id",+ "description": "The ID of the parent queue item, if this is a child item"+ }+ },+ "type": "object",+ "required": [+ "item_id",+ "created_at",+ "status",+ "started_at",+ "completed_at",+ "origin",+ "destination",+ "batch_id",+ "user_id",+ "user_display_name",+ "user_email",+ "field_values",+ "parent_item_id"+ ],+ "title": "SessionQueueItemSummary",+ "description": "Queue item fields needed to render the queue list."+ },"SessionQueueStatus": {"properties": {"queue_id": {@@ -87473,6 +88602,13 @@"type": {"type": "string","title": "Error Type"+ },+ "input": {+ "title": "Input"+ },+ "ctx": {+ "type": "object",+ "title": "Context"}},"type": "object",diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex 045a7021e2..6c87e0477a 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -418,6 +418,7 @@"queueActionsMenu": "Queue Actions Menu","queueEmpty": "Queue Empty","queueItem": "Queue Item",+ "queueItemLoadFailed": "This queue item could not be loaded.","enqueueing": "Queueing Batch","resume": "Resume","resumeTooltip": "Resume Processor",diff --git a/invokeai/frontend/web/scripts/typegen.js b/invokeai/frontend/web/scripts/typegen.jsindex 87c00a2883..f526b14946 100644--- a/invokeai/frontend/web/scripts/typegen.js+++ b/invokeai/frontend/web/scripts/typegen.js@@ -24,7 +24,13 @@ async function generateTypes(schema) {const types = await openapiTS(schema, {exportType: true,transform: (schemaObject) => {- if ('format' in schemaObject && schemaObject.format === 'binary') {+ // File upload fields. FastAPI emitted `format: binary` up to 0.129 and switched to the+ // OpenAPI 3.1 form `contentMediaType: application/octet-stream` in 0.130 — both must map+ // to `Blob`, or upload call sites silently start typing their `File` argument as `string`.+ const isBinary =+ ('format' in schemaObject && schemaObject.format === 'binary') ||+ ('contentMediaType' in schemaObject && schemaObject.contentMediaType === 'application/octet-stream');+ if (isBinary) {return schemaObject.nullable ? ts.factory.createUnionTypeNode([BLOB, NULL]) : BLOB;}if (schemaObject.title === 'MetadataField') {diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appStarted.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appStarted.tsindex a53b5e6767..aa1a03986b 100644--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appStarted.ts+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appStarted.ts@@ -1,4 +1,4 @@-import { createAction, isAnyOf } from '@reduxjs/toolkit';+import { createAction } from '@reduxjs/toolkit';import type { AppStartListening } from 'app/store/store';import { noop } from 'es-toolkit';import { setInfillMethod } from 'features/controlLayers/store/paramsSlice';@@ -6,7 +6,6 @@ import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors'import { imageSelected } from 'features/gallery/store/gallerySlice';import { appInfoApi } from 'services/api/endpoints/appInfo';import { galleryApi } from 'services/api/endpoints/gallery';-import { virtualBoardsApi } from 'services/api/endpoints/virtual_boards';export const appStarted = createAction('app/appStarted');@@ -31,20 +30,14 @@ export const addAppStartedListener = (startAppListening: AppStartListening) => {.catch(noop);// Ensure a gallery item is selected when we load the first board. The grid is fed by the- // polymorphic `getGalleryItemNames` endpoint (image + video names interleaved by date),+ // polymorphic `listGalleryItemNames` endpoint (image + video names interleaved by date),// so that's what we wait on — the older `getImageNames` is no longer dispatched and would- // time out forever.+ // time out forever. Date-based virtual boards go through the same endpoint.//// The effect must be async and await take() so that RTK keeps the listener's AbortController// alive until the query resolves; a synchronous effect causes the controller to be aborted// immediately after the effect returns, before any network response arrives.- const firstLoad = await take(- isAnyOf(- galleryApi.endpoints.getGalleryItemNames.matchFulfilled,- virtualBoardsApi.endpoints.getVirtualBoardItemNamesByDate.matchFulfilled- ),- 5000- );+ const firstLoad = await take(galleryApi.endpoints.listGalleryItemNames.matchFulfilled, 5000);if (firstLoad === null) {// timeout or cancelledreturn;@@ -54,9 +47,9 @@ export const addAppStartedListener = (startAppListening: AppStartListening) => {if (selectedItem) {return;}- const firstItem = payload.items[0];- if (firstItem) {- dispatch(imageSelected(firstItem.name));+ const firstItemName = payload.item_names[0];+ if (firstItemName) {+ dispatch(imageSelected(firstItemName));}},});diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.tsindex 65d2af4437..05dd8e9f20 100644--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts@@ -1,10 +1,8 @@import { isAnyOf } from '@reduxjs/toolkit';import type { AppStartListening } from 'app/store/store';-import { selectGetImageNamesQueryArgs, selectSelectedBoardId } from 'features/gallery/store/gallerySelectors';+import { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';import { boardIdSelected, galleryViewChanged, imageSelected } from 'features/gallery/store/gallerySlice';-import { getDateFromVirtualBoardId, isVirtualBoardId } from 'features/gallery/store/types';import { galleryApi } from 'services/api/endpoints/gallery';-import { virtualBoardsApi } from 'services/api/endpoints/virtual_boards';export const addBoardIdSelectedListener = (startAppListening: AppStartListening) => {startAppListening({@@ -18,23 +16,11 @@ export const addBoardIdSelectedListener = (startAppListening: AppStartListening)return;}- const state = getState();-- const board_id = selectSelectedBoardId(state);-- // The grid is now backed by the polymorphic getGalleryItemNames endpoint (the legacy+ // The grid is backed by the polymorphic listGalleryItemNames endpoint (the legacy// getImageNames query is no longer dispatched), so the auto-select probe must read its- // cache or it will time out and clear the user's selection on every board switch.- const queryArgs = { ...selectGetImageNamesQueryArgs(state), board_id };- const selectQuery = isVirtualBoardId(board_id)- ? virtualBoardsApi.endpoints.getVirtualBoardItemNamesByDate.select({- date: getDateFromVirtualBoardId(board_id),- categories: queryArgs.categories ?? undefined,- search_term: queryArgs.search_term || undefined,- order_dir: queryArgs.order_dir,- starred_first: queryArgs.starred_first,- })- : galleryApi.endpoints.getGalleryItemNames.select(queryArgs);+ // cache or it will time out and clear the user's selection on every board switch. The+ // selector already maps a virtual board id to its `created_date` filter.+ const selectQuery = galleryApi.endpoints.listGalleryItemNames.select(selectGalleryItemNamesQueryArgs(getState()));// wait until the board has some items - maybe it already has some from a previous fetch// must use getState() to ensure we do not have stale stateconst isSuccess = await condition(() => selectQuery(getState()).isSuccess, 5000);@@ -45,11 +31,9 @@ export const addBoardIdSelectedListener = (startAppListening: AppStartListening)}// the board was just changed - we can select the first gallery item (image or video)- const items = selectQuery(getState()).data?.items;-- const itemToSelect = items && items.length > 0 ? (items[0]?.name ?? null) : null;+ const itemNames = selectQuery(getState()).data?.item_names;- dispatch(imageSelected(itemToSelect));+ dispatch(imageSelected(itemNames?.[0] ?? null));},});};diff --git a/invokeai/frontend/web/src/features/gallery/components/GalleryImageGrid.tsx b/invokeai/frontend/web/src/features/gallery/components/GalleryImageGrid.tsxindex b62a8b01c8..7a33001384 100644--- a/invokeai/frontend/web/src/features/gallery/components/GalleryImageGrid.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/GalleryImageGrid.tsx@@ -3,7 +3,7 @@ import { createSelector } from '@reduxjs/toolkit';import { useAppSelector, useAppStore } from 'app/store/storeHooks';import { getFocusedRegion, useIsRegionFocused } from 'common/hooks/focus';import { getVideoPrefetchOptions, useRangeBasedImageFetching } from 'features/gallery/hooks/useRangeBasedImageFetching';-import type { selectGetImageNamesQueryArgs } from 'features/gallery/store/gallerySelectors';+import type { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';import {selectGalleryImageMinimumWidth,selectImageToCompare,@@ -42,7 +42,7 @@ import { scrollIntoView } from './scrollIntoView';import { useGalleryImageNames } from './use-gallery-image-names';import { useScrollableGallery } from './useScrollableGallery';-type ListImageNamesQueryArgs = ReturnType<typeof selectGetImageNamesQueryArgs>;+type ListImageNamesQueryArgs = ReturnType<typeof selectGalleryItemNamesQueryArgs>;type GridContext = {queryArgs: ListImageNamesQueryArgs;diff --git a/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.test.ts b/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.test.tsindex eff9123cc6..a42ae3d312 100644--- a/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.test.ts+++ b/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.test.ts@@ -1,34 +1,38 @@/**- * Pins the polymorphic name-flattening used by `useGalleryImageNames` for both regular boards- * and date-based virtual boards.+ * Pins the translation of a selected board into name-list query args.*- * The bug (PR #9163 review): virtual boards were image-only — selecting a virtual date fetched- * from the legacy image_names endpoint, so videos created on that date never appeared. The hook- * now consumes the by-date item_names endpoint, which returns the same (kind, name) refs as the- * regular gallery names endpoint, and this shared mapper must keep video refs in the flat list.- * (The server-side guarantee that a date query returns video refs is pinned by- * tests/app/routers/test_virtual_boards.py.)+ * A virtual board is a date, not a board row. Regular boards and virtual dates now share one+ * endpoint (`listGalleryItemNames`), so the only thing keeping virtual dates working is that+ * the id is converted into a `created_date` filter and *not* forwarded as `board_id` — the+ * backend would filter on a board that does not exist and return an empty gallery.+ *+ * The original bug this area guards (PR #9163 review): virtual boards were image-only, so+ * videos created on that date never appeared. The server-side half of that guarantee is pinned+ * by tests/app/routers/test_virtual_boards.py.*/-import type { GalleryItemRef } from 'services/api/types';+import { createStore } from 'app/store/store';+import { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';+import { boardIdSelected } from 'features/gallery/store/gallerySlice';import { describe, expect, it } from 'vitest';-import { itemRefsToNames } from './use-gallery-image-names';+describe('selectGalleryItemNamesQueryArgs', () => {+ it('converts a virtual board id into a created_date filter', () => {+ const store = createStore();+ store.dispatch(boardIdSelected({ boardId: 'by_date:2026-07-26' }));++ const args = selectGalleryItemNamesQueryArgs(store.getState());-describe('itemRefsToNames', () => {- it('keeps video refs interleaved with images, preserving order', () => {- const items: GalleryItemRef[] = [- { kind: 'image', name: 'newest.png' },- { kind: 'video', name: 'middle.mp4' },- { kind: 'image', name: 'oldest.png' },- ];- expect(itemRefsToNames(items)).toEqual(['newest.png', 'middle.mp4', 'oldest.png']);+ expect(args.created_date).toBe('2026-07-26');+ expect(args.board_id).toBeUndefined();});- it('handles a video-only list (video-only virtual date)', () => {- const items: GalleryItemRef[] = [- { kind: 'video', name: 'a.mp4' },- { kind: 'video', name: 'b.mp4' },- ];- expect(itemRefsToNames(items)).toEqual(['a.mp4', 'b.mp4']);+ it('passes a regular board id through untouched', () => {+ const store = createStore();+ store.dispatch(boardIdSelected({ boardId: 'some-board-uuid' }));++ const args = selectGalleryItemNamesQueryArgs(store.getState());++ expect(args.board_id).toBe('some-board-uuid');+ expect(args.created_date).toBeUndefined();});});diff --git a/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.ts b/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.tsindex 4749dc9de8..d4275b39d5 100644--- a/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.ts+++ b/invokeai/frontend/web/src/features/gallery/components/use-gallery-image-names.ts@@ -1,12 +1,7 @@-import { skipToken } from '@reduxjs/toolkit/query';import { EMPTY_ARRAY } from 'app/store/constants';import { useAppSelector } from 'app/store/storeHooks';-import { selectGetImageNamesQueryArgs, selectSelectedBoardId } from 'features/gallery/store/gallerySelectors';-import { getDateFromVirtualBoardId, isVirtualBoardId } from 'features/gallery/store/types';-import { useMemo } from 'react';-import { useGetGalleryItemNamesQuery } from 'services/api/endpoints/gallery';-import { useGetVirtualBoardItemNamesByDateQuery } from 'services/api/endpoints/virtual_boards';-import type { GalleryItemRef } from 'services/api/types';+import { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';+import { useListGalleryItemNamesQuery } from 'services/api/endpoints/gallery';import { useDebounce } from 'use-debounce';const selectFromGalleryItemNamesResult = ({@@ -14,11 +9,11 @@ const selectFromGalleryItemNamesResult = ({isLoading,isFetching,}: {- currentData?: { items: GalleryItemRef[] };+ currentData?: { item_names: string[] };isLoading: boolean;isFetching: boolean;}) => ({- items: currentData?.items ?? (EMPTY_ARRAY as GalleryItemRef[]),+ imageNames: currentData?.item_names ?? (EMPTY_ARRAY as string[]),isLoading,isFetching,});@@ -28,56 +23,19 @@ const galleryQueryOptions = {selectFromResult: selectFromGalleryItemNamesResult,};-/**- * Flattens polymorphic (kind, name) refs into the ordered name list consumed by the gallery- * grid and navigation hotkeys. Video refs must pass through untouched — regular boards and- * date-based virtual boards both contain them. Exported for tests.- */-export const itemRefsToNames = (items: GalleryItemRef[]): string[] => items.map((ref) => ref.name);-/*** Returns the ordered flat list of gallery item names. Names are polymorphic — both image and* video names appear in the same list, interleaved by created_at. Callers that need to know the* kind of a particular name use `isVideoName` from `features/gallery/store/types`.*- * Virtual boards (date-based) go through their own by-date endpoint, which returns the same- * polymorphic (kind, name) refs as the regular gallery names endpoint.+ * Regular boards and date-based virtual boards share one endpoint; the selector translates a+ * virtual board id into the `created_date` filter.*/export const useGalleryImageNames = () => {- const selectedBoardId = useAppSelector(selectSelectedBoardId);- const _imageQueryArgs = useAppSelector(selectGetImageNamesQueryArgs);- const [imageQueryArgs] = useDebounce(_imageQueryArgs, 300);- const isVirtual = isVirtualBoardId(selectedBoardId);-- // The polymorphic gallery names endpoint shares the same filter args as the image names- // endpoint (board_id, categories, search_term, order_dir, starred_first, is_intermediate).- const galleryResult = useGetGalleryItemNamesQuery(isVirtual ? skipToken : imageQueryArgs, galleryQueryOptions);-- const date = isVirtual ? getDateFromVirtualBoardId(selectedBoardId) : '';- const virtualResult = useGetVirtualBoardItemNamesByDateQuery(- isVirtual- ? {- date,- categories: imageQueryArgs.categories ?? undefined,- search_term: imageQueryArgs.search_term || undefined,- order_dir: imageQueryArgs.order_dir,- starred_first: imageQueryArgs.starred_first,- }- : skipToken,- galleryQueryOptions- );+ const _queryArgs = useAppSelector(selectGalleryItemNamesQueryArgs);+ const [queryArgs] = useDebounce(_queryArgs, 300);- // Flat names + isLoading exposed for backward compatibility with the existing callers (paged- // grid, search, navigation hotkeys). The kind is recoverable from the filename extension.- const imageNames = useMemo(() => {- const items = isVirtual ? virtualResult.items : galleryResult.items;- return itemRefsToNames(items);- }, [isVirtual, virtualResult.items, galleryResult.items]);+ const { imageNames, isLoading, isFetching } = useListGalleryItemNamesQuery(queryArgs, galleryQueryOptions);- return {- imageNames,- isLoading: isVirtual ? virtualResult.isLoading : galleryResult.isLoading,- isFetching: isVirtual ? virtualResult.isFetching : galleryResult.isFetching,- queryArgs: imageQueryArgs,- };+ return { imageNames, isLoading, isFetching, queryArgs };};diff --git a/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts b/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.tsindex aad849fdb5..54c65c541e 100644--- a/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts+++ b/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts@@ -1,8 +1,13 @@import { createSelector } from '@reduxjs/toolkit';import { createMemoizedSelector } from 'app/store/createMemoizedSelector';import { selectGallerySlice } from 'features/gallery/store/gallerySlice';-import { ASSETS_CATEGORIES, IMAGE_CATEGORIES } from 'features/gallery/store/types';-import type { GetImageNamesArgs, ListBoardsArgs } from 'services/api/types';+import {+ ASSETS_CATEGORIES,+ getDateFromVirtualBoardId,+ IMAGE_CATEGORIES,+ isVirtualBoardId,+} from 'features/gallery/store/types';+import type { GetImageNamesArgs, ListBoardsArgs, ListGalleryItemNamesArgs } from 'services/api/types';export const selectFirstSelectedItem = createSelector(selectGallerySlice, (gallery) => gallery.selection.at(0));export const selectLastSelectedItem = createSelector(selectGallerySlice, (gallery) => gallery.selection.at(-1));@@ -48,6 +53,25 @@ export const selectGetImageNamesQueryArgs = createMemoizedSelector(}));+/**+ * Query args for the polymorphic name list the gallery grid runs off.+ *+ * A virtual board is a date, not a board: its id carries the date and there is no board row to+ * filter on. Translating it to `created_date` here keeps that translation in one place — every+ * consumer of the name list (grid, range selection, auto-select probes) shares this selector,+ * so none of them can disagree about the cache key.+ */+export const selectGalleryItemNamesQueryArgs = createMemoizedSelector(+ [selectGetImageNamesQueryArgs],+ (args): ListGalleryItemNamesArgs => {+ if (args.board_id && isVirtualBoardId(args.board_id)) {+ const { board_id: _virtualBoardId, ...rest } = args;+ return { ...rest, created_date: getDateFromVirtualBoardId(args.board_id) };+ }+ return args;+ }+);+export const selectAutoAssignBoardOnClick = createSelector(selectGallerySlice,(gallery) => gallery.autoAssignBoardOnClickdiff --git a/invokeai/frontend/web/src/features/gallery/store/selectCachedGalleryItemNames.ts b/invokeai/frontend/web/src/features/gallery/store/selectCachedGalleryItemNames.tsindex f07a251b1b..aa935c88da 100644--- a/invokeai/frontend/web/src/features/gallery/store/selectCachedGalleryItemNames.ts+++ b/invokeai/frontend/web/src/features/gallery/store/selectCachedGalleryItemNames.ts@@ -1,18 +1,16 @@import type { AppGetState } from 'app/store/store';-import { getDateFromVirtualBoardId, isVirtualBoardId } from 'features/gallery/store/types';import { galleryApi } from 'services/api/endpoints/gallery';-import { virtualBoardsApi } from 'services/api/endpoints/virtual_boards';-import type { GetGalleryItemNamesArgs } from 'services/api/types';+import type { ListGalleryItemNamesArgs } from 'services/api/types';-import { selectGetImageNamesQueryArgs } from './gallerySelectors';+import { selectGalleryItemNamesQueryArgs } from './gallerySelectors';/*** Returns the names (in display order) of the currently-cached gallery item list.*- * The grid renders via the polymorphic ``getGalleryItemNames`` endpoint, which returns a- * mixed image+video list. Range-selection click handlers (shift-click for ranges, ctrl-click- * for discontiguous selection) need that ordered list to compute the items between two- * clicks.+ * The grid renders via the polymorphic ``listGalleryItemNames`` endpoint, which returns a+ * mixed image+video list — regular boards and date-based virtual boards alike. Range-selection+ * click handlers (shift-click for ranges, ctrl-click for discontiguous selection) need that+ * ordered list to compute the items between two clicks.** We look up the cache entry whose args match the gallery's current query args. RTK Query* keeps recently-used entries warm (60s default ``keepUnusedDataFor``), so after a board@@ -23,68 +21,32 @@ import { selectGetImageNamesQueryArgs } from './gallerySelectors';* forced a refetch.*/export const selectCachedGalleryItemNames = (state: ReturnType<AppGetState>): string[] => {- const args = selectGetImageNamesQueryArgs(state);- if (args.board_id && isVirtualBoardId(args.board_id)) {- const virtualArgs = {- date: getDateFromVirtualBoardId(args.board_id),- categories: args.categories ?? undefined,- search_term: args.search_term || undefined,- order_dir: args.order_dir,- starred_first: args.starred_first,- };- const virtual = virtualBoardsApi.endpoints.getVirtualBoardItemNamesByDate.select(virtualArgs)(state).data;- if (virtual) {- return virtual.items.map((ref) => ref.name);- }- const entries = virtualBoardsApi.util.selectInvalidatedBy(state, ['GalleryItemNameList']);- let mostRecent:- | {- names: string[];- fulfilledTimeStamp: number;- }- | undefined;- for (const entry of entries) {- if (entry.endpointName !== 'getVirtualBoardItemNamesByDate') {- continue;- }- const entryArgs = entry.originalArgs as typeof virtualArgs;- if (entryArgs.date !== virtualArgs.date) {- continue;- }- const query = virtualBoardsApi.endpoints.getVirtualBoardItemNamesByDate.select(entryArgs)(state);- if (query.data && (query.fulfilledTimeStamp ?? 0) >= (mostRecent?.fulfilledTimeStamp ?? -1)) {- mostRecent = {- names: query.data.items.map((ref) => ref.name),- fulfilledTimeStamp: query.fulfilledTimeStamp ?? 0,- };- }- }- return mostRecent?.names ?? [];- }+ const args = selectGalleryItemNamesQueryArgs(state);// Exact match: the entry the grid is actively subscribed to. This is the common case.- const exact = galleryApi.endpoints.getGalleryItemNames.select(args)(state).data;+ const exact = galleryApi.endpoints.listGalleryItemNames.select(args)(state).data;if (exact) {- return exact.items.map((ref) => ref.name);+ return exact.item_names;}// Debounce window: the grid hook debounces its args by ~300ms, so for a moment after the- // user changes a filter the cache key may not match Redux yet. Best-effort fallback to any- // cached entry on the same board so range selection still feels responsive — but do not- // silently fall back to an unrelated board's entry, which was the bug.+ // user changes a filter the cache key may not match Redux yet. Best-effort fallback to the+ // most recent cached entry for the same board or date, so range selection still feels+ // responsive — but do not silently fall back to an unrelated board's entry, which was the bug.const entries = galleryApi.util.selectInvalidatedBy(state, ['GalleryItemNameList']);+ let mostRecent: { names: string[]; fulfilledTimeStamp: number } | undefined;for (const entry of entries) {- if (entry.endpointName !== 'getGalleryItemNames') {+ if (entry.endpointName !== 'listGalleryItemNames') {continue;}- const entryArgs = entry.originalArgs as GetGalleryItemNamesArgs | undefined;- if (!entryArgs || entryArgs.board_id !== args.board_id) {+ const entryArgs = entry.originalArgs as ListGalleryItemNamesArgs | undefined;+ if (!entryArgs || entryArgs.board_id !== args.board_id || entryArgs.created_date !== args.created_date) {continue;}- const data = galleryApi.endpoints.getGalleryItemNames.select(entryArgs)(state).data;- if (data) {- return data.items.map((ref) => ref.name);+ const query = galleryApi.endpoints.listGalleryItemNames.select(entryArgs)(state);+ if (query.data && (query.fulfilledTimeStamp ?? 0) >= (mostRecent?.fulfilledTimeStamp ?? -1)) {+ mostRecent = { names: query.data.item_names, fulfilledTimeStamp: query.fulfilledTimeStamp ?? 0 };}}- return [];+ return mostRecent?.names ?? [];};/**diff --git a/invokeai/frontend/web/src/features/gallery/store/virtualBoardGalleryConsumers.test.ts b/invokeai/frontend/web/src/features/gallery/store/virtualBoardGalleryConsumers.test.tsindex e66b487042..d4c3d94db0 100644--- a/invokeai/frontend/web/src/features/gallery/store/virtualBoardGalleryConsumers.test.ts+++ b/invokeai/frontend/web/src/features/gallery/store/virtualBoardGalleryConsumers.test.ts@@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url';import { createStore } from 'app/store/store';import { boardIdSelected, searchTermChanged } from 'features/gallery/store/gallerySlice';-import { virtualBoardsApi } from 'services/api/endpoints/virtual_boards';+import { galleryApi } from 'services/api/endpoints/gallery';import { describe, expect, it } from 'vitest';import { selectCachedGalleryItemNames } from './selectCachedGalleryItemNames';@@ -27,29 +27,28 @@ describe('virtual board gallery consumers', () => {['range selection', './selectCachedGalleryItemNames.ts'],['board auto-selection', '../../../app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts'],['initial board auto-selection', '../../../app/store/middleware/listenerMiddleware/listeners/appStarted.ts'],- ])('%s reads the virtual-board item-name cache', (_label, relativePath) => {+ ])('%s reads the polymorphic item-name cache', (_label, relativePath) => {const source = readSource(relativePath);- expect(source).toContain('getVirtualBoardItemNamesByDate');+ // Regular boards and virtual dates share one endpoint; a consumer that reached for a+ // different cache would silently see an empty list on virtual dates.+ expect(source).toContain('listGalleryItemNames');});it('keeps the prior virtual-board cache available during filter debounce', async () => {const store = createStore();store.dispatch(boardIdSelected({ boardId: 'by_date:2026-07-26' }));await store.dispatch(- virtualBoardsApi.util.upsertQueryData(- 'getVirtualBoardItemNamesByDate',+ galleryApi.util.upsertQueryData(+ 'listGalleryItemNames',{- date: '2026-07-26',+ created_date: '2026-07-26',categories: ['general'],order_dir: 'DESC',starred_first: true,+ is_intermediate: false,},- {- items: [{ name: 'cached.mp4', kind: 'video' }],- starred_count: 0,- total_count: 1,- }+ { item_names: ['cached.mp4'], starred_count: 0, total_count: 1 }));@@ -62,39 +61,33 @@ describe('virtual board gallery consumers', () => {const store = createStore();store.dispatch(boardIdSelected({ boardId: 'by_date:2026-07-26' }));await store.dispatch(- virtualBoardsApi.util.upsertQueryData(- 'getVirtualBoardItemNamesByDate',+ galleryApi.util.upsertQueryData(+ 'listGalleryItemNames',{- date: '2026-07-26',+ created_date: '2026-07-26',categories: ['general'],search_term: 'older filter',order_dir: 'DESC',starred_first: true,+ is_intermediate: false,},- {- items: [{ name: 'older.mp4', kind: 'video' }],- starred_count: 0,- total_count: 1,- }+ { item_names: ['older.mp4'], starred_count: 0, total_count: 1 }));await new Promise<void>((resolve) => {setTimeout(resolve, 5);});await store.dispatch(- virtualBoardsApi.util.upsertQueryData(- 'getVirtualBoardItemNamesByDate',+ galleryApi.util.upsertQueryData(+ 'listGalleryItemNames',{- date: '2026-07-26',+ created_date: '2026-07-26',categories: ['general'],order_dir: 'DESC',starred_first: true,+ is_intermediate: false,},- {- items: [{ name: 'active.mp4', kind: 'video' }],- starred_count: 0,- total_count: 1,- }+ { item_names: ['active.mp4'], starred_count: 0, total_count: 1 }));diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsxindex 9583a3b234..8316f682d2 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx@@ -23,7 +23,7 @@ const selectedStyles = { bg: 'base.700' };type InnerItemProps = {index: number;- item: S['SessionQueueItem'];+ item: S['SessionQueueItemSummary'];};const sx: ChakraProps['sx'] = {diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsxindex 02c25761c5..04e2b64bb8 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx@@ -18,24 +18,26 @@ import type { S } from 'services/api/types';import { getQueueItemActionVisibility } from './getQueueItemActionVisibility';type Props = {- queueItem: S['SessionQueueItem'];+ queueItem: S['SessionQueueItemSummary'];};-const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {- const { session_id, batch_id, item_id, origin, destination } = queueItemDTO;+const QueueItemComponent = ({ queueItem: queueItemSummary }: Props) => {+ const { batch_id, item_id, origin, destination } = queueItemSummary;const { t } = useTranslation();const isBatchCanceled = useBatchIsCanceled(batch_id);const cancelBatch = useCancelBatch();const cancelQueueItem = useCancelQueueItem();const retryQueueItem = useRetryQueueItem();- const { data: queueItem } = useGetQueueItemQuery(item_id);+ const { data: queueItem, isError } = useGetQueueItemQuery(item_id);const originText = useOriginText(origin);const destinationText = useDestinationText(destination);const statusAndTiming = useMemo(() => {if (!queueItem) {- return t('common.loading');+ // Distinguish the two, or a queue item the backend cannot serve — one whose graph+ // references a node type this build no longer registers, say — reads as loading forever.+ return isError ? t('common.error') : t('common.loading');}if (!queueItem.completed_at || !queueItem.started_at) {return t(`queue.${queueItem.status}`);@@ -45,7 +47,7 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {return `${t('queue.completedIn')} ${seconds}${seconds === 1 ? '' : 's'}`;}return `${seconds}s`;- }, [queueItem, t]);+ }, [isError, queueItem, t]);const isCanceled = useMemo(() => !!queueItem && ['canceled', 'completed', 'failed'].includes(queueItem.status),@@ -54,8 +56,8 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {const isFailed = useMemo(() => !!queueItem && ['canceled', 'failed'].includes(queueItem.status), [queueItem]);const { canShowCancelQueueItem, canShowRetryQueueItem } = useMemo(- () => getQueueItemActionVisibility(queueItemDTO),- [queueItemDTO]+ () => getQueueItemActionVisibility(queueItemSummary),+ [queueItemSummary]);const onCancelBatch = useCallback(() => {@@ -86,7 +88,10 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {<QueueItemData label={t('queue.destination')} data={destinationText} /><QueueItemData label={t('queue.item')} data={item_id} /><QueueItemData label={t('queue.batch')} data={batch_id} />- <QueueItemData label={t('queue.session')} data={session_id} />+ <QueueItemData+ label={t('queue.session')}+ data={queueItem?.session_id ?? (isError ? t('common.error') : t('common.loading'))}+ /><ButtonGroup size="xs" orientation="vertical">{canShowCancelQueueItem && !isFailed && (<Button@@ -147,6 +152,8 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {data={queueItem}extraCopyActions={[{ label: 'Graph', getData: (data) => get(data, 'session.graph') }]}/>+ ) : isError ? (+ <Text color="error.400">{t('queue.queueItemLoadFailed')}</Text>) : (<Spinner opacity={0.5} />)}diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueList.tsx b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueList.tsxindex 7e3b58bf04..1a62610c98 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueList.tsx+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueList.tsx@@ -35,8 +35,8 @@ const QueueItemAtPosition = memo(({ index, itemId }: { index: number; itemId: nu*/// Use `currentData` instead of `data` to prevent a flash of previous queue item rendered at this index- const { currentData: queueItem, isUninitialized } = queueApi.endpoints.getQueueItem.useQueryState(itemId);- queueApi.endpoints.getQueueItem.useQuerySubscription(itemId, { skip: isUninitialized });+ const { currentData: queueItem, isUninitialized } = queueApi.endpoints.getQueueItemSummary.useQueryState(itemId);+ queueApi.endpoints.getQueueItemSummary.useQuerySubscription(itemId, { skip: isUninitialized });if (!queueItem) {return <QueueItemPlaceholder item-id={itemId} />;diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.ts b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.tsindex b9576a2b6f..1aebe797e8 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.ts+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.ts@@ -1,9 +1,15 @@import type { S } from 'services/api/types';-const isChildQueueItem = (item: S['SessionQueueItem']): boolean =>+/**+ * Takes the fields common to a full queue item and a list summary: the list rows decide from a+ * summary, the expanded detail view from the same summary it was handed.+ */+type QueueItemActionSubject = Pick<S['SessionQueueItem'], 'parent_item_id'>;++const isChildQueueItem = (item: QueueItemActionSubject): boolean =>item.parent_item_id !== null && item.parent_item_id !== undefined;-export const getQueueItemActionVisibility = (item: S['SessionQueueItem']) => ({+export const getQueueItemActionVisibility = (item: QueueItemActionSubject) => ({canShowCancelQueueItem: true,canShowRetryQueueItem: !isChildQueueItem(item),});diff --git a/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.test.ts b/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.test.tsnew file mode 100644index 0000000000..a2dba466f7--- /dev/null+++ b/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { getItemIdBatches, getUncachedItemIds } from './useRangeBasedQueueItemFetching';++describe('queue item summary batching', () => {+ it('sends nothing when there is nothing to fetch', () => {+ expect(getItemIdBatches([])).toEqual([]);+ });++ it('keeps a request that is exactly at the backend limit in one batch', () => {+ const batches = getItemIdBatches(Array.from({ length: 1000 }, (_, i) => i));+ expect(batches).toHaveLength(1);+ expect(batches[0]).toHaveLength(1000);+ });++ it('splits past the backend limit, which rejects larger batches with a 422', () => {+ const itemIds = Array.from({ length: 2001 }, (_, i) => i);++ const batches = getItemIdBatches(itemIds);++ expect(batches.map((batch) => batch.length)).toEqual([1000, 1000, 1]);+ // Every id is sent exactly once, in order — a dropped id means a row stuck on its placeholder.+ expect(batches.flat()).toEqual(itemIds);+ });++ it('does not re-request ids while their bulk request is still in flight', () => {+ const ranges = [{ startIndex: 0, endIndex: 2 }];++ expect(getUncachedItemIds([11, 12, 13], [], ranges, new Set([12]))).toEqual([11, 13]);+ });+});diff --git a/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.ts b/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.tsindex b2d4c4ac81..645dcc5b8e 100644--- a/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.ts+++ b/invokeai/frontend/web/src/features/queue/hooks/useRangeBasedQueueItemFetching.ts@@ -1,7 +1,7 @@import { useAppStore } from 'app/store/storeHooks';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import type { ListRange } from 'react-virtuoso';-import { queueApi, useGetQueueItemDTOsByItemIdsMutation } from 'services/api/endpoints/queue';+import { queueApi, useGetQueueItemSummariesByItemIdsMutation } from 'services/api/endpoints/queue';import { useThrottledCallback } from 'use-debounce';interface UseRangeBasedQueueItemFetchingArgs {@@ -13,14 +13,33 @@ interface UseRangeBasedQueueItemFetchingReturn {onRangeChanged: (range: ListRange) => void;}-const getUncachedItemIds = (itemIds: number[], cachedItemIds: number[], ranges: ListRange[]): number[] => {+/**+ * Mirrors MAX_QUEUE_ITEM_IDS_PER_REQUEST on the backend, which rejects larger batches outright.+ * A fast fling can union enough visible ranges to exceed it, so split instead of risking a 422.+ */+const MAX_ITEM_IDS_PER_REQUEST = 1000;++export const getItemIdBatches = (itemIds: number[]): number[][] => {+ const batches: number[][] = [];+ for (let i = 0; i < itemIds.length; i += MAX_ITEM_IDS_PER_REQUEST) {+ batches.push(itemIds.slice(i, i + MAX_ITEM_IDS_PER_REQUEST));+ }+ return batches;+};++export const getUncachedItemIds = (+ itemIds: number[],+ cachedItemIds: number[],+ ranges: ListRange[],+ pendingItemIds: Set<number> = new Set()+): number[] => {const uncachedItemIdsSet = new Set<number>();const cachedItemIdsSet = new Set(cachedItemIds);for (const range of ranges) {for (let i = range.startIndex; i <= range.endIndex; i++) {const n = itemIds[i]!;- if (n && !cachedItemIdsSet.has(n)) {+ if (n && !cachedItemIdsSet.has(n) && !pendingItemIds.has(n)) {uncachedItemIdsSet.add(n);}}@@ -30,33 +49,44 @@ const getUncachedItemIds = (itemIds: number[], cachedItemIds: number[], ranges:};/**- * Hook for bulk fetching queue items based on the visible range from virtuoso.- * Individual quite item components should use `useGetQueueItemQuery(item_id)` to get their specific DTO.- * This hook ensures DTOs are bulk fetched and cached efficiently.+ * Hook for bulk fetching queue item summaries based on the visible range from virtuoso.+ * Individual queue item components read the cached summary via `getQueueItemSummary`; only the+ * expanded detail view fetches the full item, which is what keeps the session graph and workflow+ * off the wire while scrolling.+ * This hook ensures summaries are bulk fetched and cached efficiently.*/export const useRangeBasedQueueItemFetching = ({itemIds,enabled,}: UseRangeBasedQueueItemFetchingArgs): UseRangeBasedQueueItemFetchingReturn => {const store = useAppStore();- const [getQueueItemDTOsByItemIds] = useGetQueueItemDTOsByItemIdsMutation();+ const [getQueueItemSummariesByItemIds] = useGetQueueItemSummariesByItemIdsMutation();const [lastRange, setLastRange] = useState<ListRange | null>(null);const [pendingRanges, setPendingRanges] = useState<ListRange[]>([]);+ const pendingItemIdsRef = useRef<Set<number>>(new Set());const fetchQueueItems = useCallback((ranges: ListRange[], itemIds: number[]) => {if (!enabled) {return;}- const cachedItemIds = queueApi.util.selectCachedArgsForQuery(store.getState(), 'getQueueItem');- const uncachedItemIds = getUncachedItemIds(itemIds, cachedItemIds, ranges);+ const cachedItemIds = queueApi.util.selectCachedArgsForQuery(store.getState(), 'getQueueItemSummary');+ const uncachedItemIds = getUncachedItemIds(itemIds, cachedItemIds, ranges, pendingItemIdsRef.current);if (uncachedItemIds.length === 0) {return;}- getQueueItemDTOsByItemIds({ item_ids: uncachedItemIds });+ for (const item_ids of getItemIdBatches(uncachedItemIds)) {+ item_ids.forEach((item_id) => pendingItemIdsRef.current.add(item_id));+ void getQueueItemSummariesByItemIds({ item_ids })+ .unwrap()+ .then(+ () => item_ids.forEach((item_id) => pendingItemIdsRef.current.delete(item_id)),+ () => item_ids.forEach((item_id) => pendingItemIdsRef.current.delete(item_id))+ );+ }setPendingRanges([]);},- [enabled, getQueueItemDTOsByItemIds, store]+ [enabled, getQueueItemSummariesByItemIds, store]);const throttledFetchQueueItems = useThrottledCallback(fetchQueueItems, 500);diff --git a/invokeai/frontend/web/src/services/api/endpoints/gallery.ts b/invokeai/frontend/web/src/services/api/endpoints/gallery.tsindex 5b3dd85493..aa9eb95b51 100644--- a/invokeai/frontend/web/src/services/api/endpoints/gallery.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/gallery.ts@@ -1,12 +1,13 @@import type {- GetGalleryItemNamesArgs,- GetGalleryItemNamesResult,+ ListGalleryItemNamesArgs,+ ListGalleryItemNamesResult,ListGalleryItemsArgs,ListGalleryItemsResponse,} from 'services/api/types';import { getListGalleryItemsUrl } from 'services/api/util';import stableHash from 'stable-hash';+import type { ApiTagDescription } from '..';import { api, buildV1Url } from '..';/**@@ -34,25 +35,37 @@ export const galleryApi = api.injectEndpoints({}),/**- * Ordered (kind, name) refs for virtualized selection. The gallery grid's name list and- * keyboard navigation use this — the flat string list is derived by mapping items to `name`.+ * Ordered flat name list for virtualized selection — the gallery grid and keyboard+ * navigation run off this. A name ending in `.mp4` is a video.+ *+ * `created_date` selects a date-based virtual board; without it the usual board/category+ * filters apply. Both cases go through this one endpoint.*/- getGalleryItemNames: build.query<GetGalleryItemNamesResult, GetGalleryItemNamesArgs>({+ listGalleryItemNames: build.query<ListGalleryItemNamesResult, ListGalleryItemNamesArgs>({query: (queryArgs) => ({- url: buildGalleryUrl('items/names', queryArgs),+ url: buildGalleryUrl('item_names', queryArgs),method: 'GET',}),- providesTags: (result, error, queryArgs) => [- 'GalleryItemNameList',- 'FetchOnReconnect',- { type: 'GalleryItemNameList', id: stableHash(queryArgs) },- ],+ providesTags: (result, error, queryArgs) => {+ const tags: ApiTagDescription[] = [+ 'GalleryItemNameList',+ 'FetchOnReconnect',+ { type: 'GalleryItemNameList', id: stableHash(queryArgs) },+ ];+ if (queryArgs.created_date) {+ // Image and video mutations both have to refetch a virtual date's contents, so a+ // date-scoped request also carries each kind's name-list tag.+ tags.push({ type: 'ImageNameList', id: `virtual_${queryArgs.created_date}` });+ tags.push({ type: 'VideoNameList', id: `virtual_${queryArgs.created_date}` });+ }+ return tags;+ },}),}),});-// useGetGalleryItemNamesQuery is consumed by use-gallery-image-names.ts.-export const { useGetGalleryItemNamesQuery } = galleryApi;+// useListGalleryItemNamesQuery is consumed by use-gallery-image-names.ts.+export const { useListGalleryItemNamesQuery } = galleryApi;/** @knipignore Lands with the paged gallery view / future bulk-DTO consumers; not used today. */export const { useListGalleryItemsQuery } = galleryApi;diff --git a/invokeai/frontend/web/src/services/api/endpoints/queue.ts b/invokeai/frontend/web/src/services/api/endpoints/queue.tsindex 0ce864882f..5aa65a7379 100644--- a/invokeai/frontend/web/src/services/api/endpoints/queue.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/queue.ts@@ -1,11 +1,12 @@+import type { FetchBaseQueryError } from '@reduxjs/toolkit/query/react';import { getUserScopedQueueCounts } from 'features/queue/store/userScopedQueueCounts';import queryString from 'query-string';import type { components, paths } from 'services/api/schema';import type {- GetQueueItemDTOsByItemIdsArgs,- GetQueueItemDTOsByItemIdsResult,GetQueueItemIdsArgs,GetQueueItemIdsResult,+ GetQueueItemSummariesByItemIdsArgs,+ GetQueueItemSummariesByItemIdsResult,} from 'services/api/types';import { getQueueStatusWithObservedEvents } from 'services/events/queueStatusEvents';import stableHash from 'stable-hash';@@ -331,24 +332,70 @@ export const queueApi = api.injectEndpoints({{ type: 'SessionQueueItemIdList', id: stableHash(queryArgs) },],}),- getQueueItemDTOsByItemIds: build.mutation<GetQueueItemDTOsByItemIdsResult, GetQueueItemDTOsByItemIdsArgs>({+ /**+ * The list rows render from summaries, not from full queue items: a full item carries its+ * session graph and workflow, which is megabytes per screenful of rows and is needed by+ * nothing the list draws. The detail view fetches the full item itself via `getQueueItem`+ * when a row is expanded.+ *+ * Fetched one id at a time so that each row is an independently invalidatable cache entry,+ * exactly like `getQueueItem`. `getQueueItemSummariesByItemIds` primes many of these entries+ * in one request; this query is what refetches a single one after an invalidation.+ */+ getQueueItemSummary: build.query<GetQueueItemSummariesByItemIdsResult[number], number>({+ queryFn: async (item_id, _api, _extraOptions, baseQuery) => {+ const result = await baseQuery({+ url: buildQueueUrl('item_summaries_by_ids'),+ method: 'POST',+ body: { item_ids: [item_id] },+ });+ if (result.error) {+ return { error: result.error };+ }+ const summary = (result.data as GetQueueItemSummariesByItemIdsResult)[0];+ if (!summary) {+ // The route omits ids it cannot find rather than erroring, which happens when an item is+ // deleted between the id list being fetched and this row scrolling into view. Surface it+ // as the 404 `getQueueItem` would give, so the row falls back to its placeholder instead+ // of caching `undefined` as if it were an item.+ return {+ error: { status: 404, data: `Queue item ${item_id} not found` } satisfies FetchBaseQueryError,+ };+ }+ return { data: summary };+ },+ // Same tags getQueueItem provides, so every existing per-item invalidation — socket status+ // events, cancel, delete, retry — refreshes the list row as well, with nothing to wire up.+ providesTags: (result) => {+ const tags: ApiTagDescription[] = ['FetchOnReconnect'];+ if (result) {+ tags.push({ type: 'SessionQueueItem', id: result.item_id });+ tags.push({ type: 'BatchStatus', id: result.batch_id });+ }+ return tags;+ },+ }),+ getQueueItemSummariesByItemIds: build.mutation<+ GetQueueItemSummariesByItemIdsResult,+ GetQueueItemSummariesByItemIdsArgs+ >({query: (body) => ({- url: buildQueueUrl('items_by_ids'),+ url: buildQueueUrl('item_summaries_by_ids'),method: 'POST',body,}),- // Don't provide cache tags - we'll manually upsert into individual getQueueItem caches+ // Don't provide cache tags - we'll manually upsert into individual getQueueItemSummary cachesasync onQueryStarted(_, { dispatch, queryFulfilled }) {try {- const { data: queueItems } = await queryFulfilled;+ const { data: summaries } = await queryFulfilled;- // Upsert each queue item into the individual item cache+ // Upsert each summary into the individual item cacheconst updates: Param0<typeof queueApi.util.upsertQueryEntries> = [];- for (const queueItem of queueItems) {+ for (const summary of summaries) {updates.push({- endpointName: 'getQueueItem',- arg: queueItem.item_id,- value: queueItem,+ endpointName: 'getQueueItemSummary',+ arg: summary.item_id,+ value: summary,});}dispatch(queueApi.util.upsertQueryEntries(updates));@@ -413,7 +460,7 @@ export const {useGetQueueStatusQuery,useGetQueueItemQuery,useGetQueueItemIdsQuery,- useGetQueueItemDTOsByItemIdsMutation,+ useGetQueueItemSummariesByItemIdsMutation,useCancelQueueItemMutation,useCancelQueueItemsByDestinationMutation,useGetCurrentQueueItemQuery,diff --git a/invokeai/frontend/web/src/services/api/endpoints/virtual_boards.ts b/invokeai/frontend/web/src/services/api/endpoints/virtual_boards.tsindex 4a8e9ef9ff..9cc1ba3329 100644--- a/invokeai/frontend/web/src/services/api/endpoints/virtual_boards.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/virtual_boards.ts@@ -1,6 +1,3 @@-import queryString from 'query-string';-import type { GetGalleryItemNamesResult, ImageCategory } from 'services/api/types';-import type { ApiTagDescription } from '..';import { api, buildV1Url } from '..';@@ -17,7 +14,9 @@ export type VirtualSubBoard = {const buildVirtualBoardsUrl = (path: string = '') => buildV1Url(`virtual_boards/${path}`);-export const virtualBoardsApi = api.injectEndpoints({+// Not exported: with virtual-date name lists served by `listGalleryItemNames`, nothing outside+// this module needs the api object itself — only the hook below.+const virtualBoardsApi = api.injectEndpoints({endpoints: (build) => ({listVirtualBoardsByDate: build.query<VirtualSubBoard[], void>({query: () => ({@@ -25,36 +24,9 @@ export const virtualBoardsApi = api.injectEndpoints({}),providesTags: (): ApiTagDescription[] => ['VirtualBoards', 'FetchOnReconnect'],}),-- /**- * Polymorphic (image + video) refs for a virtual date board. Same result shape as the- * gallery's `getGalleryItemNames`, so the gallery grid can consume either transparently.- */- getVirtualBoardItemNamesByDate: build.query<- GetGalleryItemNamesResult,- {- date: string;- starred_first?: boolean;- order_dir?: 'ASC' | 'DESC';- categories?: ImageCategory[];- search_term?: string;- }- >({- query: ({ date, ...params }) => ({- url: buildVirtualBoardsUrl(- `by_date/${date}/item_names?${queryString.stringify(params, { arrayFormat: 'none', skipNull: true, skipEmptyString: true })}`- ),- }),- // Both image and video mutations must refetch a virtual date's contents, so this- // provides the name-list tag of each kind plus the polymorphic one.- providesTags: (_result, _error, arg): ApiTagDescription[] => [- { type: 'ImageNameList', id: `virtual_${arg.date}` },- { type: 'VideoNameList', id: `virtual_${arg.date}` },- 'GalleryItemNameList',- 'FetchOnReconnect',- ],- }),}),});-export const { useListVirtualBoardsByDateQuery, useGetVirtualBoardItemNamesByDateQuery } = virtualBoardsApi;+// Virtual-date name lists are served by `listGalleryItemNames` with a `created_date` filter;+// the deprecated `by_date/{date}/item_names` route is no longer called from the UI.+export const { useListVirtualBoardsByDateQuery } = virtualBoardsApi;diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex e52e01e423..b4d1d6758d 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1334,7 +1334,11 @@ export type paths = {};/*** Get Image Names- * @description Gets ordered list of image names with metadata for optimistic updates+ * @deprecated+ * @description 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.*/get: operations["get_image_names"];put?: never;@@ -1575,7 +1579,11 @@ export type paths = {};/*** Get Video Names+ * @deprecated* @description Gets ordered list of video names with metadata for optimistic updates.+ *+ * Deprecated: use `GET /v1/gallery/item_names`, which returns images and videos interleaved+ * in one ordered list. This video-only endpoint predates the polymorphic gallery.*/get: operations["get_video_names"];put?: never;@@ -1658,6 +1666,29 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/gallery/item_names": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * List Gallery Item Names+ * @description 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.+ */+ get: operations["list_gallery_item_names"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/gallery/items/names": {parameters: {query?: never;@@ -1667,7 +1698,12 @@ export type paths = {};/*** Get Gallery Item Names+ * @deprecated* @description 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.*/get: operations["get_gallery_item_names"];put?: never;@@ -1843,8 +1879,11 @@ export type paths = {};/*** List Virtual Board Image Names By Date- * @description Gets ordered image names for a specific date. Image-only; kept for API compatibility —- * the UI uses the polymorphic `/by_date/{date}/item_names` endpoint.+ * @deprecated+ * @description Gets ordered image names for a specific date. Image-only.+ *+ * Deprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which covers images and+ * videos in one ordered list.*/get: operations["list_virtual_board_image_names_by_date"];put?: never;@@ -1864,7 +1903,11 @@ export type paths = {};/*** List Virtual Board Item Names By Date+ * @deprecated* @description Gets ordered polymorphic (image + video) item refs for a specific date.+ *+ * Deprecated: use `GET /v1/gallery/item_names?created_date=<date>`, which returns the same+ * order as a flat name list instead of one model per item.*/get: operations["list_virtual_board_item_names_by_date"];put?: never;@@ -2264,6 +2307,10 @@ export type paths = {/*** Get Queue Items By Item Ids* @description Gets queue items for the specified queue item ids. Maintains order of item ids.+ *+ * Bound the legacy full-item endpoint as well as the summary endpoint: callers can otherwise+ * force one graph deserialization and response copy per supplied id, defeating the queue-list+ * optimization with an authenticated memory/CPU exhaustion request.*/post: operations["get_queue_items_by_item_ids"];delete?: never;@@ -2272,6 +2319,26 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/queue/{queue_id}/item_summaries_by_ids": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Get Queue Item Summaries By Ids+ * @description Gets lightweight queue item summaries for specified IDs in requested order.+ */+ post: operations["get_queue_item_summaries_by_ids"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/queue/{queue_id}/processor/resume": {parameters: {query?: never;@@ -4779,6 +4846,14 @@ export type components = {*/image_names: string[];};+ /** Body_get_queue_item_summaries_by_ids */+ Body_get_queue_item_summaries_by_ids: {+ /**+ * Item Ids+ * @description Object containing list of queue item ids to fetch summaries for+ */+ item_ids: number[];+ };/** Body_get_queue_items_by_item_ids */Body_get_queue_items_by_item_ids: {/**@@ -4791,7 +4866,6 @@ export type components = {Body_import_style_presets: {/*** File- * Format: binary* @description The file to import*/file: Blob;@@ -4849,7 +4923,6 @@ export type components = {Body_set_workflow_thumbnail: {/*** Image- * Format: binary* @description The image file to upload*/image: Blob;@@ -4872,10 +4945,7 @@ export type components = {};/** Body_update_model_image */Body_update_model_image: {- /**- * Image- * Format: binary- */+ /** Image */image: Blob;};/** Body_update_style_preset */@@ -4906,10 +4976,7 @@ export type components = {};/** Body_upload_image */Body_upload_image: {- /**- * File- * Format: binary- */+ /** File */file: Blob;/*** Resize To@@ -4925,10 +4992,7 @@ export type components = {};/** Body_upload_video */Body_upload_video: {- /**- * File- * Format: binary- */+ /** File */file: Blob;/*** Metadata@@ -13902,9 +13966,38 @@ export type components = {* @enum {string}*/GalleryItemKind: "image" | "video";+ /**+ * GalleryItemNames+ * @description Ordered flat list of gallery item names plus counts for optimistic UI.+ *+ * Names are polymorphic — images and videos are interleaved by `created_at`. The kind of a+ * given name is its file extension (`.mp4` is a video), which is how every consumer already+ * discriminates. Mirrors the shape of the image-only `ImageNamesResult`.+ */+ GalleryItemNames: {+ /**+ * Item Names+ * @description Ordered list of image and video names.+ */+ item_names: string[];+ /**+ * Starred Count+ * @description Number of starred items (when starred_first=True).+ */+ starred_count: number;+ /**+ * Total Count+ * @description Total number of items matching the query.+ */+ total_count: number;+ };/*** GalleryItemNamesResult* @description Ordered list of gallery item references plus counts for optimistic UI.+ *+ * Deprecated in favour of :class:`GalleryItemNames`. Wrapping every name in an object to+ * carry a `kind` discriminator costs ~800ms of model construction on a 200k-item library,+ * for a field callers derive from the filename extension anyway.*/GalleryItemNamesResult: {/**@@ -26151,15 +26244,282 @@ export type components = {*/format: "sdnq_quantized";variant: components["schemas"]["ZImageVariantType"];- /** @default */- repo_variant: components["schemas"]["ModelRepoVariant"];- /**- * Submodels- * @description Loadable submodels in this model- */- submodels: {- [key: string]: components["schemas"]["SubmodelDefinition"];- } | null;+ /** @default */+ repo_variant: components["schemas"]["ModelRepoVariant"];+ /**+ * Submodels+ * @description Loadable submodels in this model+ */+ submodels: {+ [key: string]: components["schemas"]["SubmodelDefinition"];+ } | null;+ };+ /**+ * Main_SDNQ_FLUX_Config+ * @description Model config for SDNQ-quantized FLUX transformer models.+ */+ Main_SDNQ_FLUX_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;+ /**+ * Type+ * @default main+ * @constant+ */+ type: "main";+ /**+ * Trigger Phrases+ * @description Set of trigger phrases for this model+ */+ trigger_phrases: string[] | null;+ /** @description Default settings for this model */+ default_settings: components["schemas"]["MainModelDefaultSettings"] | null;+ /**+ * Config Path+ * @description Path to the config for this model, if any.+ */+ config_path: string | null;+ /**+ * Base+ * @default flux+ * @constant+ */+ base: "flux";+ /**+ * Format+ * @default sdnq_quantized+ * @constant+ */+ format: "sdnq_quantized";+ variant: components["schemas"]["FluxVariantType"];+ };+ /**+ * Main_SDNQ_Flux2_Config+ * @description Model config for SDNQ-quantized FLUX.2 transformer models (e.g. Klein 4B / 9B).+ */+ Main_SDNQ_Flux2_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;+ /**+ * Type+ * @default main+ * @constant+ */+ type: "main";+ /**+ * Trigger Phrases+ * @description Set of trigger phrases for this model+ */+ trigger_phrases: string[] | null;+ /** @description Default settings for this model */+ default_settings: components["schemas"]["MainModelDefaultSettings"] | null;+ /**+ * Config Path+ * @description Path to the config for this model, if any.+ */+ config_path: string | null;+ /**+ * Base+ * @default flux2+ * @constant+ */+ base: "flux2";+ /**+ * Format+ * @default sdnq_quantized+ * @constant+ */+ format: "sdnq_quantized";+ variant: components["schemas"]["Flux2VariantType"];+ };+ /**+ * Main_SDNQ_ZImage_Config+ * @description Model config for SDNQ-quantized Z-Image transformer models.+ */+ Main_SDNQ_ZImage_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;+ /**+ * Type+ * @default main+ * @constant+ */+ type: "main";+ /**+ * Trigger Phrases+ * @description Set of trigger phrases for this model+ */+ trigger_phrases: string[] | null;+ /** @description Default settings for this model */+ default_settings: components["schemas"]["MainModelDefaultSettings"] | null;+ /**+ * Config Path+ * @description Path to the config for this model, if any.+ */+ config_path: string | null;+ /**+ * Base+ * @default z-image+ * @constant+ */+ base: "z-image";+ /**+ * Format+ * @default sdnq_quantized+ * @constant+ */+ format: "sdnq_quantized";+ variant: components["schemas"]["ZImageVariantType"];};/*** Combine Masks@@ -30926,6 +31286,94 @@ export type components = {/** @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: "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_SDNQ_Folder_Config* @description Configuration for folder-based SDNQ-quantized Qwen3 Encoder models.@@ -34363,6 +34811,83 @@ export type components = {/** @description The workflow associated with this queue item */workflow?: components["schemas"]["WorkflowWithoutID"] | null;};+ /**+ * SessionQueueItemSummary+ * @description Queue item fields needed to render the queue list.+ */+ SessionQueueItemSummary: {+ /**+ * Item Id+ * @description The identifier of the session queue item+ */+ item_id: number;+ /**+ * Created At+ * @description When this queue item was created+ */+ created_at: string;+ /**+ * Status+ * @description The status of this queue item+ * @enum {string}+ */+ status: "pending" | "in_progress" | "waiting" | "completed" | "failed" | "canceled";+ /**+ * Device+ * @description The device that processed this queue item, e.g. 'cuda:1'+ */+ device?: string | null;+ /**+ * Started At+ * @description When this queue item was started+ */+ started_at: string | null;+ /**+ * Completed At+ * @description When this queue item was completed+ */+ completed_at: string | null;+ /**+ * Origin+ * @description The origin of this queue item+ */+ origin: string | null;+ /**+ * Destination+ * @description The destination of this queue item+ */+ destination: string | null;+ /**+ * Batch Id+ * @description The ID of the batch associated with this queue item+ */+ batch_id: string;+ /**+ * User Id+ * @description The ID of the user who created this queue item+ */+ user_id: string;+ /**+ * User Display Name+ * @description The display name of the user who created this queue item+ */+ user_display_name: string | null;+ /**+ * User Email+ * @description The email of the user who created this queue item+ */+ user_email: string | null;+ /**+ * Field Values+ * @description The batch field values used for this queue item+ */+ field_values: components["schemas"]["NodeFieldValue"][] | null;+ /**+ * Parent Item Id+ * @description The ID of the parent queue item, if this is a child item+ */+ parent_item_id: number | null;+ };/** SessionQueueStatus */SessionQueueStatus: {/**@@ -38625,6 +39150,10 @@ export type components = {msg: string;/** Error Type */type: string;+ /** Input */+ input?: unknown;+ /** Context */+ ctx?: Record<string, never>;};/** VideoBoardArg */VideoBoardArg: {@@ -42587,6 +43116,13 @@ export interface operations {};content?: never;};+ /** @description Another operation on this model is already in progress */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description Validation Error */422: {headers: {@@ -42730,6 +43266,13 @@ export interface operations {};content?: never;};+ /** @description Another operation on this model is already in progress */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description Validation Error */422: {headers: {@@ -42891,6 +43434,13 @@ export interface operations {};content?: never;};+ /** @description Another operation on this model is already in progress */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description Validation Error */422: {headers: {@@ -42934,6 +43484,13 @@ export interface operations {};content?: never;};+ /** @description Another operation on this model is already in progress */+ 409: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };/** @description Validation Error */422: {headers: {@@ -45190,6 +45747,52 @@ 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 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?: {@@ -46402,6 +47005,42 @@ export interface operations {};};};+ get_queue_item_summaries_by_ids: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ /** @description The queue id to perform this operation on */+ queue_id: string;+ };+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["Body_get_queue_item_summaries_by_ids"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["SessionQueueItemSummary"][];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };resume: {parameters: {query?: never;diff --git a/invokeai/frontend/web/src/services/api/types.ts b/invokeai/frontend/web/src/services/api/types.tsindex 7c16c84369..e7fed5ebf6 100644--- a/invokeai/frontend/web/src/services/api/types.ts+++ b/invokeai/frontend/web/src/services/api/types.ts@@ -32,10 +32,10 @@ export type GetQueueItemIdsResult =paths['/api/v1/queue/{queue_id}/item_ids']['get']['responses']['200']['content']['application/json'];export type GetQueueItemIdsArgs = NonNullable<paths['/api/v1/queue/{queue_id}/item_ids']['get']['parameters']['query']>;-export type GetQueueItemDTOsByItemIdsResult =- paths['/api/v1/queue/{queue_id}/items_by_ids']['post']['responses']['200']['content']['application/json'];-export type GetQueueItemDTOsByItemIdsArgs =- paths['/api/v1/queue/{queue_id}/items_by_ids']['post']['requestBody']['content']['application/json'];+export type GetQueueItemSummariesByItemIdsResult =+ paths['/api/v1/queue/{queue_id}/item_summaries_by_ids']['post']['responses']['200']['content']['application/json'];+export type GetQueueItemSummariesByItemIdsArgs =+ paths['/api/v1/queue/{queue_id}/item_summaries_by_ids']['post']['requestBody']['content']['application/json'];export type InputFieldJSONSchemaExtra = S['InputFieldJSONSchemaExtra'];export type OutputFieldJSONSchemaExtra = S['OutputFieldJSONSchemaExtra'];@@ -920,6 +920,6 @@ export type OffsetPaginatedResults_GalleryItem_ = S['OffsetPaginatedResults_Gallexport type ListGalleryItemsArgs = NonNullable<paths['/api/v1/gallery/items/']['get']['parameters']['query']>;export type ListGalleryItemsResponse =paths['/api/v1/gallery/items/']['get']['responses']['200']['content']['application/json'];-export type GetGalleryItemNamesArgs = NonNullable<paths['/api/v1/gallery/items/names']['get']['parameters']['query']>;-export type GetGalleryItemNamesResult =- paths['/api/v1/gallery/items/names']['get']['responses']['200']['content']['application/json'];+export type ListGalleryItemNamesArgs = NonNullable<paths['/api/v1/gallery/item_names']['get']['parameters']['query']>;+export type ListGalleryItemNamesResult =+ paths['/api/v1/gallery/item_names']['get']['responses']['200']['content']['application/json'];diff --git a/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx b/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsxindex b4b74e573b..ac01cdff4b 100644--- a/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx+++ b/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx@@ -61,6 +61,18 @@ export const buildOnQueueItemStatusChanged = (dispatch: AppDispatch, coordinator}));+ // The list rows render from summaries, which are a separate cache. The tag invalidation below+ // would refresh them too, but only after a round trip — mirror the write so a row's status+ // flips as immediately as the detail view's does. The summary carries no error or sequence+ // fields, so only the status and timestamps apply.+ dispatch(+ queueApi.util.updateQueryData('getQueueItemSummary', item_id, (draft) => {+ draft.status = status;+ draft.started_at = started_at;+ draft.completed_at = completed_at;+ })+ );+// Optimistically update the listAllQueueItems cache for this destination so the canvas// staging area immediately reflects status changes without waiting for a tag-based refetchif (destination) {diff --git a/pyproject.toml b/pyproject.tomlindex 6b116b9d75..9e5ca1f07e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,10 +68,16 @@ dependencies = [# Core application dependencies, pinned for reproducible builds."fastapi-events",- # FastAPI 0.119.0 breaks OpenAPI schema generation for the AnyInvocation class. It's not clear if this is an Invoke,- # FastAPI or pydantic bug. Probably Invoke's, because we are doing something unusual with AnyInvocation. 0.118.3 is- # the last known-good version.- "fastapi== 0.118.3",+ # The old pin sat at 0.118.3 because 0.119.0 crashed generating our OpenAPI schema. That was a FastAPI bug, not+ # ours (`KeyError: '$ref'` in fastapi/_compat/v2.py, which assumed every field mapping carries a `$ref`), and it+ # is fixed as of 0.124.0 — no change to AnyInvocation was needed.+ #+ # Two later changes did need adapting to, both handled: 0.130 emits `contentMediaType` instead of+ # `format: binary` for file uploads (see the Blob mapping in frontend/web/scripts/typegen.js), and 0.141 keeps+ # included routers as a single node in `app.routes` rather than copying their routes into it (see+ # `_iter_route_contexts` in tests/app/routers/test_model_manager_authorization.py). Keep the minor-version bound:+ # both of those were silent breakages that only surfaced because something happened to assert on them.+ "fastapi>=0.141.1,<0.142","huggingface-hub","networkx","pydantic-settings",diff --git a/tests/app/api/test_gzip_content_types.py b/tests/app/api/test_gzip_content_types.pynew file mode 100644index 0000000000..afd9e4a8a2--- /dev/null+++ b/tests/app/api/test_gzip_content_types.py@@ -0,0 +1,105 @@+"""GZip must skip response types that are already compressed.++Starlette's GZipMiddleware compresses everything except `text/event-stream`. The gallery+serves PNG, WebP and MP4 bytes, which are already deflate-compressed: gzipping a 3 MB PNG+costs ~52ms of event-loop time and returns a *larger* body. With auto-switch on, the UI+fetches the full image after every generated image, so that cost lands repeatedly during a+batch.++These tests pin which content types are compressed, using a standalone app so they exercise+the middleware rather than the whole API surface.+"""++import pytest+from fastapi import FastAPI, Response+from fastapi.testclient import TestClient++from invokeai.app.api_app import ContentTypeAwareGZipMiddleware++# Comfortably above the middleware's minimum_size, and large enough that a missing exclusion+# would be obvious rather than marginal.+BODY = b"x" * 50_000+++def client() -> TestClient:+ app = FastAPI()++ @app.get("/payload")+ def payload(content_type: str) -> Response:+ return Response(content=BODY, media_type=content_type)++ @app.get("/tiny")+ def tiny() -> Response:+ return Response(content=b"small", media_type="application/json")++ app.add_middleware(ContentTypeAwareGZipMiddleware, minimum_size=1000)+ return TestClient(app)+++ "content_type",+ [+ "application/json",+ "text/html; charset=utf-8",+ "text/css",+ "application/javascript",+ "image/svg+xml",+ ],+)+def test_compressible_types_are_compressed(client: TestClient, content_type: str):+ r = client.get("/payload", params={"content_type": content_type}, headers={"Accept-Encoding": "gzip"})++ assert r.status_code == 200+ assert r.headers["content-encoding"] == "gzip"+ # httpx decodes transparently, so this also proves the compressed body round-trips.+ assert r.content == BODY+ assert int(r.headers["content-length"]) < len(BODY)+++ "content_type",+ [+ "image/png",+ "image/webp",+ "image/jpeg",+ "video/mp4",+ "application/zip",+ "application/octet-stream",+ # `text/` prefix matches, but compressing an event stream withholds events until the+ # compressor flushes.+ "text/event-stream",+ ],+)+def test_already_compressed_types_are_passed_through(client: TestClient, content_type: str):+ r = client.get("/payload", params={"content_type": content_type}, headers={"Accept-Encoding": "gzip"})++ assert r.status_code == 200+ assert "content-encoding" not in r.headers, f"{content_type} should not be gzipped"+ assert r.content == BODY+++def test_small_responses_are_left_alone(client: TestClient):+ r = client.get("/tiny", headers={"Accept-Encoding": "gzip"})++ assert r.status_code == 200+ assert "content-encoding" not in r.headers+++def test_the_real_app_uses_the_content_type_aware_middleware():+ """Without this, the tests above would keep passing while the app served gzipped PNGs."""+ from starlette.middleware.gzip import GZipMiddleware++ from invokeai.app.api_app import app++ installed = [m.cls for m in app.user_middleware]+ assert ContentTypeAwareGZipMiddleware in installed+ assert GZipMiddleware not in installed+++def test_clients_without_gzip_support_get_plain_bodies(client: TestClient):+ r = client.get("/payload", params={"content_type": "application/json"}, headers={"Accept-Encoding": "identity"})++ assert r.status_code == 200+ assert "content-encoding" not in r.headers+ assert r.content == BODYdiff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pyindex 5ff2058af1..fe139998a6 100644--- a/tests/app/routers/conftest.py+++ b/tests/app/routers/conftest.py@@ -54,6 +54,7 @@ _PATCHED_API_DEPENDENCIES_MODULES = ("invokeai.app.api.routers.model_relationships","invokeai.app.api.routers.utilities","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 --git a/tests/app/routers/test_custom_nodes.py b/tests/app/routers/test_custom_nodes.pyindex 3fa86c08a5..b2f9442daf 100644--- a/tests/app/routers/test_custom_nodes.py+++ b/tests/app/routers/test_custom_nodes.py@@ -1,8 +1,9 @@"""Tests for the custom nodes router."""-import asyncioimport json+import subprocessimport sys+import threadingfrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -135,7 +136,9 @@ class TestUninstallPackNameValidation:patch("invokeai.app.api.routers.custom_nodes.shutil") as mock_shutil,patch("invokeai.app.api.routers.custom_nodes._remove_workflows_by_ids") as mock_remove_workflows,):- response = asyncio.run(uninstall_custom_node_pack(MagicMock(), pack_name))+ # The route is `def`, not `async def`, so that its synchronous filesystem work+ # runs in the threadpool instead of on the event loop.+ response = uninstall_custom_node_pack(MagicMock(), pack_name)assert response.name == pack_nameassert response.success is False@@ -565,3 +568,87 @@ class TestUninstallReinstallReloadsSubmodules:)finally:_purge_pack_modules(pack_name)+++class TestConcurrentPackMutation:+ """Guards that two concurrent pack operations cannot corrupt each other.++ Install, uninstall and reload were `async def` bodies containing no `await`, which made them+ implicitly mutually exclusive — the event loop had no point at which to switch between two of+ them. Dispatched to the threadpool they interleave for real, and install's failure path is+ destructive: it `rmtree`s `target_dir` on a failed clone, without knowing whether that+ directory is its own or one a concurrent install just finished writing.+ """++ # How long the losing install waits for the winner before giving up. Only reached when the+ # two installs are correctly serialized — then nobody ever sets the event.+ RACER_CLONE_WAIT = 1.0+ SOURCE = "https://github.com/example/my-pack.git"++ def test_failed_install_does_not_delete_a_concurrent_install(self, tmp_path: Path) -> None:+ from types import SimpleNamespace++ from invokeai.app.api.routers.custom_nodes import InstallNodePackRequest, install_custom_node_pack++ racer_past_exists_check = threading.Event()+ winner_installed = threading.Event()+ clone_calls: list[list[str]] = []+ calls_lock = threading.Lock()++ def fake_clone(cmd, **kwargs): # type: ignore[no-untyped-def]+ target = Path(cmd[3])+ with calls_lock:+ is_racer = not clone_calls+ clone_calls.append(cmd)++ if is_racer:+ # Reaching here means the exists-check has already passed. Fail only after the+ # other install has written its files — that ordering is what turns this+ # request's cleanup into a deletion of somebody else's pack.+ racer_past_exists_check.set()+ winner_installed.wait(timeout=TestConcurrentPackMutation.RACER_CLONE_WAIT)+ return subprocess.CompletedProcess(cmd, 128, "", "fatal: clone failed")++ target.mkdir(parents=True, exist_ok=True)+ (target / "__init__.py").write_text("")+ winner_installed.set()+ return subprocess.CompletedProcess(cmd, 0, "", "")++ responses: list[object] = []+ responses_lock = threading.Lock()++ def attempt() -> None:+ response = install_custom_node_pack(MagicMock(), InstallNodePackRequest(source=self.SOURCE))+ with responses_lock:+ responses.append(response)++ with (+ patch("invokeai.app.api.routers.custom_nodes._get_custom_nodes_path", return_value=tmp_path),+ # A stand-in module rather than patching `subprocess.run` itself: patching the real+ # module would leak into the rest of the suite, and the router's `except+ # subprocess.TimeoutExpired` needs a real exception class to catch.+ patch(+ "invokeai.app.api.routers.custom_nodes.subprocess",+ SimpleNamespace(run=fake_clone, TimeoutExpired=subprocess.TimeoutExpired),+ ),+ patch("invokeai.app.api.routers.custom_nodes._load_node_pack"),+ patch("invokeai.app.api.routers.custom_nodes.ApiDependencies"),+ ):+ racer = threading.Thread(target=attempt)+ racer.start()+ # Start the second install only once the first is past the exists-check, so the+ # interleaving under test is reached deterministically rather than by luck.+ assert racer_past_exists_check.wait(timeout=10)++ winner = threading.Thread(target=attempt)+ winner.start()++ for thread in (racer, winner):+ thread.join(timeout=30)+ assert not thread.is_alive()++ pack_dir = tmp_path / "my-pack"+ assert (pack_dir / "__init__.py").exists(), (+ "The successful install's pack directory was deleted by the failed install's cleanup."+ )+ assert sum(1 for response in responses if response.success) == 1 # type: ignore[attr-defined]diff --git a/tests/app/routers/test_event_loop_blocking.py b/tests/app/routers/test_event_loop_blocking.pynew file mode 100644index 0000000000..a50fde4a5e--- /dev/null+++ b/tests/app/routers/test_event_loop_blocking.py@@ -0,0 +1,137 @@+"""Guards that slow gallery queries do not stall the whole server.++The gallery list/name routes run synchronous SQLite work. If such a route is declared+`async def`, that work executes *on the event loop*, so for its whole duration the process+serves nothing else - no other HTTP request, no socket.io progress event. On a large+library a single search can take minutes, which users experience as the backend being+dead rather than as a slow search.++Declaring these routes `def` hands them to Starlette's threadpool instead, leaving the+loop free. These tests pin that property down: the slowness is simulated with a+synchronous sleep in the service layer, so they assert the *dispatch mechanism* rather+than any particular query's speed, and stay fast and deterministic in CI.+"""++import asyncio+import time+from unittest.mock import MagicMock++import pytest+from httpx import ASGITransport, AsyncClient++from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api_app import app+from invokeai.app.services.gallery.gallery_common import GalleryItem, GalleryItemNames, GalleryItemNamesResult+from invokeai.app.services.image_records.image_records_common import ImageNamesResult+from invokeai.app.services.session_queue.session_queue_common import SessionQueueItemSummary+from invokeai.app.services.shared.pagination import OffsetPaginatedResults++# Long enough that a blocked event loop is unmistakable, short enough to keep the suite fast.+BLOCKING_SECONDS = 1.0++# A trivial route with no auth dependency and no database access. If the loop is free, this+# answers in single-digit milliseconds no matter what else the server is doing.+PROBE_ROUTE = "/api/v1/app/version"+++def anyio_backend() -> str:+ return "asyncio"+++def blocking_invoker(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ """Point every router at services whose gallery/image reads block for BLOCKING_SECONDS.++ Patching the attribute on the class itself covers all routers at once - they share the+ single `ApiDependencies` object rather than importing their own copy.+ """+ invoker = MagicMock()+ # A bare MagicMock attribute is truthy, which would put the auth dependencies into+ # multiuser mode and answer every request with 401 before the route is ever reached.+ invoker.services.configuration.multiuser = False++ def slow_list_item_names(**_: object) -> GalleryItemNamesResult:+ time.sleep(BLOCKING_SECONDS)+ return GalleryItemNamesResult(items=[], starred_count=0, total_count=0)++ def slow_get_image_names(**_: object) -> ImageNamesResult:+ time.sleep(BLOCKING_SECONDS)+ return ImageNamesResult(image_names=[], starred_count=0, total_count=0)++ def slow_list_items(**_: object) -> OffsetPaginatedResults[GalleryItem]:+ time.sleep(BLOCKING_SECONDS)+ return OffsetPaginatedResults[GalleryItem](limit=10, offset=0, total=0, items=[])++ def slow_get_item_names(**_: object) -> GalleryItemNames:+ time.sleep(BLOCKING_SECONDS)+ return GalleryItemNames(item_names=[], starred_count=0, total_count=0)++ def slow_queue_item_summaries(**_: object) -> list[SessionQueueItemSummary]:+ time.sleep(BLOCKING_SECONDS)+ return []++ invoker.services.gallery.list_item_names.side_effect = slow_list_item_names+ invoker.services.gallery.get_item_names.side_effect = slow_get_item_names+ invoker.services.gallery.list_items.side_effect = slow_list_items+ invoker.services.images.get_image_names.side_effect = slow_get_image_names+ invoker.services.session_queue.get_queue_item_summaries_by_ids.side_effect = slow_queue_item_summaries++ monkeypatch.setattr(ApiDependencies, "invoker", invoker, raising=False)+ return invoker+++async def _probe_latency_while_busy(+ client: AsyncClient, slow_route: str, params: dict, json_body: dict | None = None+) -> tuple[float, asyncio.Task]:+ """Start `slow_route`, then time a probe request issued while it is still running.++ The clock starts before yielding to the slow request, so a blocked loop shows up as+ probe latency even though the probe itself never got a chance to be dispatched.+ """+ started = time.perf_counter()+ if json_body is None:+ slow_request = asyncio.create_task(client.get(slow_route, params=params))+ else:+ slow_request = asyncio.create_task(client.post(slow_route, params=params, json=json_body))+ # Hand control to the slow request so it reaches its route handler before we probe.+ for _ in range(10):+ await asyncio.sleep(0)++ response = await client.get(PROBE_ROUTE)+ elapsed = time.perf_counter() - started++ assert response.status_code == 200+ return elapsed, slow_request+++ "slow_route,params,json_body",+ [+ ("/api/v1/gallery/items/names", {}, None),+ ("/api/v1/gallery/items/names", {"search_term": "anything"}, None),+ ("/api/v1/gallery/item_names", {}, None),+ ("/api/v1/gallery/items/", {}, None),+ ("/api/v1/images/names", {}, None),+ ("/api/v1/queue/default/item_summaries_by_ids", {}, {"item_ids": [1, 2, 3]}),+ ],+)+async def test_slow_gallery_read_leaves_the_event_loop_free(+ blocking_invoker: MagicMock, slow_route: str, params: dict, json_body: dict | None+) -> None:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as client:+ elapsed, slow_request = await _probe_latency_while_busy(client, slow_route, params, json_body)++ assert elapsed < BLOCKING_SECONDS / 2, (+ f"{PROBE_ROUTE} took {elapsed:.2f}s while {slow_route} was running. The slow route is "+ f"executing its blocking database work on the event loop, so the server answers "+ f"nothing else until it finishes. Declare the route `def` instead of `async def`."+ )+ assert not slow_request.done(), (+ "The slow request finished before the probe was even dispatched, so nothing was "+ "measured concurrently - the event loop was blocked for its full duration."+ )++ await slow_requestdiff --git a/tests/app/routers/test_gallery_item_names.py b/tests/app/routers/test_gallery_item_names.pynew file mode 100644index 0000000000..0dec1103b2--- /dev/null+++ b/tests/app/routers/test_gallery_item_names.py@@ -0,0 +1,162 @@+"""Router-level tests for GET /api/v1/gallery/item_names.++This endpoint replaces two deprecated ones — `/gallery/items/names` and+`/virtual_boards/by_date/{date}/item_names` — with a flat name list. The deprecated shape+wrapped every name in an object carrying a `kind` discriminator, which cost one model per row+(~800ms on a 200k-item library) for a value callers derive from the file extension.++What matters here is that the replacement is faithful: same order, same filtering, same+per-user isolation, and videos still present. Where possible that is asserted *against* the+deprecated endpoint rather than against hardcoded expectations, so the two cannot drift while+both are still served.+"""++from typing import Any++from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin+from invokeai.app.services.invoker import Invoker++ITEM_NAMES_URL = "/api/v1/gallery/item_names"+DEPRECATED_URL = "/api/v1/gallery/items/names"+++def _save_image(mock_invoker: Invoker, image_name: str, user_id: str) -> None:+ mock_invoker.services.image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=10,+ height=10,+ has_workflow=False,+ user_id=user_id,+ )+++def _save_video(mock_invoker: Invoker, video_name: str, user_id: str) -> None:+ mock_invoker.services.video_records.save(+ video_name=video_name,+ video_origin=ResourceOrigin.INTERNAL,+ video_category=ImageCategory.GENERAL,+ width=10,+ height=10,+ duration=1.0,+ fps=8.0,+ has_workflow=False,+ is_intermediate=False,+ user_id=user_id,+ )+++def test_requires_auth_in_multiuser_mode(enable_multiuser: Any, client: TestClient):+ r = client.get(ITEM_NAMES_URL)+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_returns_flat_names_including_videos(client: TestClient, user1_token: str, mock_invoker: Invoker):+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ _save_image(mock_invoker, "img-a.png", user1.user_id)+ _save_video(mock_invoker, "vid-a.mp4", user1.user_id)++ r = client.get(ITEM_NAMES_URL, headers={"Authorization": f"Bearer {user1_token}"})+ assert r.status_code == status.HTTP_200_OK+ body = r.json()++ assert sorted(body["item_names"]) == ["img-a.png", "vid-a.mp4"]+ assert body["total_count"] == 2+ # The names are plain strings — no per-item object wrapper.+ assert all(isinstance(name, str) for name in body["item_names"])+++def test_matches_the_deprecated_endpoint_order(client: TestClient, user1_token: str, mock_invoker: Invoker):+ """The replacement must not reorder anything, or virtualized selection silently breaks."""+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ for i in range(5):+ _save_image(mock_invoker, f"img-{i}.png", user1.user_id)+ _save_video(mock_invoker, "vid-mid.mp4", user1.user_id)++ headers = {"Authorization": f"Bearer {user1_token}"}+ new = client.get(ITEM_NAMES_URL, headers=headers)+ old = client.get(DEPRECATED_URL, headers=headers)+ assert new.status_code == status.HTTP_200_OK+ assert old.status_code == status.HTTP_200_OK++ assert new.json()["item_names"] == [item["name"] for item in old.json()["items"]]+ assert new.json()["total_count"] == old.json()["total_count"]+ assert new.json()["starred_count"] == old.json()["starred_count"]+++def test_created_date_matches_the_deprecated_virtual_board_endpoint(+ client: TestClient, user1_token: str, mock_invoker: Invoker+):+ """`created_date` is the replacement for the by-date virtual-board route."""+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ _save_image(mock_invoker, "dated-img.png", user1.user_id)+ _save_video(mock_invoker, "dated-vid.mp4", user1.user_id)++ headers = {"Authorization": f"Bearer {user1_token}"}+ # Read the date the records actually landed on rather than assuming today's date, so the+ # test cannot fail when it runs across a midnight boundary.+ dates = client.get("/api/v1/virtual_boards/by_date", headers=headers).json()+ assert len(dates) == 1+ date = dates[0]["date"]++ new = client.get(ITEM_NAMES_URL, params={"created_date": date, "is_intermediate": "false"}, headers=headers)+ old = client.get(f"/api/v1/virtual_boards/by_date/{date}/item_names", headers=headers)+ assert new.status_code == status.HTTP_200_OK+ assert old.status_code == status.HTTP_200_OK++ assert new.json()["item_names"] == [item["name"] for item in old.json()["items"]]+ assert "dated-vid.mp4" in new.json()["item_names"]+++def test_created_date_excludes_other_dates(client: TestClient, user1_token: str, mock_invoker: Invoker):+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ _save_image(mock_invoker, "dated-img.png", user1.user_id)++ r = client.get(+ ITEM_NAMES_URL,+ params={"created_date": "1999-01-01", "is_intermediate": "false"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ assert r.json()["item_names"] == []+ assert r.json()["total_count"] == 0+++def test_non_admin_sees_only_own_items(client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker):+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ _save_image(mock_invoker, "u1-only.png", user1.user_id)+ _save_image(mock_invoker, "u2-only.png", user2.user_id)++ r = client.get(ITEM_NAMES_URL, headers={"Authorization": f"Bearer {user1_token}"})+ assert r.status_code == status.HTTP_200_OK+ assert r.json()["item_names"] == ["u1-only.png"]+++def test_marked_deprecated_in_the_openapi_schema(client: TestClient):+ """External integrations rely on the old routes, so they stay served — but signposted."""+ schema = client.get("/openapi.json").json()++ assert schema["paths"][ITEM_NAMES_URL]["get"].get("deprecated") is not True+ for path in (+ DEPRECATED_URL,+ "/api/v1/images/names",+ "/api/v1/videos/names",+ "/api/v1/virtual_boards/by_date/{date}/image_names",+ "/api/v1/virtual_boards/by_date/{date}/item_names",+ ):+ assert schema["paths"][path]["get"]["deprecated"] is True, f"{path} should be marked deprecated"diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.pyindex 0b03a6a194..8fa0c6645d 100644--- a/tests/app/routers/test_model_manager.py+++ b/tests/app/routers/test_model_manager.py@@ -280,3 +280,359 @@ def test_get_stats_returns_null_when_no_stats(monkeypatch: Any, client: TestClieassert response.status_code == 200assert response.json() is None+++async def test_update_model_record_runs_sync_work_off_the_event_loop(monkeypatch: Any) -> None:+ """The async cache-invalidation path must not strand DB work on the event loop."""+ import threading+ from types import SimpleNamespace+ from unittest.mock import MagicMock++ import invokeai.app.api.routers.model_manager as model_manager_router++ event_loop_thread = threading.get_ident()+ service_threads: list[int] = []+ previous = SimpleNamespace(+ cpu_only=False,+ default_settings=SimpleNamespace(fp8_storage=False, cpu_only=False),+ )+ updated = SimpleNamespace(+ cpu_only=False,+ default_settings=SimpleNamespace(fp8_storage=False, cpu_only=False),+ )++ class Store:+ def get_model(self, key: str) -> Any:+ service_threads.append(threading.get_ident())+ return previous++ def update_model(self, key: str, changes: Any, allow_class_change: bool) -> Any:+ service_threads.append(threading.get_ident())+ return updated++ services = SimpleNamespace(+ logger=MagicMock(),+ model_manager=SimpleNamespace(store=Store(), load=SimpleNamespace(ram_caches={})),+ )+ invoker = DummyInvoker(services)+ monkeypatch.setattr(model_manager_router, "ApiDependencies", MockApiDependencies(invoker))+ monkeypatch.setattr(model_manager_router, "prepare_model_config_for_response", lambda config, _: config)++ result = await model_manager_router.update_model_record(+ key="model-key",+ changes=MagicMock(),+ current_admin=MagicMock(),+ )++ assert result is updated+ assert service_threads+ assert all(thread_id != event_loop_thread for thread_id in service_threads)+++def test_convert_model_rejects_a_second_conversion_while_one_is_running() -> None:+ """Conversions are serialized, and the loser is told so instead of being made to wait.++ Two conversions in flight means two models resident at once, which nothing bounds, and for+ the same key the second reads a record the first is midway through replacing. As `async def`+ handlers with no `await` they could not overlap; in the threadpool they can.+ """+ from unittest.mock import MagicMock++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import _MODEL_CONVERSION_LOCK, convert_model++ assert _MODEL_CONVERSION_LOCK.acquire(blocking=False), "lock leaked by an earlier test"+ try:+ with pytest.raises(HTTPException) as exc_info:+ # Never reaches the model store: the guard is the first thing the handler does.+ convert_model(MagicMock(), key="some-key")+ finally:+ _MODEL_CONVERSION_LOCK.release()++ assert exc_info.value.status_code == 409+ assert "already in progress" in exc_info.value.detail+++def test_convert_model_releases_the_lock_when_the_conversion_fails() -> None:+ """A failed conversion must not wedge the endpoint for the rest of the process's life."""+ from unittest.mock import MagicMock, patch++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import _MODEL_CONVERSION_LOCK, convert_model++ with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=RuntimeError("boom")):+ with pytest.raises(RuntimeError):+ convert_model(MagicMock(), key="some-key")++ assert _MODEL_CONVERSION_LOCK.acquire(blocking=False), "the lock was not released on failure"+ _MODEL_CONVERSION_LOCK.release()++ # And the endpoint still works afterwards - the next caller gets past the guard.+ with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=HTTPException(424, "not found")):+ with pytest.raises(HTTPException) as exc_info:+ convert_model(MagicMock(), key="some-key")+ assert exc_info.value.status_code == 424+++def test_delete_is_refused_while_the_same_model_is_being_converted() -> None:+ """A delete landing mid-conversion must not pull the source out from under it.++ Conversion is a read-modify-replace spanning many service calls: it loads the model, writes a+ diffusers copy, installs that copy, then deletes the original. As `async def` bodies with no+ `await` neither route could interleave with the other; in the threadpool they can. A delete+ slipping into the middle removes the record the conversion is still working from, the+ conversion's own final delete then fails, and the copy it already installed survives — so the+ admin is answered 204 and the model reappears under a new key.+ """+ import threading+ from unittest.mock import MagicMock, patch++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import convert_model, delete_model++ conversion_running = threading.Event()+ release_conversion = threading.Event()+ installer = MagicMock()++ def blocking_conversion(key: str, user_id: str) -> object:+ conversion_running.set()+ assert release_conversion.wait(timeout=30)+ return MagicMock()++ with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:+ deps.invoker.services.model_manager.install = installer+ with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):+ conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": "model-key"})+ conversion.start()+ try:+ assert conversion_running.wait(timeout=30)++ with pytest.raises(HTTPException) as exc_info:+ delete_model(MagicMock(), key="model-key")++ assert exc_info.value.status_code == 409+ # The refusal has to happen before the installer is touched, not after.+ installer.delete.assert_not_called()++ # A different model is untouched by the claim.+ delete_model(MagicMock(), key="other-key")+ installer.delete.assert_called_once_with("other-key")+ finally:+ release_conversion.set()+ conversion.join(timeout=30)+ assert not conversion.is_alive()++ # Once the conversion is done the key is free again.+ delete_model(MagicMock(), key="model-key")+ assert installer.delete.call_args_list[-1].args == ("model-key",)+++def test_bulk_delete_reports_a_busy_key_instead_of_racing_it() -> None:+ """Bulk deletion claims each key separately, so one busy model does not stall or corrupt the rest."""+ import threading+ from unittest.mock import MagicMock, patch++ from invokeai.app.api.routers.model_manager import BulkDeleteModelsRequest, bulk_delete_models, convert_model++ conversion_running = threading.Event()+ release_conversion = threading.Event()+ installer = MagicMock()++ def blocking_conversion(key: str, user_id: str) -> object:+ conversion_running.set()+ assert release_conversion.wait(timeout=30)+ return MagicMock()++ with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:+ deps.invoker.services.model_manager.install = installer+ with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):+ conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": "busy-key"})+ conversion.start()+ try:+ assert conversion_running.wait(timeout=30)++ response = bulk_delete_models(+ MagicMock(), request=BulkDeleteModelsRequest(keys=["free-key", "busy-key"])+ )+ finally:+ release_conversion.set()+ conversion.join(timeout=30)+ assert not conversion.is_alive()++ assert response.deleted == ["free-key"]+ assert [entry["key"] for entry in response.failed] == ["busy-key"]+ assert "already in progress" in response.failed[0]["error"]+ installer.delete.assert_called_once_with("free-key")+++def conversion_in_flight():+ """Hold a conversion of `busy-key` at a barrier for the duration of the test.++ Yields the mocked installer/store/model_images so a test can assert what the racing request+ did or did not reach.+ """+ import threading+ from contextlib import contextmanager+ from unittest.mock import MagicMock, patch++ from invokeai.app.api.routers.model_manager import convert_model++ @contextmanager+ def _run(key: str = "busy-key"):+ running = threading.Event()+ release = threading.Event()++ def blocking_conversion(key: str, user_id: str) -> object:+ running.set()+ assert release.wait(timeout=30)+ return MagicMock()++ with patch("invokeai.app.api.routers.model_manager.ApiDependencies") as deps:+ with patch("invokeai.app.api.routers.model_manager._convert_model", side_effect=blocking_conversion):+ conversion = threading.Thread(target=convert_model, args=(MagicMock(),), kwargs={"key": key})+ conversion.start()+ try:+ assert running.wait(timeout=30)+ yield deps+ finally:+ release.set()+ conversion.join(timeout=30)+ assert not conversion.is_alive()++ return _run+++def test_reidentify_is_refused_while_the_same_model_is_being_converted(conversion_in_flight) -> None:+ """Reidentification rewrites the record a conversion is about to replace from its own snapshot."""+ from unittest.mock import MagicMock++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import reidentify_model++ with conversion_in_flight() as deps:+ with pytest.raises(HTTPException) as exc_info:+ reidentify_model(key="busy-key", current_admin=MagicMock())++ assert exc_info.value.status_code == 409+ deps.invoker.services.model_manager.store.replace_model.assert_not_called()+++async def test_update_model_record_is_refused_while_the_same_model_is_being_converted(+ conversion_in_flight,+) -> None:+ """An edit accepted mid-conversion would be reported as saved and then dropped.++ The conversion writes the name, description, hash and source it read *before* it started into+ the replacement record, so anything written in between never reaches the new key.+ """+ from unittest.mock import MagicMock++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import update_model_record+ from invokeai.app.services.model_records import ModelRecordChanges++ with conversion_in_flight() as deps:+ with pytest.raises(HTTPException) as exc_info:+ await update_model_record(+ key="busy-key", changes=ModelRecordChanges(name="renamed"), current_admin=MagicMock()+ )++ assert exc_info.value.status_code == 409+ deps.invoker.services.model_manager.store.update_model.assert_not_called()+++def test_model_image_writes_are_refused_while_the_same_model_is_being_converted(conversion_in_flight) -> None:+ """A conversion moves the image to the replacement's key, so writes in between are lost."""+ from unittest.mock import MagicMock++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers.model_manager import delete_model_image++ with conversion_in_flight() as deps:+ with pytest.raises(HTTPException) as exc_info:+ delete_model_image(MagicMock(), key="busy-key")++ assert exc_info.value.status_code == 409+ deps.invoker.services.model_images.delete.assert_not_called()+++async def test_model_image_upload_claims_before_read() -> None:+ from unittest.mock import MagicMock, patch++ from invokeai.app.api.routers import model_manager++ image = MagicMock()+ image.content_type = "image/png"++ async def read() -> bytes:+ assert "upload-key" in model_manager._CLAIMED_MODEL_KEYS+ return b"image"++ image.read = read++ with patch.object(model_manager, "ApiDependencies") as deps:+ deps.invoker.services.logger = MagicMock()+ deps.invoker.services.model_images = MagicMock()+ with patch.object(model_manager.Image, "open", return_value=MagicMock()):+ await model_manager.update_model_image("upload-key", image, MagicMock())+++def test_converted_model_key_is_claimed_after_install() -> None:+ from pathlib import Path+ from unittest.mock import MagicMock, patch++ from starlette.exceptions import HTTPException++ from invokeai.app.api.routers import model_manager+ from invokeai.app.api.routers.model_manager import delete_model++ installer = MagicMock()+ installer.install_path.return_value = "replacement-key"+ install_config = MagicMock()++ with patch.object(model_manager, "ApiDependencies") as deps:+ deps.invoker.services.logger = MagicMock()+ deps.invoker.services.model_manager.install = installer+ with model_manager._install_and_claim_model(installer, Path("/tmp/converted"), install_config) as new_key:+ assert new_key == "replacement-key"+ with pytest.raises(HTTPException) as exc_info:+ delete_model(MagicMock(), key="replacement-key")++ assert exc_info.value.status_code == 409+ installer.delete.assert_not_called()+++def test_model_mutations_document_claim_conflicts() -> None:+ from invokeai.app.api.routers.model_manager import model_manager_router++ routes = {route.operation_id: route for route in model_manager_router.routes if route.operation_id}++ for operation_id in ("reidentify_model", "update_model_image", "delete_model", "delete_model_image"):+ assert 409 in routes[operation_id].responses+++def test_bulk_reidentify_reports_a_busy_key_instead_of_racing_it(conversion_in_flight) -> None:+ from unittest.mock import MagicMock, patch++ from invokeai.app.api.routers.model_manager import BulkReidentifyModelsRequest, bulk_reidentify_models++ with conversion_in_flight():+ with patch("invokeai.app.api.routers.model_manager._reidentify_model") as reidentify:+ response = bulk_reidentify_models(+ MagicMock(), request=BulkReidentifyModelsRequest(keys=["free-key", "busy-key"])+ )++ assert response.succeeded == ["free-key"]+ assert [entry["key"] for entry in response.failed] == ["busy-key"]+ assert "already in progress" in response.failed[0]["error"]+ reidentify.assert_called_once_with("free-key")diff --git a/tests/app/routers/test_model_manager_authorization.py b/tests/app/routers/test_model_manager_authorization.pyindex ba54a3a50d..e881d320b6 100644--- a/tests/app/routers/test_model_manager_authorization.py+++ b/tests/app/routers/test_model_manager_authorization.py@@ -175,13 +175,40 @@ PUBLIC_ROUTES = {}-def _routes_without_auth() -> set[tuple[str, str]]:- """Every (method, path) in the app whose dependency tree contains no auth dependency."""+# A floor, not an exact count: routes come and go, but a *collapse* means the traversal below stopped+# seeing the app rather than that the app shrank. Without this the guard fails open — see+# `_iter_api_route_contexts`.+MIN_EXPECTED_API_ROUTES = 150+++def _iter_api_route_contexts() -> list[Any]:+ """Every API route in the app, with its full external path.++ Walking `app.routes` directly is not enough: since FastAPI 0.141 an included router stays a single+ node in `app.routes` instead of having its routes copied into it, so `isinstance(route, APIRoute)`+ matched 2 of ~197 routes and this guard passed while inspecting almost nothing. `iter_route_contexts`+ is the traversal FastAPI's own OpenAPI generation uses, so by construction it yields exactly the+ routes the app exposes. The context's `path` is the full external path — `route.path` is only the+ portion below the router prefix.+ """+ from fastapi import routingfrom fastapi.routing import APIRoute- from invokeai.app.api import auth_dependenciesfrom invokeai.app.api_app import app+ contexts = [ctx for ctx in routing.iter_route_contexts(app.routes) if isinstance(ctx.route, APIRoute)]+ assert len(contexts) >= MIN_EXPECTED_API_ROUTES, (+ f"Only {len(contexts)} API routes discovered, expected at least {MIN_EXPECTED_API_ROUTES}. FastAPI has "+ "likely changed how routes are stored again, which makes the auth guard below inspect almost nothing "+ "and pass. Fix the traversal - do not lower this floor."+ )+ return contexts+++def _routes_without_auth() -> set[tuple[str, str]]:+ """Every (method, path) in the app whose dependency tree contains no auth dependency."""+ from invokeai.app.api import auth_dependencies+auth_functions = {auth_dependencies.get_current_user,auth_dependencies.get_current_user_or_default,@@ -194,10 +221,10 @@ def _routes_without_auth() -> set[tuple[str, str]]:return any(has_auth(sub) for sub in dependant.dependencies)return {- (method, route.path)- for route in app.routes- if isinstance(route, APIRoute) and not has_auth(route.dependant)- for method in route.methods+ (method, ctx.path)+ for ctx in _iter_api_route_contexts()+ if not has_auth(ctx.route.dependant)+ for method in ctx.route.methods}diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.pyindex be5d2a61be..56fb469e4c 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -1099,6 +1099,10 @@ class TestSessionQueueAuth:r = client.get("/api/v1/queue/default/item_ids")assert r.status_code == status.HTTP_401_UNAUTHORIZED+ def test_get_queue_item_summaries_by_ids_requires_auth(self, enable_multiuser: Any, client: TestClient):+ r = client.post("/api/v1/queue/default/item_summaries_by_ids", json={"item_ids": [1]})+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+def test_get_current_queue_item_requires_auth(self, enable_multiuser: Any, client: TestClient):r = client.get("/api/v1/queue/default/current")assert r.status_code == status.HTTP_401_UNAUTHORIZEDdiff --git a/tests/app/routers/test_no_blocking_async_routes.py b/tests/app/routers/test_no_blocking_async_routes.pynew file mode 100644index 0000000000..77cf2e56ed--- /dev/null+++ b/tests/app/routers/test_no_blocking_async_routes.py@@ -0,0 +1,111 @@+"""No route handler may be `async def` without awaiting something.++Nearly every service in the backend is synchronous. A route declared `async def` that only+calls those services runs their blocking work *on the event loop*, so for its duration the+process serves no other request and delivers no socket.io event. On a large library that is+seconds per request, which users experience as the application freezing mid-generation.++`tests/app/routers/test_event_loop_blocking.py` proves the effect for a handful of routes.+This test enforces the rule for all of them, because a per-route test cannot cover a route+that does not exist yet — and the failure mode is invisible until someone has a big enough+library to notice.++See docs/contributing/blocking-work-in-api-routes for the rule itself.+"""++import ast+import pathlib++ROUTERS_DIR = pathlib.Path(__file__).parents[3] / "invokeai" / "app" / "api" / "routers"++# Decorators that register a function as a route. `api_route` takes the method as a keyword,+# the rest name it directly.+ROUTE_DECORATORS = {"get", "post", "put", "patch", "delete", "head", "options", "api_route"}++# A floor, not an exact count: routes come and go, but a collapse means this test stopped+# finding the routers rather than that the app shrank.+MIN_EXPECTED_ROUTE_HANDLERS = 150+++def _is_route_handler(node: ast.AsyncFunctionDef | ast.FunctionDef) -> bool:+ for decorator in node.decorator_list:+ target = decorator.func if isinstance(decorator, ast.Call) else decorator+ if isinstance(target, ast.Attribute) and target.attr in ROUTE_DECORATORS:+ return True+ return False+++def _awaits_something(node: ast.AsyncFunctionDef) -> bool:+ """Whether the handler's *own* body awaits.++ A nested closure's `await` says nothing about the handler: the closure is a separate+ coroutine, and the handler that merely defines it still runs its own body to completion on+ the event loop. Counting those awaits would let a handler pass by defining an inner async+ helper it never awaits.+ """+ for child in ast.iter_child_nodes(node):+ if isinstance(child, (ast.Await, ast.AsyncWith, ast.AsyncFor)):+ return True+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):+ continue # a separate scope - its awaits are not this handler's+ if _awaits_something(child): # type: ignore[arg-type]+ return True+ return False+++def test_no_route_handler_is_async_without_awaiting() -> None:+ offenders: list[str] = []+ handlers = 0++ for path in sorted(ROUTERS_DIR.glob("*.py")):+ tree = ast.parse(path.read_text(encoding="utf-8"))+ # Walk the whole module, not just its top level: a handler registered from inside a+ # factory function or an `if` block is still a handler, and "every handler including+ # ones written later" has to mean every handler.+ for node in ast.walk(tree):+ if not isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)) or not _is_route_handler(node):+ continue+ handlers += 1+ if isinstance(node, ast.AsyncFunctionDef) and not _awaits_something(node):+ offenders.append(f"{path.name}:{node.lineno} {node.name}")++ assert handlers >= MIN_EXPECTED_ROUTE_HANDLERS, (+ f"Only {handlers} route handlers found in {ROUTERS_DIR}, expected at least "+ f"{MIN_EXPECTED_ROUTE_HANDLERS}. This test has stopped seeing the routers - fix the discovery, "+ "do not lower this floor."+ )++ assert not offenders, (+ "These route handlers are declared `async def` but never await anything, so their "+ "synchronous work runs on the event loop and stalls the whole server while it runs:\n "+ + "\n ".join(offenders)+ + "\n\nDeclare them `def` - FastAPI will run them in a threadpool. If a handler genuinely "+ "needs to be async, it must await something; blocking calls inside it belong in "+ "`run_in_threadpool`. See docs/contributing/blocking-work-in-api-routes."+ )+++def _parse_handler(source: str) -> ast.AsyncFunctionDef:+ node = ast.parse(source).body[0]+ assert isinstance(node, ast.AsyncFunctionDef)+ return node+++def test_awaits_something_ignores_awaits_in_nested_closures() -> None:+ """A handler that only *defines* an async helper still runs its own body on the loop."""+ handler = _parse_handler(+ "async def handler():\n async def helper():\n await something()\n return blocking_service_call()\n"+ )++ assert not _awaits_something(handler)+++def test_awaits_something_sees_awaits_below_the_top_level_of_the_body() -> None:+ for body in (+ " await service.do()",+ " if cond:\n await service.do()",+ " async with lock:\n pass",+ " async for item in stream:\n pass",+ " try:\n await service.do()\n finally:\n pass",+ ):+ assert _awaits_something(_parse_handler(f"async def handler():\n{body}\n")), bodydiff --git a/tests/app/routers/test_session_queue_item_id_limits.py b/tests/app/routers/test_session_queue_item_id_limits.pynew file mode 100644index 0000000000..b009c8ca57--- /dev/null+++ b/tests/app/routers/test_session_queue_item_id_limits.py@@ -0,0 +1,71 @@+"""Guards the batch bound on the queue summary route.++`item_summaries_by_ids` takes a client-supplied list of ids and the SQLite layer binds one+parameter per id. Unbounded, a client could post tens of thousands of ids: past SQLite's+per-statement variable limit the query raises `OperationalError`, which the route reports as a+generic HTTP 500, and even below that limit it is an invitation to make the server do arbitrary+work per request. The route caps the list so oversized requests are rejected by validation+instead.+"""++from unittest.mock import MagicMock++import pytest+from fastapi.testclient import TestClient++from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers.session_queue import MAX_QUEUE_ITEM_IDS_PER_REQUEST+from invokeai.app.api_app import app++SUMMARIES_ROUTE = "/api/v1/queue/default/item_summaries_by_ids"+FULL_ITEMS_ROUTE = "/api/v1/queue/default/items_by_ids"++# SQLite's bind-parameter limit on builds >= 3.32. One id over it is what turns the unbounded+# version of this route into a 500.+SQLITE_MAX_VARIABLE_NUMBER = 32766+++def mock_queue_invoker(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ invoker = MagicMock()+ # A bare MagicMock attribute is truthy, which would put the auth dependencies into multiuser+ # mode and answer with 401 before the route is reached.+ invoker.services.configuration.multiuser = False+ invoker.services.session_queue.get_queue_item_summaries_by_ids.return_value = []+ monkeypatch.setattr(ApiDependencies, "invoker", invoker, raising=False)+ return invoker+++def test_summaries_by_ids_rejects_oversized_id_lists(mock_queue_invoker: MagicMock) -> None:+ client = TestClient(app)++ response = client.post(SUMMARIES_ROUTE, json={"item_ids": list(range(SQLITE_MAX_VARIABLE_NUMBER + 1))})++ assert response.status_code == 422, (+ f"Expected a controlled rejection, got {response.status_code}. An unbounded id list reaches "+ f"the SQLite layer, which binds one variable per id and raises OperationalError."+ )+ # The request must be turned away by validation, before any database work is attempted.+ mock_queue_invoker.services.session_queue.get_queue_item_summaries_by_ids.assert_not_called()+++def test_summaries_by_ids_accepts_a_full_size_batch(mock_queue_invoker: MagicMock) -> None:+ client = TestClient(app)+ item_ids = list(range(MAX_QUEUE_ITEM_IDS_PER_REQUEST))++ response = client.post(SUMMARIES_ROUTE, json={"item_ids": item_ids})++ assert response.status_code == 200+ mock_queue_invoker.services.session_queue.get_queue_item_summaries_by_ids.assert_called_once_with(+ queue_id="default", item_ids=item_ids+ )+++def test_full_items_by_ids_rejects_oversized_id_lists(mock_queue_invoker: MagicMock) -> None:+ client = TestClient(app)++ response = client.post(FULL_ITEMS_ROUTE, json={"item_ids": list(range(MAX_QUEUE_ITEM_IDS_PER_REQUEST + 1))})++ assert response.status_code == 422+ # Validation must reject the request before graph deserialization starts.+ mock_queue_invoker.services.session_queue.get_queue_item.assert_not_called()diff --git a/tests/app/routers/test_session_queue_sanitization.py b/tests/app/routers/test_session_queue_sanitization.pyindex 9fe1551058..e2b375585e 100644--- a/tests/app/routers/test_session_queue_sanitization.py+++ b/tests/app/routers/test_session_queue_sanitization.py@@ -7,7 +7,11 @@ import pytestfrom invokeai.app.api.routers.session_queue import sanitize_queue_item_for_userfrom invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_outputfrom invokeai.app.invocations.fields import InputField, OutputField-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, GraphExecutionStatefrom invokeai.app.services.shared.invocation_context import InvocationContext@@ -189,3 +193,48 @@ def test_sanitize_system_user_item_for_admin(sample_session_queue_item):assert result.field_values is not Noneassert len(result.field_values) == 1assert len(result.session.graph.nodes) == 1+++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 --git a/tests/app/routers/test_style_presets.py b/tests/app/routers/test_style_presets.pyindex 5712ec2ef4..935e260985 100644--- a/tests/app/routers/test_style_presets.py+++ b/tests/app/routers/test_style_presets.py@@ -134,6 +134,26 @@ def test_import_forbidden_for_regular_user(client: TestClient, user1_token: str)assert r.status_code == status.HTTP_403_FORBIDDEN+def test_import_malformed_json_returns_400(client: TestClient, admin_token: str):+ r = client.post(+ "/api/v1/style_presets/import",+ files={"file": ("presets.json", b"{not-json", "application/json")},+ headers=_auth(admin_token),+ )+ assert r.status_code == status.HTTP_400_BAD_REQUEST+++def test_admin_can_import_csv_without_blocking_parser(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.post(+ "/api/v1/style_presets/import",+ files={"file": ("presets.csv", b"name,prompt,negative_prompt\nImported,p,n\n", "text/csv")},+ headers=_auth(admin_token),+ )+ assert r.status_code == status.HTTP_200_OK+ admin_id = _user_id(mock_invoker, "[email protected]")+ assert any(p.name == "Imported" for p in mock_invoker.services.style_preset_records.get_many(user_id=admin_id))++# ----------------------------- Bug B regression: JSONDecodeError → 400 -----------------------------diff --git a/tests/app/routers/test_videos_multiuser.py b/tests/app/routers/test_videos_multiuser.pyindex 346173039f..c0308c6e19 100644--- a/tests/app/routers/test_videos_multiuser.py+++ b/tests/app/routers/test_videos_multiuser.py@@ -11,7 +11,6 @@ same fixture pattern as test_boards_multiuser. The storage-level user_idfilter is covered separately in tests/app/services/video_records."""-import asyncioimport inspectfrom pathlib import Pathfrom typing import Any@@ -675,12 +674,13 @@ def test_get_video_thumbnail_closes_file_before_route_returns(mock_invoker.services.videos.get_path.return_value = str(thumbnail_path)current_user = MagicMock(is_admin=True)- async def get_thumbnail_after_delete() -> bytes:- response = await get_video_thumbnail(current_user=current_user, video_name="video.mp4")- thumbnail_path.unlink()- return bytes(response.body)+ # The route is `def`, not `async def`, so that its synchronous file read runs in the+ # threadpool instead of on the event loop. Deleting the file straight after it returns is+ # what proves the handle was closed before the response was built.+ response = get_video_thumbnail(current_user=current_user, video_name="video.mp4")+ thumbnail_path.unlink()- assert asyncio.run(get_thumbnail_after_delete()) == b"thumbnail-data"+ assert bytes(response.body) == b"thumbnail-data"@pytest.mark.parametrize(diff --git a/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.pynew file mode 100644index 0000000000..e4bf1c211e--- /dev/null+++ b/tests/app/services/orphaned_models/test_orphaned_models_scratch_dir.py@@ -0,0 +1,76 @@+"""The orphan scan must not report a model that is still being written.++An orphan is defined as model files under the models root with no database record — which is also+an exact description of a conversion in progress. Model conversion builds its diffusers copy on the+models volume (so the finished result can be moved into place rather than copied across a+filesystem boundary), and `DELETE /sync/orphaned` rmtrees whatever the scan reported. Before both+routes ran in the threadpool they could not overlap; now they can, so the scratch directory has to+be invisible to the scan by construction.+"""++from logging import Logger+from pathlib import Path++import pytest++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelsService+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+++def db() -> SqliteDatabase:+ database = SqliteDatabase(db_path=None, logger=Logger("test_orphaned_models"), verbose=False)+ database._conn.execute("CREATE TABLE models (id TEXT PRIMARY KEY, config TEXT NOT NULL);")+ database._conn.commit()+ return database+++def models_path(tmp_path: Path) -> Path:+ path = tmp_path / "models"+ path.mkdir()+ return path+++def _service(models_path: Path, db: SqliteDatabase) -> OrphanedModelsService:+ config = InvokeAIAppConfig()+ config._root = models_path.parent+ assert config.models_path == models_path+ return OrphanedModelsService(config=config, db=db)+++def _write_model_file(directory: Path, name: str = "model.safetensors") -> None:+ directory.mkdir(parents=True, exist_ok=True)+ (directory / name).write_bytes(b"not really a model")+++def test_conversion_scratch_directory_is_not_reported_as_orphaned(models_path: Path, db: SqliteDatabase) -> None:+ # What a conversion looks like on disk while it runs: a TemporaryDirectory under the scratch+ # area, holding the diffusers copy it has written so far.+ _write_model_file(models_path / CONVERSION_SCRATCH_DIRNAME / "tmp8f2b1c" / "sd-v1-5")++ orphans = _service(models_path, db).find_orphaned_models()++ assert orphans == [], (+ "The scan reported a conversion's working directory. `DELETE /sync/orphaned` would delete "+ "it while the conversion is still writing into it."+ )+++def test_a_real_orphan_is_still_reported(models_path: Path, db: SqliteDatabase) -> None:+ """The control: the skip must be targeted, not a scan that has stopped finding anything."""+ _write_model_file(models_path / "some-unregistered-model")++ orphans = _service(models_path, db).find_orphaned_models()++ assert [orphan.path for orphan in orphans] == ["some-unregistered-model"]+++def test_conversion_scratch_directory_cannot_be_deleted(models_path: Path, db: SqliteDatabase) -> None:+ _write_model_file(models_path / CONVERSION_SCRATCH_DIRNAME / "active-conversion" / "sd-v1-5")++ result = _service(models_path, db).delete_orphaned_models([CONVERSION_SCRATCH_DIRNAME])++ assert result[CONVERSION_SCRATCH_DIRNAME].startswith("error:")+ assert (models_path / CONVERSION_SCRATCH_DIRNAME).exists()diff --git a/tests/app/services/session_queue/test_session_queue_status_user_scoping.py b/tests/app/services/session_queue/test_session_queue_status_user_scoping.pyindex c9e2147b0e..1a12b14536 100644--- a/tests/app/services/session_queue/test_session_queue_status_user_scoping.py+++ b/tests/app/services/session_queue/test_session_queue_status_user_scoping.py@@ -15,6 +15,7 @@ a single own-count and (b) hid other users' redacted entries entirely. These tesrestored behavior."""+import sqlite3import uuidimport pytest@@ -143,3 +144,62 @@ def test_get_queue_item_ids_returns_all_users_ids(session_queue: SqliteSessionQuassert set(result.item_ids) == {a_item_id, b_item_id}assert result.total_count == 2+++def test_get_queue_item_summaries_by_ids_returns_only_requested_queue_items_in_order(+ session_queue: SqliteSessionQueue,+) -> None:+ first_id = _insert_queue_item(session_queue, user_id="user-a")+ second_id = _insert_queue_item(session_queue, user_id="user-b")+ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ UPDATE session_queue+ SET origin = ?, destination = ?, device = ?, field_values = ?+ WHERE item_id = ?+ """,+ (+ "canvas",+ "gallery",+ "cuda:1",+ '[{"node_path":"node","field_name":"seed","value":123}]',+ second_id,+ ),+ )++ summaries = session_queue.get_queue_item_summaries_by_ids(+ queue_id="default", item_ids=[second_id, 999999, first_id]+ )++ assert [item.item_id for item in summaries] == [second_id, first_id]+ assert summaries[0].origin == "canvas"+ assert summaries[0].destination == "gallery"+ assert summaries[0].device == "cuda:1"+ assert summaries[0].field_values is not None+ assert summaries[0].field_values[0].field_name == "seed"+ assert summaries[0].field_values[0].value == 123+ assert summaries[0].user_id == "user-b"+ assert summaries[0].created_at is not None+ assert summaries[0].status == "pending"+++def test_get_queue_item_summaries_by_ids_chunks_past_the_sqlite_bind_limit(+ session_queue: SqliteSessionQueue,+) -> None:+ """Every id becomes one bind parameter, so a single IN (...) would raise OperationalError once+ the list outgrows SQLite's per-statement variable limit. The query is chunked instead."""+ real_ids = [_insert_queue_item(session_queue, user_id="user-a") for _ in range(3)]++ # Size the request off the limit this SQLite build actually enforces (999 on builds older than+ # 3.32, 32766 since), so the test stays meaningful wherever it runs.+ with session_queue._db.transaction() as cursor:+ bind_limit = cursor.connection.getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER)++ # Padding ids do not exist, which also covers chunks that match nothing at all.+ padding_ids = list(range(100_000, 100_000 + bind_limit + 10))+ split = len(padding_ids) // 2+ item_ids = [real_ids[0], *padding_ids[:split], real_ids[1], *padding_ids[split:], real_ids[2]]++ summaries = session_queue.get_queue_item_summaries_by_ids(queue_id="default", item_ids=item_ids)++ assert [item.item_id for item in summaries] == real_idsdiff --git a/tests/app/services/users/test_user_service.py b/tests/app/services/users/test_user_service.pyindex 1cdca16b00..60c7887e9f 100644--- a/tests/app/services/users/test_user_service.py+++ b/tests/app/services/users/test_user_service.py@@ -1,10 +1,12 @@"""Tests for user service."""+import threadingfrom logging import Loggerimport pytestfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.services.users import users_defaultfrom invokeai.app.services.users.users_common import UserCreateRequest, UserUpdateRequestfrom invokeai.app.services.users.users_default import USER_LOOKUP_CHUNK_SIZE, UserService@@ -243,16 +245,73 @@ def test_create_admin(user_service: UserService):def test_create_admin_when_exists(user_service: UserService):"""Test creating admin when one already exists."""- user_data = UserCreateRequest(- email="[email protected]",- display_name="Admin User",- password="AdminPassword123",+ user_service.create_admin(+ UserCreateRequest(+ email="[email protected]",+ display_name="Admin User",+ password="AdminPassword123",+ ))- user_service.create_admin(user_data)+ # A *different* email, so this exercises the admin guard rather than the unique-email one.+ with pytest.raises(ValueError, match="Admin user already exists"):+ user_service.create_admin(+ UserCreateRequest(+ email="[email protected]",+ display_name="Second Admin",+ password="AdminPassword123",+ )+ )- with pytest.raises(ValueError, match="already exists"):- user_service.create_admin(user_data)++def test_concurrent_create_admin_creates_exactly_one_admin(user_service: UserService, monkeypatch):+ """Two concurrent `POST /auth/setup` requests must not both create an administrator.++ The route is unauthenticated during the first-run window and runs in the threadpool, so the+ two requests really do interleave. Checking has_admin() in its own transaction before the+ INSERT leaves a window in which both callers see no admin and both create one; the loser then+ holds a persistent admin account instead of getting the intended 400.++ The barrier models that interleaving deterministically: it releases both threads only once+ both have passed every step preceding the write.+ """+ barrier = threading.Barrier(2, timeout=30)+ real_hash_password = users_default.hash_password++ def synchronized_hash_password(password: str) -> str:+ barrier.wait()+ return real_hash_password(password)++ monkeypatch.setattr(users_default, "hash_password", synchronized_hash_password)++ results: dict[int, object] = {}++ def attempt(index: int) -> None:+ try:+ results[index] = user_service.create_admin(+ UserCreateRequest(+ email=f"admin{index}@example.com",+ display_name=f"Admin {index}",+ password="AdminPassword123",+ )+ )+ except ValueError as exc:+ results[index] = exc++ threads = [threading.Thread(target=attempt, args=(index,)) for index in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=30)+ assert not thread.is_alive()++ created = [result for result in results.values() if not isinstance(result, ValueError)]+ rejected = [result for result in results.values() if isinstance(result, ValueError)]++ assert len(created) == 1, f"Both requests created an administrator: {results}"+ assert len(rejected) == 1+ assert "Admin user already exists" in str(rejected[0])+ assert user_service.count_admins() == 1def test_list_users(user_service: UserService):diff --git a/uv.lock b/uv.lockindex a1905f55a7..f9df5f4c1a 100644--- a/uv.lock+++ b/uv.lock@@ -887,16 +887,18 @@ wheels = [[[package]]name = "fastapi"-version = "0.118.3"+version = "0.141.1"source = { registry = "https://pypi.org/simple" }dependencies = [+ { name = "annotated-doc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or sys_platform == 'darwin' or sys_platform == 'win32' or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu')" },{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or sys_platform == 'darwin' or sys_platform == 'win32' or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu')" },{ name = "starlette", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or sys_platform == 'darwin' or sys_platform == 'win32' or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu')" },{ name = "typing-extensions", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or sys_platform == 'darwin' or sys_platform == 'win32' or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu')" },+ { name = "typing-inspection", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or sys_platform == 'darwin' or sys_platform == 'win32' or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-cuda') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cpu' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-rocm') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-cuda' and extra == 'extra-8-invokeai-xpu') or (sys_platform != 'linux' and extra == 'extra-8-invokeai-rocm' and extra == 'extra-8-invokeai-xpu')" },]-sdist = { url = "https://files.pythonhosted.org/packages/44/e0/b2c4c5fed29587f0c0c56cec9b59f2c3ca58fd40e6c96d9a788219662a35/fastapi-0.118.3.tar.gz", hash = "sha256:5bf36d9bb0cd999e1aefcad74985a6d6a1fc3a35423d497f9e1317734633411d", size = 312055, upload-time = "2025-10-10T10:40:18.15Z" }+sdist = { url = "https://files.pythonhosted.org/packages/8a/02/91e3416a8fdd715abb903a952a6bec7cdd8d14eed55d415fc8595524c319/fastapi-0.141.1.tar.gz", hash = "sha256:e8822fc40db1e1858054d7a949a888695bc9bdce70139178e33bd2871a453ca1", size = 425799, upload-time = "2026-07-29T17:18:05.568Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/24/04/2f9e8a965f4214883258a6f716fea324d1b81e97bce6346cfbafffe6b86c/fastapi-0.118.3-py3-none-any.whl", hash = "sha256:8b9673dc083b4b9d3d295d49ba1c0a2abbfb293d34ba210fd9b0a90d5f39981e", size = 97957, upload-time = "2025-10-10T10:40:16.118Z" },+ { url = "https://files.pythonhosted.org/packages/cb/03/10388a42375ee7e4ac9b94eb2c5c569c8b5795e377e701c9ac3ad63de890/fastapi-0.141.1-py3-none-any.whl", hash = "sha256:bfb91aa2d334c61cb35ba9a116fc123b3d3df31640b801cf57a7a78ec3f603b3", size = 131954, upload-time = "2026-07-29T17:18:04.364Z" },][[package]]@@ -1427,7 +1429,7 @@ requires-dist = [{ name = "dynamicprompts" },{ name = "einops" },{ name = "email-validator", specifier = ">=2.0.0" },- { name = "fastapi", specifier = "==0.118.3" },+ { name = "fastapi", specifier = ">=0.141.1,<0.142" },{ name = "fastapi-events" },{ name = "gguf" },{ name = "gprof2dot", marker = "extra == 'dev'" },