Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix: scope socket events and queue UI per user in multiuser mode (#9358)

Lincoln Stein29ccdbba0776
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index fb756ab881..8d282ac0bb 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -472,6 +472,7 @@ async def list_image_dtos(
board_id,
search_term,
current_user.user_id,
+ current_user.is_admin,
)
return image_dtos
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index bdd2e40644..0321a25429 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -1155,7 +1155,7 @@ async def convert_model(
with TemporaryDirectory(dir=ApiDependencies.invoker.services.configuration.models_path) as tmpdir:
convert_path = pathlib.Path(tmpdir) / pathlib.Path(model_config.path).stem
- converted_model = loader.load_model(model_config)
+ converted_model = loader.load_model(model_config, user_id=current_admin.user_id)
# write the converted file to the convert path
raw_model = converted_model.model
assert hasattr(raw_model, "save_pretrained")
diff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.py
index 89d2f9a739..9850364af2 100644
--- a/invokeai/app/api/routers/session_queue.py
+++ b/invokeai/app/api/routers/session_queue.py
@@ -468,12 +468,14 @@ async def get_queue_status(
current_user: CurrentUserOrDefault,
queue_id: str = Path(description="The queue id to perform this operation on"),
) -> SessionQueueAndProcessorStatus:
- """Gets the status of the session queue. Returns global counts; non-admin users additionally
- get their own pending/in_progress counts (so the UI can show an X/Y badge) and cannot see the
- current item's identifiers unless they own it."""
+ """Gets the status of the session queue. Returns global counts; every user additionally gets
+ their own pending/in_progress counts (so the UI can show an X/Y badge and scope personal UI
+ like the progress bar to the user's own activity). Non-admin users cannot see the current
+ item's identifiers unless they own it."""
try:
- user_id = None if current_user.is_admin else current_user.user_id
- queue = ApiDependencies.invoker.services.session_queue.get_queue_status(queue_id, user_id=user_id)
+ queue = ApiDependencies.invoker.services.session_queue.get_queue_status(
+ queue_id, user_id=current_user.user_id, is_admin=current_user.is_admin
+ )
processor = ApiDependencies.invoker.services.session_processor.get_status()
return SessionQueueAndProcessorStatus(queue=queue, processor=processor)
except Exception as e:
diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.py
index 3ba8fee292..4541aadb62 100644
--- a/invokeai/app/api/routers/utilities.py
+++ b/invokeai/app/api/routers/utilities.py
@@ -103,7 +103,7 @@ def _resolve_model_path(model_config_path: str) -> Path:
return (base_models_path / model_path).resolve()
-def _run_expand_prompt(prompt: str, model_key: str, max_tokens: int, system_prompt: str | None) -> str:
+def _run_expand_prompt(prompt: str, model_key: str, max_tokens: int, system_prompt: str | None, user_id: str) -> str:
"""Run text LLM inference synchronously (called from thread)."""
model_manager = ApiDependencies.invoker.services.model_manager
model_config = model_manager.store.get_model(model_key)
@@ -112,7 +112,7 @@ def _run_expand_prompt(prompt: str, model_key: str, max_tokens: int, system_prom
raise ValueError(f"Model '{model_key}' is not a TextLLM model (got {model_config.type})")
with _model_load_lock:
- loaded_model = model_manager.load.load_model(model_config)
+ loaded_model = model_manager.load.load_model(model_config, user_id=user_id)
with torch.no_grad(), loaded_model.model_on_device() as (_, model):
model_abs_path = _resolve_model_path(model_config.path)
@@ -147,6 +147,7 @@ async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptRe
body.model_key,
body.max_tokens,
body.system_prompt,
+ current_user.user_id,
)
return ExpandPromptResponse(expanded_prompt=expanded)
except UnknownModelException:
@@ -172,7 +173,7 @@ class ImageToPromptResponse(BaseModel):
error: str | None = None
-def _run_image_to_prompt(image_name: str, model_key: str, instruction: str) -> str:
+def _run_image_to_prompt(image_name: str, model_key: str, instruction: str, user_id: str) -> str:
"""Run LLaVA OneVision inference synchronously (called from thread)."""
model_manager = ApiDependencies.invoker.services.model_manager
model_config = model_manager.store.get_model(model_key)
@@ -181,7 +182,7 @@ def _run_image_to_prompt(image_name: str, model_key: str, instruction: str) -> s
raise ValueError(f"Model '{model_key}' is not a LLaVA OneVision model (got {model_config.type})")
with _model_load_lock:
- loaded_model = model_manager.load.load_model(model_config)
+ loaded_model = model_manager.load.load_model(model_config, user_id=user_id)
# Load the image from InvokeAI's image store
image = ApiDependencies.invoker.services.images.get_pil_image(image_name)
@@ -229,6 +230,7 @@ async def image_to_prompt(current_user: CurrentUserOrDefault, body: ImageToPromp
body.image_name,
body.model_key,
body.instruction,
+ current_user.user_id,
)
return ImageToPromptResponse(prompt=prompt)
except UnknownModelException:
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py
index bdaf641c1c..83cde3cfc1 100644
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@ -1,5 +1,6 @@
# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
+from collections.abc import Collection
from typing import Any
from fastapi import FastAPI
@@ -35,6 +36,7 @@ from invokeai.app.services.events.events_common import (
ModelLoadStartedEvent,
QueueClearedEvent,
QueueEventBase,
+ QueueItemsCanceledEvent,
QueueItemsRetriedEvent,
QueueItemStatusChangedEvent,
RecallParametersUpdatedEvent,
@@ -72,6 +74,7 @@ QUEUE_EVENTS = {
QueueItemStatusChangedEvent,
BatchEnqueuedEvent,
QueueItemsRetriedEvent,
+ QueueItemsCanceledEvent,
QueueClearedEvent,
RecallParametersUpdatedEvent,
}
@@ -276,19 +279,79 @@ class SocketIO:
async def _handle_unsub_bulk_download(self, sid: str, data: Any) -> None:
await self._sio.leave_room(sid, BulkDownloadSubscriptionEvent(**data).bulk_download_id)
- def _owner_and_admin_sids(self, owner_user_id: str) -> list[str]:
- """Sids belonging to the event's owner or to any admin.
+ def _admin_sids(self) -> list[str]:
+ """Sids belonging to admin sockets."""
+ return [sid for sid, info in self._socket_users.items() if info.get("is_admin")]
+
+ def _owner_and_admin_sids(self, owner_user_ids: str | Collection[str]) -> list[str]:
+ """Sids belonging to the event's owner(s) or to any admin.
Used as `skip_sid` when broadcasting a sanitized companion event to the queue room,
- so the owner and admins (who already received the full event) don't get a second
+ so the owners and admins (who already received the full event) don't get a second
copy that would clobber their cache with redacted values.
+
+ Accepts a collection because a single event can have several owners — a retry batch may
+ span multiple users' queue items.
"""
+ owners = {owner_user_ids} if isinstance(owner_user_ids, str) else set(owner_user_ids)
return [
- sid
- for sid, info in self._socket_users.items()
- if info.get("user_id") == owner_user_id or info.get("is_admin")
+ sid for sid, info in self._socket_users.items() if info.get("user_id") in owners or info.get("is_admin")
]
+ async def _emit_bulk_queue_item_event(
+ self,
+ event_name: str,
+ event_data: QueueItemsRetriedEvent | QueueItemsCanceledEvent,
+ item_ids_field: str,
+ item_ids_by_user_field: str,
+ ) -> None:
+ """Routes a multi-owner bulk queue item event (retried/canceled).
+
+ These events carry queue item ids grouped by owner and are the only signal other clients
+ get for a bulk operation, which changes many rows in one SQL statement and emits no
+ per-item queue_item_status_changed events. Routing:
+
+ - Each owner's room gets the event scoped to that owner's own item ids. Admin sids are
+ skipped here because admins receive the full event below — without the skip, an admin
+ who also owns affected items (including the "system" user in single-user mode, whose
+ sockets are all in both rooms) would receive two copies and double-refetch the queue
+ caches.
+ - The admin room gets the full event: all item ids, all owners.
+ - The rest of the queue room gets a sanitized companion carrying no item ids and no
+ owners — just the queue_id its badge-count refetch needs.
+ """
+ item_ids_by_user: dict[str, list[int]] = getattr(event_data, item_ids_by_user_field)
+ admin_sids = self._admin_sids()
+ for user_id in event_data.user_ids:
+ user_room = f"user:{user_id}"
+ owner_item_ids = item_ids_by_user.get(user_id, [])
+ owner_event_data = event_data.model_copy(
+ update={
+ item_ids_field: owner_item_ids,
+ "user_ids": [user_id],
+ item_ids_by_user_field: {user_id: owner_item_ids},
+ }
+ )
+ await self._sio.emit(
+ event=event_name,
+ data=owner_event_data.model_dump(mode="json"),
+ room=user_room,
+ skip_sid=admin_sids,
+ )
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+
+ sanitized = event_data.model_copy(update={item_ids_field: [], "user_ids": [], item_ids_by_user_field: {}})
+ await self._sio.emit(
+ event=event_name,
+ data=sanitized.model_dump(mode="json"),
+ room=event_data.queue_id,
+ skip_sid=self._owner_and_admin_sids(event_data.user_ids),
+ )
+ logger.debug(
+ f"Emitted {event_name}: full to user rooms {event_data.user_ids} and admin, "
+ f"sanitized to queue {event_data.queue_id}"
+ )
+
async def _handle_queue_event(self, event: FastAPIEvent[QueueEventBase]):
"""Handle queue events with user isolation.
@@ -325,25 +388,36 @@ class SocketIO:
if isinstance(event_data, InvocationEventBase) and hasattr(event_data, "user_id"):
user_room = f"user:{event_data.user_id}"
- # Emit to the user's room
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=user_room)
-
- # Also emit to admin room so admins can see all events, but strip image preview data
- # from InvocationProgressEvent to prevent admins from seeing other users' image content
if isinstance(event_data, InvocationProgressEvent):
- admin_event_data = event_data.model_copy(update={"image": None})
- await self._sio.emit(event=event_name, data=admin_event_data.model_dump(mode="json"), room="admin")
+ # Progress events only drive personal UI (the global progress bar and progress
+ # image previews) and are high-frequency. No admin UI consumes other users'
+ # progress, so emit to the owner only. This also keeps other users' progress
+ # from hijacking an admin's progress bar and image previews.
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=user_room)
+ logger.debug(f"Emitted invocation progress event to user room {user_room}")
else:
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
-
- logger.debug(f"Emitted private invocation event {event_name} to user room {user_room} and admin room")
+ # started/complete/error also feed admins' gallery cache updates, so admins
+ # receive them for all users. Emit to the union of owner + admin rooms in a
+ # SINGLE call so an admin owner receives exactly one copy (see the
+ # RecallParametersUpdatedEvent note below on python-socketio's recipient
+ # dedup across a room list).
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=[user_room, "admin"]
+ )
+ logger.debug(
+ f"Emitted private invocation event {event_name} to user room {user_room} and admin room"
+ )
# QueueItemStatusChangedEvent: full to owner+admin, sanitized to everyone else in
# the queue room so their queue list, badge, and item caches refresh.
elif isinstance(event_data, QueueItemStatusChangedEvent):
user_room = f"user:{event_data.user_id}"
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=user_room)
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+ # Single emit to the union of rooms — python-socketio dedups recipients across a
+ # room list, so an admin owner (or the single-user "system" user, which is in both
+ # rooms) receives exactly one copy instead of running the frontend handler twice.
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=[user_room, "admin"]
+ )
sanitized = event_data.model_copy(
update={
@@ -385,8 +459,9 @@ class SocketIO:
# carry user_id) stay private to owner + admins.
elif isinstance(event_data, QueueItemEventBase) and hasattr(event_data, "user_id"):
user_room = f"user:{event_data.user_id}"
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=user_room)
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=[user_room, "admin"]
+ )
logger.debug(f"Emitted private queue item event {event_name} to user room {user_room} and admin room")
@@ -412,8 +487,9 @@ class SocketIO:
# room so their badge total and queue list pick up the new items.
elif isinstance(event_data, BatchEnqueuedEvent):
user_room = f"user:{event_data.user_id}"
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=user_room)
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=[user_room, "admin"]
+ )
sanitized = event_data.model_copy(
update={"user_id": "redacted", "batch_id": "redacted", "origin": None}
@@ -428,24 +504,22 @@ class SocketIO:
f"Emitted batch_enqueued: full to {user_room}+admin, sanitized to queue {event_data.queue_id}"
)
- # QueueItemsRetriedEvent carries queue item ids that should only be visible
- # to the affected owners + admins.
+ # QueueItemsRetriedEvent: retried items are re-enqueued, raising the queue's global
+ # total, but retrying emits no per-item queue_item_status_changed — this event is the
+ # only signal. Item ids are only visible to their owners + admins; everyone else gets
+ # the sanitized companion so their badge total refetches (the frontend handler skips
+ # its per-item invalidation when retried_item_ids is empty).
elif isinstance(event_data, QueueItemsRetriedEvent):
- for user_id in event_data.user_ids:
- user_room = f"user:{user_id}"
- owner_event_data = event_data.model_copy(
- update={
- "retried_item_ids": event_data.retried_item_ids_by_user.get(user_id, []),
- "user_ids": [user_id],
- "retried_item_ids_by_user": {user_id: event_data.retried_item_ids_by_user.get(user_id, [])},
- }
- )
- await self._sio.emit(
- event=event_name, data=owner_event_data.model_dump(mode="json"), room=user_room
- )
- await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
- logger.debug(
- f"Emitted private queue_items_retried event to user rooms {event_data.user_ids} and admin room"
+ await self._emit_bulk_queue_item_event(
+ event_name, event_data, "retried_item_ids", "retried_item_ids_by_user"
+ )
+
+ # QueueItemsCanceledEvent: a bulk cancel/delete (e.g. cancel-all-except-current) emits
+ # no per-item queue_item_status_changed, so this event is the only signal that pending
+ # items were removed from the queue.
+ elif isinstance(event_data, QueueItemsCanceledEvent):
+ await self._emit_bulk_queue_item_event(
+ event_name, event_data, "canceled_item_ids", "canceled_item_ids_by_user"
)
# QueueClearedEvent: an unscoped clear (user_id=None — admin or single-user mode)
@@ -477,20 +551,50 @@ class SocketIO:
)
else:
- # For remaining queue events that do not carry user identity,
- # emit to all subscribers in the queue room.
- await self._sio.emit(
- event=event_name, data=event_data.model_dump(mode="json"), room=event_data.queue_id
- )
- logger.debug(
- f"Emitted general queue event {event_name} to all subscribers in queue {event_data.queue_id}"
- )
+ # Fail closed: an event type without explicit routing above must not leak user
+ # identity or item ids to the whole queue room. If it carries user identity in
+ # any form, deliver it to the identified owners + admins only and log loudly —
+ # the event needs an explicit branch (and probably a sanitized companion) added
+ # above. Only identity-free events are broadcast.
+ owner_user_ids = getattr(event_data, "user_ids", None) or []
+ single_user_id = getattr(event_data, "user_id", None)
+ if single_user_id is not None:
+ owner_user_ids = [*owner_user_ids, single_user_id]
+ if owner_user_ids:
+ rooms = [f"user:{user_id}" for user_id in owner_user_ids] + ["admin"]
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=rooms)
+ logger.warning(
+ f"Queue event {event_name} carries user identity but has no explicit routing; "
+ f"emitted to owner + admin rooms only. Add a routing branch for it in _handle_queue_event."
+ )
+ else:
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=event_data.queue_id
+ )
+ logger.debug(
+ f"Emitted general queue event {event_name} to all subscribers in queue {event_data.queue_id}"
+ )
except Exception as e:
# Log any unhandled exceptions in event handling to prevent silent failures
logger.error(f"Error handling queue event {event[0]}: {e}", exc_info=True)
async def _handle_model_event(self, event: FastAPIEvent[ModelEventBase | DownloadEventBase]) -> None:
- await self._sio.emit(event=event[0], data=event[1].model_dump(mode="json"))
+ event_name, event_data = event
+
+ # Model load events only drive personal UI (the loading-models spinner that puts the
+ # progress bar into indeterminate mode), so they are routed to the user whose action
+ # triggered the load. Broadcasting them made every user's progress bar animate whenever
+ # any user's generation loaded a model. In single-user mode the owner is "system" and
+ # every socket is in user:system, preserving the old behavior.
+ if isinstance(event_data, (ModelLoadStartedEvent, ModelLoadCompleteEvent)):
+ await self._sio.emit(
+ event=event_name, data=event_data.model_dump(mode="json"), room=f"user:{event_data.user_id}"
+ )
+ return
+
+ # Model install / download events remain broadcast to all connected sockets - they feed
+ # the model manager UI, which is not per-user.
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"))
async def _handle_bulk_image_download_event(self, event: FastAPIEvent[BulkDownloadEventBase]) -> None:
event_name, event_data = event
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index 65be86f839..0294933720 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -29,6 +29,7 @@ from invokeai.app.services.events.events_common import (
ModelLoadCompleteEvent,
ModelLoadStartedEvent,
QueueClearedEvent,
+ QueueItemsCanceledEvent,
QueueItemsRetriedEvent,
QueueItemStatusChangedEvent,
RecallParametersUpdatedEvent,
@@ -113,6 +114,10 @@ class EventServiceBase:
"""Emitted when a list of queue items are retried"""
self.dispatch(QueueItemsRetriedEvent.build(retry_result, user_ids, retried_item_ids_by_user))
+ def emit_queue_items_canceled(self, queue_id: str, canceled_item_ids_by_user: dict[str, list[int]]) -> None:
+ """Emitted when queue items are canceled or deleted in bulk without per-item status change events"""
+ self.dispatch(QueueItemsCanceledEvent.build(queue_id, canceled_item_ids_by_user))
+
def emit_queue_cleared(self, queue_id: str, user_id: str | None = None) -> None:
"""Emitted when a queue is cleared. `user_id` scopes the clear to one user's items; None means all."""
self.dispatch(QueueClearedEvent.build(queue_id, user_id))
@@ -176,15 +181,17 @@ class EventServiceBase:
# region Model loading
- def emit_model_load_started(self, config: "AnyModelConfig", submodel_type: Optional["SubModelType"] = None) -> None:
+ def emit_model_load_started(
+ self, config: "AnyModelConfig", submodel_type: Optional["SubModelType"] = None, user_id: str = "system"
+ ) -> None:
"""Emitted when a model load is started."""
- self.dispatch(ModelLoadStartedEvent.build(config, submodel_type))
+ self.dispatch(ModelLoadStartedEvent.build(config, submodel_type, user_id))
def emit_model_load_complete(
- self, config: "AnyModelConfig", submodel_type: Optional["SubModelType"] = None
+ self, config: "AnyModelConfig", submodel_type: Optional["SubModelType"] = None, user_id: str = "system"
) -> None:
"""Emitted when a model load is complete."""
- self.dispatch(ModelLoadCompleteEvent.build(config, submodel_type))
+ self.dispatch(ModelLoadCompleteEvent.build(config, submodel_type, user_id))
# endregion
diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.py
index 15b48bb466..ef031e6e1f 100644
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@ -325,6 +325,29 @@ class QueueItemsRetriedEvent(QueueEventBase):
)
+@payload_schema.register
+class QueueItemsCanceledEvent(QueueEventBase):
+ """Event model for queue_items_canceled. Emitted when queue items are canceled or deleted in
+ bulk (e.g. cancel/delete-all-except-current) without per-item status change events."""
+
+ __event_name__ = "queue_items_canceled"
+
+ canceled_item_ids: list[int] = Field(description="The IDs of the queue items that were canceled or deleted")
+ user_ids: list[str] = Field(description="The IDs of the users who own the canceled queue items")
+ canceled_item_ids_by_user: dict[str, list[int]] = Field(
+ description="The canceled queue item IDs keyed by owner user ID."
+ )
+
+ @classmethod
+ def build(cls, queue_id: str, canceled_item_ids_by_user: dict[str, list[int]]) -> "QueueItemsCanceledEvent":
+ return cls(
+ queue_id=queue_id,
+ canceled_item_ids=[item_id for item_ids in canceled_item_ids_by_user.values() for item_id in item_ids],
+ user_ids=list(canceled_item_ids_by_user.keys()),
+ canceled_item_ids_by_user=canceled_item_ids_by_user,
+ )
+
+
@payload_schema.register
class QueueClearedEvent(QueueEventBase):
"""Event model for queue_cleared"""
@@ -510,10 +533,13 @@ class ModelLoadStartedEvent(ModelEventBase):
config: AnyModelConfig = Field(description="The model's config")
submodel_type: Optional[SubModelType] = Field(default=None, description="The submodel type, if any")
+ user_id: str = Field(default="system", description="The ID of the user whose action triggered the load")
@classmethod
- def build(cls, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> "ModelLoadStartedEvent":
- return cls(config=config, submodel_type=submodel_type)
+ def build(
+ cls, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None, user_id: str = "system"
+ ) -> "ModelLoadStartedEvent":
+ return cls(config=config, submodel_type=submodel_type, user_id=user_id)
@payload_schema.register
@@ -524,10 +550,13 @@ class ModelLoadCompleteEvent(ModelEventBase):
config: AnyModelConfig = Field(description="The model's config")
submodel_type: Optional[SubModelType] = Field(default=None, description="The submodel type, if any")
+ user_id: str = Field(default="system", description="The ID of the user whose action triggered the load")
@classmethod
- def build(cls, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> "ModelLoadCompleteEvent":
- return cls(config=config, submodel_type=submodel_type)
+ def build(
+ cls, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None, user_id: str = "system"
+ ) -> "ModelLoadCompleteEvent":
+ return cls(config=config, submodel_type=submodel_type, user_id=user_id)
@payload_schema.register
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 1eb3857dba..b9d03a8186 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -215,6 +215,13 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
AND board_images.board_id = ?
"""
query_params.append(board_id)
+ elif user_id is not None and not is_admin:
+ # No board_id supplied — still enforce per-user isolation so
+ # non-admins cannot enumerate other users' images
+ query_conditions += """--sql
+ AND images.user_id = ?
+ """
+ query_params.append(user_id)
# Search term condition
if search_term:
@@ -465,6 +472,13 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
AND board_images.board_id = ?
"""
query_params.append(board_id)
+ elif user_id is not None and not is_admin:
+ # No board_id supplied — still enforce per-user isolation so
+ # non-admins cannot enumerate other users' images
+ query_conditions += """--sql
+ AND images.user_id = ?
+ """
+ query_params.append(user_id)
if search_term:
query_conditions += """--sql
diff --git a/invokeai/app/services/model_load/model_load_base.py b/invokeai/app/services/model_load/model_load_base.py
index 87a405b4ea..a06f869cbf 100644
--- a/invokeai/app/services/model_load/model_load_base.py
+++ b/invokeai/app/services/model_load/model_load_base.py
@@ -15,12 +15,19 @@ class ModelLoadServiceBase(ABC):
"""Wrapper around AnyModelLoader."""
@abstractmethod
- def load_model(self, model_config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> LoadedModel:
+ def load_model(
+ self,
+ model_config: AnyModelConfig,
+ submodel_type: Optional[SubModelType] = None,
+ user_id: Optional[str] = None,
+ ) -> LoadedModel:
"""
Given a model's configuration, load it and return the LoadedModel object.
:param model_config: Model configuration record (as returned by ModelRecordBase.get_model())
:param submodel: For main (pipeline models), the submodel to fetch.
+ :param user_id: The user whose action triggered the load, threaded into the model load
+ events so they can be routed to that user's UI (defaults to the system user).
"""
@property
diff --git a/invokeai/app/services/model_load/model_load_default.py b/invokeai/app/services/model_load/model_load_default.py
index 2e2d2ae219..480c88dd74 100644
--- a/invokeai/app/services/model_load/model_load_default.py
+++ b/invokeai/app/services/model_load/model_load_default.py
@@ -50,18 +50,25 @@ class ModelLoadService(ModelLoadServiceBase):
"""Return the RAM cache used by this loader."""
return self._ram_cache
- def load_model(self, model_config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> LoadedModel:
+ def load_model(
+ self,
+ model_config: AnyModelConfig,
+ submodel_type: Optional[SubModelType] = None,
+ user_id: Optional[str] = None,
+ ) -> LoadedModel:
"""
Given a model's configuration, load it and return the LoadedModel object.
:param model_config: Model configuration record (as returned by ModelRecordBase.get_model())
:param submodel: For main (pipeline models), the submodel to fetch.
+ :param user_id: The user whose action triggered the load, threaded into the model load
+ events so they can be routed to that user's UI (defaults to the system user).
"""
# We don't have an invoker during testing
# TODO(psyche): Mock this method on the invoker in the tests
if hasattr(self, "_invoker"):
- self._invoker.services.events.emit_model_load_started(model_config, submodel_type)
+ self._invoker.services.events.emit_model_load_started(model_config, submodel_type, user_id or "system")
implementation, model_config, submodel_type = self._registry.get_implementation(model_config, submodel_type) # type: ignore
loaded_model: LoadedModel = implementation(
@@ -71,7 +78,7 @@ class ModelLoadService(ModelLoadServiceBase):
).load_model(model_config, submodel_type)
if hasattr(self, "_invoker"):
- self._invoker.services.events.emit_model_load_complete(model_config, submodel_type)
+ self._invoker.services.events.emit_model_load_complete(model_config, submodel_type, user_id or "system")
return loaded_model
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index a07abf10ee..2737816d71 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -79,18 +79,25 @@ class SessionQueueBase(ABC):
queue_id: str,
user_id: Optional[str] = None,
acting_user_id: Optional[str] = None,
+ is_admin: bool = False,
) -> SessionQueueStatus:
"""Gets the status of the queue.
Aggregate counts (pending/in_progress/.../total) are always global across all users.
If user_id is provided, the requesting user's own counts are additionally returned in
- the user_pending/user_in_progress fields (left None otherwise).
+ the user_pending/user_in_progress fields (left None otherwise). Admin callers should
+ also pass their user_id so personal UI (e.g. the progress bar) can distinguish their
+ own activity from other users'.
acting_user_id is independent of user_id and controls only current-item redaction:
when set, the returned status omits item_id/session_id/batch_id unless the
currently-running item belongs to acting_user_id. The redaction is decided from the
same get_current() snapshot used to embed those identifiers, so it cannot race against
a concurrent state change.
+
+ is_admin disables current-item redaction entirely: admins may see the identifiers of
+ any user's current item. Redaction stays fail-closed - a caller that passes user_id
+ without is_admin gets the non-admin behavior.
"""
pass
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index 51980d68f3..e845d663ef 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -1,6 +1,7 @@
import asyncio
import json
import sqlite3
+from collections.abc import Sequence
from typing import Any, Optional, Union, cast
from pydantic_core import to_jsonable_python
@@ -399,7 +400,12 @@ class SqliteSessionQueue(SessionQueueBase):
# Doing this inside get_queue_status guarantees the redaction decision and the
# embedded identifiers come from the same get_current() snapshot — eliminating the
# race where a second read could find None and skip scrubbing stale identifiers.
- queue_status = self.get_queue_status(queue_id=queue_item.queue_id, acting_user_id=queue_item.user_id)
+ # user_id additionally embeds the owner's per-user counts so the owner's client can
+ # apply the event's queue_status optimistically without waiting for a refetch; the
+ # sanitized companion nulls them before reaching anyone else.
+ queue_status = self.get_queue_status(
+ queue_id=queue_item.queue_id, user_id=queue_item.user_id, acting_user_id=queue_item.user_id
+ )
self.__invoker.services.events.emit_queue_item_status_changed(queue_item, batch_status, queue_status)
return queue_item
@@ -622,6 +628,35 @@ class SqliteSessionQueue(SessionQueueBase):
)
return queue_item
+ def _collect_item_ids_by_user(
+ self, cursor: sqlite3.Cursor, where: str, params: Sequence[Any]
+ ) -> dict[str, list[int]]:
+ """Groups the item ids matched by `where` by their owner's user id.
+
+ Bulk cancel/delete operations mutate many rows in a single SQL statement and therefore
+ emit no per-item queue_item_status_changed events. Call this with the operation's WHERE
+ clause before mutating, then pass the result to _emit_queue_items_canceled after the
+ transaction commits so every affected owner (and everyone's badge counts) can refresh.
+ """
+ cursor.execute(
+ f"""--sql
+ SELECT item_id, user_id
+ FROM session_queue
+ {where};
+ """,
+ tuple(params),
+ )
+ item_ids_by_user: dict[str, list[int]] = {}
+ for item_id, owner_user_id in cursor.fetchall():
+ item_ids_by_user.setdefault(owner_user_id, []).append(item_id)
+ return item_ids_by_user
+
+ def _emit_queue_items_canceled(self, queue_id: str, item_ids_by_user: dict[str, list[int]]) -> None:
+ """Emits queue_items_canceled for a bulk cancel/delete, unless nothing was affected —
+ an empty result must not broadcast a pointless refetch signal to every client."""
+ if item_ids_by_user:
+ self.__invoker.services.events.emit_queue_items_canceled(queue_id, item_ids_by_user)
+
def cancel_by_batch_ids(
self, queue_id: str, batch_ids: list[str], user_id: Optional[str] = None
) -> CancelByBatchIDsResult:
@@ -646,15 +681,8 @@ class SqliteSessionQueue(SessionQueueBase):
if user_id is not None:
params.append(user_id)
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
- {where};
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ canceled_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in canceled_item_ids_by_user.values())
cursor.execute(
f"""--sql
UPDATE session_queue
@@ -665,11 +693,13 @@ class SqliteSessionQueue(SessionQueueBase):
tuple(params),
)
- # Handle current item separately - check ownership if user_id is provided
+ # Handle current item separately - check ownership if user_id is provided. This emits a
+ # per-item queue_item_status_changed, so the bulk event below need not include it.
if current_queue_item is not None and current_queue_item.batch_id in batch_ids:
if user_id is None or current_queue_item.user_id == user_id:
self._set_queue_item_status(current_queue_item.item_id, "canceled")
+ self._emit_queue_items_canceled(queue_id, canceled_item_ids_by_user)
return CancelByBatchIDsResult(canceled=count)
def cancel_by_destination(
@@ -695,15 +725,8 @@ class SqliteSessionQueue(SessionQueueBase):
if user_id is not None:
params.append(user_id)
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
- {where};
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ canceled_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in canceled_item_ids_by_user.values())
cursor.execute(
f"""--sql
UPDATE session_queue
@@ -714,11 +737,13 @@ class SqliteSessionQueue(SessionQueueBase):
tuple(params),
)
- # Handle current item separately - check ownership if user_id is provided
+ # Handle current item separately - check ownership if user_id is provided. This emits a
+ # per-item queue_item_status_changed, so the bulk event below need not include it.
if current_queue_item is not None and current_queue_item.destination == destination:
if user_id is None or current_queue_item.user_id == user_id:
self._set_queue_item_status(current_queue_item.item_id, "canceled")
+ self._emit_queue_items_canceled(queue_id, canceled_item_ids_by_user)
return CancelByDestinationResult(canceled=count)
def delete_by_destination(
@@ -727,39 +752,45 @@ class SqliteSessionQueue(SessionQueueBase):
with self._db.transaction() as cursor:
current_queue_item = self.get_current(queue_id)
- # Handle current item separately - check ownership if user_id is provided
+ # Handle current item separately - check ownership if user_id is provided. Its cancel
+ # emits a per-item queue_item_status_changed, so the bulk event below must not signal
+ # it a second time. Its row still matches the destination WHERE (the cancel only flips
+ # its status), so it is excluded from the collected ids — but not from the DELETE or
+ # the returned count.
+ canceled_current_item_id: Optional[int] = None
if current_queue_item is not None and current_queue_item.destination == destination:
if user_id is None or current_queue_item.user_id == user_id:
self.cancel_queue_item(current_queue_item.item_id)
+ canceled_current_item_id = current_queue_item.item_id
# Build WHERE clause with optional user_id filter
user_filter = "AND user_id = ?" if user_id is not None else ""
- params = [queue_id, destination]
- if user_id is not None:
- params.append(user_id)
-
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
+ where = f"""--sql
WHERE
queue_id == ?
AND destination == ?
{user_filter}
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ """
+ params = [queue_id, destination]
+ if user_id is not None:
+ params.append(user_id)
+
+ deleted_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in deleted_item_ids_by_user.values())
+ if canceled_current_item_id is not None and current_queue_item is not None:
+ owner_item_ids = deleted_item_ids_by_user.get(current_queue_item.user_id)
+ if owner_item_ids is not None and canceled_current_item_id in owner_item_ids:
+ owner_item_ids.remove(canceled_current_item_id)
+ if not owner_item_ids:
+ del deleted_item_ids_by_user[current_queue_item.user_id]
cursor.execute(
f"""--sql
DELETE FROM session_queue
- WHERE
- queue_id == ?
- AND destination == ?
- {user_filter}
+ {where};
""",
tuple(params),
)
+ self._emit_queue_items_canceled(queue_id, deleted_item_ids_by_user)
return DeleteByDestinationResult(deleted=count)
def delete_all_except_current(self, queue_id: str, user_id: Optional[str] = None) -> DeleteAllExceptCurrentResult:
@@ -783,15 +814,8 @@ class SqliteSessionQueue(SessionQueueBase):
params.append(user_id)
params.extend(current_chain_item_ids)
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
- {where};
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ deleted_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in deleted_item_ids_by_user.values())
cursor.execute(
f"""--sql
DELETE
@@ -800,6 +824,7 @@ class SqliteSessionQueue(SessionQueueBase):
""",
tuple(params),
)
+ self._emit_queue_items_canceled(queue_id, deleted_item_ids_by_user)
return DeleteAllExceptCurrentResult(deleted=count)
def cancel_by_queue_id(self, queue_id: str) -> CancelByQueueIDResult:
@@ -815,15 +840,8 @@ class SqliteSessionQueue(SessionQueueBase):
AND status != 'in_progress'
"""
params = [queue_id]
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
- {where};
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ canceled_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in canceled_item_ids_by_user.values())
cursor.execute(
f"""--sql
UPDATE session_queue
@@ -834,8 +852,11 @@ class SqliteSessionQueue(SessionQueueBase):
tuple(params),
)
+ # The current item's cancel emits its own queue_item_status_changed; the bulk event
+ # below covers the silently-updated rows.
if current_queue_item is not None and current_queue_item.queue_id == queue_id:
self._set_queue_item_status(current_queue_item.item_id, "canceled")
+ self._emit_queue_items_canceled(queue_id, canceled_item_ids_by_user)
return CancelByQueueIDResult(canceled=count)
def cancel_all_except_current(self, queue_id: str, user_id: Optional[str] = None) -> CancelAllExceptCurrentResult:
@@ -859,15 +880,8 @@ class SqliteSessionQueue(SessionQueueBase):
params.append(user_id)
params.extend(current_chain_item_ids)
- cursor.execute(
- f"""--sql
- SELECT COUNT(*)
- FROM session_queue
- {where};
- """,
- tuple(params),
- )
- count = cursor.fetchone()[0]
+ canceled_item_ids_by_user = self._collect_item_ids_by_user(cursor, where, params)
+ count = sum(len(item_ids) for item_ids in canceled_item_ids_by_user.values())
cursor.execute(
f"""--sql
UPDATE session_queue
@@ -877,6 +891,7 @@ class SqliteSessionQueue(SessionQueueBase):
""",
tuple(params),
)
+ self._emit_queue_items_canceled(queue_id, canceled_item_ids_by_user)
return CancelAllExceptCurrentResult(canceled=count)
def get_queue_item(self, item_id: int) -> SessionQueueItem:
@@ -989,7 +1004,9 @@ class SqliteSessionQueue(SessionQueueBase):
queue_item = self.get_queue_item(item_id)
batch_status = self.get_batch_status(queue_id=queue_item.queue_id, batch_id=queue_item.batch_id)
- queue_status = self.get_queue_status(queue_id=queue_item.queue_id, acting_user_id=queue_item.user_id)
+ queue_status = self.get_queue_status(
+ queue_id=queue_item.queue_id, user_id=queue_item.user_id, acting_user_id=queue_item.user_id
+ )
self.__invoker.services.events.emit_queue_item_status_changed(queue_item, batch_status, queue_status)
return queue_item
@@ -1143,6 +1160,7 @@ class SqliteSessionQueue(SessionQueueBase):
queue_id: str,
user_id: Optional[str] = None,
acting_user_id: Optional[str] = None,
+ is_admin: bool = False,
) -> SessionQueueStatus:
with self._db.transaction() as cursor:
# Aggregate counts are always global (across all users). This lets a non-admin's
@@ -1190,11 +1208,13 @@ class SqliteSessionQueue(SessionQueueBase):
# so a concurrent transition (e.g. B finishing while A's status changes) cannot leave
# stale identifiers in the result. The aggregate counts stay global; only the current
# item's identifiers are gated. acting_user_id (event path) takes precedence over
- # user_id (API path) when deciding the redaction owner; either being None means an
- # admin/global caller who may see the current item.
+ # user_id (API path) when deciding the redaction owner; either being None means a
+ # global caller who may see the current item. is_admin disables redaction outright so
+ # admin callers can pass their user_id (for the per-user counts) without losing
+ # visibility of other users' current item.
owner_user_id = user_id if acting_user_id is None else acting_user_id
show_current_item = current_item is not None and (
- owner_user_id is None or current_item.user_id == owner_user_id
+ is_admin or owner_user_id is None or current_item.user_id == owner_user_id
)
return SessionQueueStatus(
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index e38766d5ba..9c142359bc 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -394,7 +394,7 @@ class ModelsInterface(InvocationContextInterface):
if submodel_type:
message += f" ({submodel_type.value})"
self._util.signal_progress(message)
- return self._services.model_manager.load.load_model(model, submodel_type)
+ return self._services.model_manager.load.load_model(model, submodel_type, user_id=self._data.queue_item.user_id)
def load_by_attrs(
self, name: str, base: BaseModelType, type: ModelType, submodel_type: Optional[SubModelType] = None
@@ -424,7 +424,9 @@ class ModelsInterface(InvocationContextInterface):
if submodel_type:
message += f" ({submodel_type.value})"
self._util.signal_progress(message)
- return self._services.model_manager.load.load_model(configs[0], submodel_type)
+ return self._services.model_manager.load.load_model(
+ configs[0], submodel_type, user_id=self._data.queue_item.user_id
+ )
@staticmethod
def _raise_if_external(model: AnyModelConfig) -> None:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index e2801e9e39..75669eb584 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -7738,7 +7738,7 @@
"get": {
"tags": ["queue"],
"summary": "Get Queue Status",
- "description": "Gets the status of the session queue. Returns global counts; non-admin users additionally\nget their own pending/in_progress counts (so the UI can show an X/Y badge) and cannot see the\ncurrent item's identifiers unless they own it.",
+ "description": "Gets the status of the session queue. Returns global counts; every user additionally gets\ntheir own pending/in_progress counts (so the UI can show an X/Y badge and scope personal UI\nlike the progress bar to the user's own activity). Non-admin users cannot see the current\nitem's identifiers unless they own it.",
"operationId": "get_queue_status",
"security": [
{
@@ -57112,9 +57112,15 @@
],
"default": null,
"description": "The submodel type, if any"
+ },
+ "user_id": {
+ "default": "system",
+ "description": "The ID of the user whose action triggered the load",
+ "title": "User Id",
+ "type": "string"
}
},
- "required": ["timestamp", "config", "submodel_type"],
+ "required": ["timestamp", "config", "submodel_type", "user_id"],
"title": "ModelLoadCompleteEvent",
"type": "object"
},
@@ -57422,9 +57428,15 @@
],
"default": null,
"description": "The submodel type, if any"
+ },
+ "user_id": {
+ "default": "system",
+ "description": "The ID of the user whose action triggered the load",
+ "title": "User Id",
+ "type": "string"
}
},
- "required": ["timestamp", "config", "submodel_type"],
+ "required": ["timestamp", "config", "submodel_type", "user_id"],
"title": "ModelLoadStartedEvent",
"type": "object"
},
@@ -60263,6 +60275,51 @@
"title": "QueueItemStatusChangedEvent",
"type": "object"
},
+ "QueueItemsCanceledEvent": {
+ "description": "Event model for queue_items_canceled. Emitted when queue items are canceled or deleted in\nbulk (e.g. cancel/delete-all-except-current) without per-item status change events.",
+ "properties": {
+ "timestamp": {
+ "description": "The timestamp of the event",
+ "title": "Timestamp",
+ "type": "integer"
+ },
+ "queue_id": {
+ "description": "The ID of the queue",
+ "title": "Queue Id",
+ "type": "string"
+ },
+ "canceled_item_ids": {
+ "description": "The IDs of the queue items that were canceled or deleted",
+ "items": {
+ "type": "integer"
+ },
+ "title": "Canceled Item Ids",
+ "type": "array"
+ },
+ "user_ids": {
+ "description": "The IDs of the users who own the canceled queue items",
+ "items": {
+ "type": "string"
+ },
+ "title": "User Ids",
+ "type": "array"
+ },
+ "canceled_item_ids_by_user": {
+ "additionalProperties": {
+ "items": {
+ "type": "integer"
+ },
+ "type": "array"
+ },
+ "description": "The canceled queue item IDs keyed by owner user ID.",
+ "title": "Canceled Item Ids By User",
+ "type": "object"
+ }
+ },
+ "required": ["timestamp", "queue_id", "canceled_item_ids", "user_ids", "canceled_item_ids_by_user"],
+ "title": "QueueItemsCanceledEvent",
+ "type": "object"
+ },
"QueueItemsRetriedEvent": {
"description": "Event model for queue_items_retried",
"properties": {
diff --git a/invokeai/frontend/web/src/app/hooks/useSyncFaviconQueueStatus.ts b/invokeai/frontend/web/src/app/hooks/useSyncFaviconQueueStatus.ts
index 7bd55f25f4..9eb8d09cb1 100644
--- a/invokeai/frontend/web/src/app/hooks/useSyncFaviconQueueStatus.ts
+++ b/invokeai/frontend/web/src/app/hooks/useSyncFaviconQueueStatus.ts
@@ -1,4 +1,5 @@
import { useAssertSingleton } from 'common/hooks/useAssertSingleton';
+import { getUserScopedQueueCounts } from 'features/queue/store/userScopedQueueCounts';
import { useEffect } from 'react';
import { useGetQueueStatusQuery } from 'services/api/endpoints/queue';
@@ -7,9 +8,14 @@ const invokeLogoSVG = 'assets/images/invoke-favicon.svg';
const invokeAlertLogoSVG = 'assets/images/invoke-alert-favicon.svg';
const queryOptions = {
- selectFromResult: (res) => ({
- queueSize: res.data ? res.data.queue.pending + res.data.queue.in_progress : 0,
- }),
+ // The busy favicon/title reflect the user's own activity, not other users' generations.
+ selectFromResult: (res) => {
+ if (!res.data) {
+ return { queueSize: 0 };
+ }
+ const { pending, inProgress } = getUserScopedQueueCounts(res.data.queue);
+ return { queueSize: pending + inProgress };
+ },
} satisfies Parameters<typeof useGetQueueStatusQuery>[1];
const updateFavicon = (queueSize: number) => {
diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
index d502deb449..e622cd83d0 100644
--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx
@@ -1,6 +1,6 @@
import { useStore } from '@nanostores/react';
import { logger } from 'app/logging/logger';
-import { useAppSelector } from 'app/store/storeHooks';
+import { useAppSelector, useAppStore } from 'app/store/storeHooks';
import { selectAutoSwitch } from 'features/gallery/store/gallerySelectors';
import type { ProgressImage as ProgressImageType } from 'features/nodes/types/common';
import { LRUCache } from 'lru-cache';
@@ -8,6 +8,7 @@ import { type Atom, atom, computed, type WritableAtom } from 'nanostores';
import type { PropsWithChildren } from 'react';
import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import type { S } from 'services/api/types';
+import { getEventScope } from 'services/events/eventScope';
import { $socket } from 'services/events/stores';
import { assert } from 'tsafe';
import type { JsonObject } from 'type-fest';
@@ -27,6 +28,7 @@ const log = logger('events');
export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {
const socket = useStore($socket);
+ const store = useAppStore();
const autoSwitch = useAppSelector(selectAutoSwitch);
const $progressEvent = useState(() => atom<S['InvocationProgressEvent'] | null>(null))[0];
const $progressImage = useState(() => atom<ProgressImageType | null>(null))[0];
@@ -44,6 +46,11 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {
}
const onInvocationProgress = (data: S['InvocationProgressEvent']) => {
+ // The backend routes progress events to the owner's room only; this check is defense in
+ // depth, mirroring the invocation_progress listener in setEventListeners.
+ if (getEventScope(store.getState, data) !== 'own') {
+ return;
+ }
if (finishedQueueItemIds.has(data.item_id)) {
log.trace(
{ data } as JsonObject,
@@ -64,7 +71,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {
return () => {
socket.off('invocation_progress', onInvocationProgress);
};
- }, [$isProgressImageResolving, $progressEvent, $progressImage, finishedQueueItemIds, socket]);
+ }, [$isProgressImageResolving, $progressEvent, $progressImage, finishedQueueItemIds, socket, store]);
useEffect(() => {
if (!socket) {
@@ -72,6 +79,14 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {
}
const onQueueItemStatusChanged = (data: S['QueueItemStatusChangedEvent']) => {
+ // Other users' terminal status changes must not clear this client's live progress
+ // preview. Both the sanitized companion (user_id="redacted", broadcast to every queue
+ // subscriber) and foreign full events (received by admins via the admin room) carry a
+ // real top-level item_id and terminal status, so without this guard they would drive
+ // the terminal branch below and blank the viewer mid-generation.
+ if (getEventScope(store.getState, data) !== 'own') {
+ return;
+ }
if (finishedQueueItemIds.has(data.item_id)) {
log.trace(
{ data } as JsonObject,
@@ -115,7 +130,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {
return () => {
socket.off('queue_item_status_changed', onQueueItemStatusChanged);
};
- }, [$isProgressImageResolving, $progressEvent, $progressImage, autoSwitch, finishedQueueItemIds, socket]);
+ }, [$isProgressImageResolving, $progressEvent, $progressImage, autoSwitch, finishedQueueItemIds, socket, store]);
const onLoadImage = useCallback(() => {
if (!shouldClearProgressImageOnLoadRef.current) {
diff --git a/invokeai/frontend/web/src/features/queue/components/InvokeButtonIcon.tsx b/invokeai/frontend/web/src/features/queue/components/InvokeButtonIcon.tsx
new file mode 100644
index 0000000000..56264705a8
--- /dev/null
+++ b/invokeai/frontend/web/src/features/queue/components/InvokeButtonIcon.tsx
@@ -0,0 +1,32 @@
+import { Icon, spinAnimation, useShiftModifier } from '@invoke-ai/ui-library';
+import { useUserHasActiveQueueItems } from 'features/queue/hooks/useUserHasActiveQueueItems';
+import { memo } from 'react';
+import { PiCircleNotchBold, PiLightningFill, PiSparkleFill } from 'react-icons/pi';
+
+type Props = {
+ /** Whether the invoke button is disabled — the parent already subscribes to useInvoke, so it
+ * passes the flag down rather than the icon duplicating that (heavy) hook tree. */
+ isDisabled: boolean;
+ boxSize: number;
+};
+
+/**
+ * Icon shared by the invoke buttons: a spinner while the user has queue items pending or in
+ * progress — feedback that their session is enqueued even when another user's generation
+ * occupies the processor — otherwise the shift-dependent lightning/sparkle glyph.
+ */
+export const InvokeButtonIcon = memo(({ isDisabled, boxSize }: Props) => {
+ const shift = useShiftModifier();
+ const hasActiveQueueItems = useUserHasActiveQueueItems();
+
+ if (!isDisabled && hasActiveQueueItems) {
+ return <Icon boxSize={boxSize} as={PiCircleNotchBold} animation={spinAnimation} />;
+ }
+
+ if (shift) {
+ return <PiLightningFill />;
+ }
+
+ return <PiSparkleFill />;
+});
+InvokeButtonIcon.displayName = 'InvokeButtonIcon';
diff --git a/invokeai/frontend/web/src/features/queue/components/InvokeQueueBackButton.tsx b/invokeai/frontend/web/src/features/queue/components/InvokeQueueBackButton.tsx
index a363d159e1..aa20eff461 100644
--- a/invokeai/frontend/web/src/features/queue/components/InvokeQueueBackButton.tsx
+++ b/invokeai/frontend/web/src/features/queue/components/InvokeQueueBackButton.tsx
@@ -1,10 +1,10 @@
import { Button, Flex, Spacer, useShiftModifier } from '@invoke-ai/ui-library';
import { useAppSelector } from 'app/store/storeHooks';
import { selectDynamicPromptsIsLoading } from 'features/dynamicPrompts/store/dynamicPromptsSlice';
+import { InvokeButtonIcon } from 'features/queue/components/InvokeButtonIcon';
import { QueueIterationsNumberInput } from 'features/queue/components/QueueIterationsNumberInput';
import { useInvoke } from 'features/queue/hooks/useInvoke';
import { memo } from 'react';
-import { PiLightningFill, PiSparkleFill } from 'react-icons/pi';
import { useAutoAddBoard } from 'services/api/hooks/useAutoAddBoard';
import { useBoardAccess } from 'services/api/hooks/useBoardAccess';
@@ -28,7 +28,7 @@ export const InvokeButton = memo(() => {
isLoading={queue.isLoading || isLoadingDynamicPrompts}
loadingText={invoke}
isDisabled={queue.isDisabled || !canWriteImages}
- rightIcon={shift ? <PiLightningFill /> : <PiSparkleFill />}
+ rightIcon={<InvokeButtonIcon isDisabled={queue.isDisabled || !canWriteImages} boxSize={5} />}
variant="solid"
colorScheme="invokeYellow"
size="lg"
diff --git a/invokeai/frontend/web/src/features/queue/hooks/useUserHasActiveQueueItems.ts b/invokeai/frontend/web/src/features/queue/hooks/useUserHasActiveQueueItems.ts
new file mode 100644
index 0000000000..794f464cdd
--- /dev/null
+++ b/invokeai/frontend/web/src/features/queue/hooks/useUserHasActiveQueueItems.ts
@@ -0,0 +1,21 @@
+import { getUserScopedQueueCounts } from 'features/queue/store/userScopedQueueCounts';
+import { useGetQueueStatusQuery } from 'services/api/endpoints/queue';
+
+/**
+ * Whether the current user has queue items that are pending or in progress. Drives the invoke
+ * button spinners so the user gets feedback that their session is enqueued even when another
+ * user's generation occupies the processor.
+ */
+export const useUserHasActiveQueueItems = (): boolean => {
+ const { hasActiveQueueItems } = useGetQueueStatusQuery(undefined, {
+ selectFromResult: ({ data }) => {
+ if (!data) {
+ return { hasActiveQueueItems: false };
+ }
+ const { pending, inProgress } = getUserScopedQueueCounts(data.queue);
+ return { hasActiveQueueItems: pending + inProgress > 0 };
+ },
+ });
+
+ return hasActiveQueueItems;
+};
diff --git a/invokeai/frontend/web/src/features/queue/store/userScopedQueueCounts.ts b/invokeai/frontend/web/src/features/queue/store/userScopedQueueCounts.ts
new file mode 100644
index 0000000000..8cd8ad86b1
--- /dev/null
+++ b/invokeai/frontend/web/src/features/queue/store/userScopedQueueCounts.ts
@@ -0,0 +1,16 @@
+import type { S } from 'services/api/types';
+
+/**
+ * The user-scoped view of the queue counts, for personal UI: the progress bar, the busy favicon,
+ * and the invoke-button spinner. In multiuser mode the global counts include other users'
+ * generations, so the per-user counts are preferred; a status that carries no per-user counts
+ * (e.g. the sanitized statuses broadcast to non-owners) falls back to the global counts, which
+ * are correct in single-user mode.
+ *
+ * This is the single place encoding that fallback — personal-UI consumers must not reimplement
+ * it, or they drift and disagree about whether the user is busy.
+ */
+export const getUserScopedQueueCounts = (queue: S['SessionQueueStatus']): { pending: number; inProgress: number } => ({
+ pending: queue.user_pending ?? queue.pending,
+ inProgress: queue.user_in_progress ?? queue.in_progress,
+});
diff --git a/invokeai/frontend/web/src/features/system/components/ProgressBar.tsx b/invokeai/frontend/web/src/features/system/components/ProgressBar.tsx
index 5a4abdd4d2..2049d9fe19 100644
--- a/invokeai/frontend/web/src/features/system/components/ProgressBar.tsx
+++ b/invokeai/frontend/web/src/features/system/components/ProgressBar.tsx
@@ -1,6 +1,7 @@
import type { ProgressProps } from '@invoke-ai/ui-library';
import { Progress } from '@invoke-ai/ui-library';
import { useStore } from '@nanostores/react';
+import { getUserScopedQueueCounts } from 'features/queue/store/userScopedQueueCounts';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useGetQueueStatusQuery } from 'services/api/endpoints/queue';
@@ -12,6 +13,8 @@ const ProgressBar = (props: ProgressProps) => {
const isConnected = useStore($isConnected);
const lastProgressEvent = useStore($lastProgressEvent);
const loadingModelsCount = useStore($loadingModelsCount);
+ // The progress bar reflects the user's own activity, not other users' generations.
+ const inProgressCount = queueStatus ? getUserScopedQueueCounts(queueStatus.queue).inProgress : undefined;
const value = useMemo(() => {
if (!lastProgressEvent) {
return 0;
@@ -28,7 +31,7 @@ const ProgressBar = (props: ProgressProps) => {
return true;
}
- if (!queueStatus?.queue.in_progress) {
+ if (!inProgressCount) {
return false;
}
@@ -45,7 +48,7 @@ const ProgressBar = (props: ProgressProps) => {
}
return false;
- }, [isConnected, lastProgressEvent, queueStatus?.queue.in_progress, loadingModelsCount]);
+ }, [isConnected, lastProgressEvent, inProgressCount, loadingModelsCount]);
return (
<Progress
diff --git a/invokeai/frontend/web/src/features/ui/components/FloatingLeftPanelButtons.tsx b/invokeai/frontend/web/src/features/ui/components/FloatingLeftPanelButtons.tsx
index c9620d84ac..f6474cbd83 100644
--- a/invokeai/frontend/web/src/features/ui/components/FloatingLeftPanelButtons.tsx
+++ b/invokeai/frontend/web/src/features/ui/components/FloatingLeftPanelButtons.tsx
@@ -1,22 +1,15 @@
-import { ButtonGroup, Flex, Icon, IconButton, spinAnimation, Tooltip, useShiftModifier } from '@invoke-ai/ui-library';
+import { ButtonGroup, Flex, IconButton, Tooltip, useShiftModifier } from '@invoke-ai/ui-library';
import { ToolChooser } from 'features/controlLayers/components/Tool/ToolChooser';
import { CanvasManagerProviderGate } from 'features/controlLayers/contexts/CanvasManagerProviderGate';
import { useDeleteAllExceptCurrentQueueItemDialog } from 'features/queue/components/DeleteAllExceptCurrentQueueItemConfirmationAlertDialog';
+import { InvokeButtonIcon } from 'features/queue/components/InvokeButtonIcon';
import { InvokeButtonTooltip } from 'features/queue/components/InvokeButtonTooltip/InvokeButtonTooltip';
import { useDeleteCurrentQueueItem } from 'features/queue/hooks/useDeleteCurrentQueueItem';
import { useInvoke } from 'features/queue/hooks/useInvoke';
import { navigationApi } from 'features/ui/layouts/navigation-api';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import {
- PiCircleNotchBold,
- PiLightningFill,
- PiSlidersHorizontalBold,
- PiSparkleFill,
- PiXBold,
- PiXCircle,
-} from 'react-icons/pi';
-import { useGetQueueStatusQuery } from 'services/api/endpoints/queue';
+import { PiSlidersHorizontalBold, PiXBold, PiXCircle } from 'react-icons/pi';
import { useAutoAddBoard } from 'services/api/hooks/useAutoAddBoard';
import { useBoardAccess } from 'services/api/hooks/useBoardAccess';
@@ -83,7 +76,7 @@ const InvokeIconButton = memo(() => {
onClick={shift ? queue.enqueueFront : queue.enqueueBack}
isLoading={queue.isLoading}
isDisabled={queue.isDisabled || !canWriteImages}
- icon={<InvokeIconButtonIcon />}
+ icon={<InvokeButtonIcon isDisabled={queue.isDisabled || !canWriteImages} boxSize={6} />}
colorScheme="invokeYellow"
flexGrow={1}
/>
@@ -92,30 +85,6 @@ const InvokeIconButton = memo(() => {
});
InvokeIconButton.displayName = 'InvokeIconButton';
-const InvokeIconButtonIcon = memo(() => {
- const shift = useShiftModifier();
- const queue = useInvoke();
- const { isProcessing } = useGetQueueStatusQuery(undefined, {
- selectFromResult: ({ data }) => {
- if (!data) {
- return { isProcessing: false };
- }
- return { isProcessing: data.queue.in_progress > 0 };
- },
- });
-
- if (!queue.isDisabled && isProcessing) {
- return <Icon boxSize={6} as={PiCircleNotchBold} animation={spinAnimation} />;
- }
-
- if (shift) {
- return <PiLightningFill />;
- }
-
- return <PiSparkleFill />;
-});
-InvokeIconButtonIcon.displayName = 'InvokeIconButtonIcon';
-
const DeleteCurrentIconButton = memo(() => {
const { t } = useTranslation();
const deleteCurrentQueueItem = useDeleteCurrentQueueItem();
diff --git a/invokeai/frontend/web/src/services/api/endpoints/queue.ts b/invokeai/frontend/web/src/services/api/endpoints/queue.ts
index 70f4e6a65c..0ce864882f 100644
--- a/invokeai/frontend/web/src/services/api/endpoints/queue.ts
+++ b/invokeai/frontend/web/src/services/api/endpoints/queue.ts
@@ -1,3 +1,4 @@
+import { getUserScopedQueueCounts } from 'features/queue/store/userScopedQueueCounts';
import queryString from 'query-string';
import type { components, paths } from 'services/api/schema';
import type {
@@ -433,5 +434,8 @@ export const enqueueMutationFixedCacheKeyOptions = {
export const useIsGenerationInProgress = () => {
const { data } = useGetQueueStatusQuery();
- return data && data.queue.in_progress > 0;
+ // In multiuser mode the global in_progress count includes other users' generations; this hook
+ // drives personal UI (the progress workspace tabs), so it must react only to the current
+ // user's own activity.
+ return data !== undefined && getUserScopedQueueCounts(data.queue).inProgress > 0;
};
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index f938b7f0f2..26ecd09dc4 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -2197,9 +2197,10 @@ export type paths = {
};
/**
* Get Queue Status
- * @description Gets the status of the session queue. Returns global counts; non-admin users additionally
- * get their own pending/in_progress counts (so the UI can show an X/Y badge) and cannot see the
- * current item's identifiers unless they own it.
+ * @description Gets the status of the session queue. Returns global counts; every user additionally gets
+ * their own pending/in_progress counts (so the UI can show an X/Y badge and scope personal UI
+ * like the progress bar to the user's own activity). Non-admin users cannot see the current
+ * item's identifiers unless they own it.
*/
get: operations["get_queue_status"];
put?: never;
@@ -24168,6 +24169,12 @@ export type components = {
* @default null
*/
submodel_type: components["schemas"]["SubModelType"] | null;
+ /**
+ * User Id
+ * @description The ID of the user whose action triggered the load
+ * @default system
+ */
+ user_id: string;
};
/**
* ModelLoadStartedEvent
@@ -24189,6 +24196,12 @@ export type components = {
* @default null
*/
submodel_type: components["schemas"]["SubModelType"] | null;
+ /**
+ * User Id
+ * @description The ID of the user whose action triggered the load
+ * @default system
+ */
+ user_id: string;
};
/**
* ModelLoaderOutput
@@ -25534,6 +25547,40 @@ export type components = {
*/
session_id: string;
};
+ /**
+ * QueueItemsCanceledEvent
+ * @description Event model for queue_items_canceled. Emitted when queue items are canceled or deleted in
+ * bulk (e.g. cancel/delete-all-except-current) without per-item status change events.
+ */
+ QueueItemsCanceledEvent: {
+ /**
+ * Timestamp
+ * @description The timestamp of the event
+ */
+ timestamp: number;
+ /**
+ * Queue Id
+ * @description The ID of the queue
+ */
+ queue_id: string;
+ /**
+ * Canceled Item Ids
+ * @description The IDs of the queue items that were canceled or deleted
+ */
+ canceled_item_ids: number[];
+ /**
+ * User Ids
+ * @description The IDs of the users who own the canceled queue items
+ */
+ user_ids: string[];
+ /**
+ * Canceled Item Ids By User
+ * @description The canceled queue item IDs keyed by owner user ID.
+ */
+ canceled_item_ids_by_user: {
+ [key: string]: number[];
+ };
+ };
/**
* QueueItemsRetriedEvent
* @description Event model for queue_items_retried
diff --git a/invokeai/frontend/web/src/services/events/eventScope.test.ts b/invokeai/frontend/web/src/services/events/eventScope.test.ts
new file mode 100644
index 0000000000..2fa9e11a1e
--- /dev/null
+++ b/invokeai/frontend/web/src/services/events/eventScope.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import { getEventScope, REDACTED_USER_ID } from './eventScope';
+
+const buildGetState = (user: { user_id: string; is_admin: boolean } | null, token: string | null = null) =>
+ (() => ({ auth: { user, token } })) as never;
+
+describe('getEventScope', () => {
+ it("classifies the current user's event as own", () => {
+ const getState = buildGetState({ user_id: 'user-1', is_admin: false }, 'token-1');
+ expect(getEventScope(getState, { user_id: 'user-1' })).toBe('own');
+ });
+
+ it("classifies another user's event as foreign", () => {
+ const getState = buildGetState({ user_id: 'admin-1', is_admin: true }, 'token-1');
+ expect(getEventScope(getState, { user_id: 'user-1' })).toBe('foreign');
+ });
+
+ it('classifies redacted companion events as sanitized, regardless of the current user', () => {
+ expect(getEventScope(buildGetState({ user_id: 'user-1', is_admin: false }), { user_id: REDACTED_USER_ID })).toBe(
+ 'sanitized'
+ );
+ expect(getEventScope(buildGetState(null), { user_id: REDACTED_USER_ID })).toBe('sanitized');
+ });
+
+ it('classifies every event as own in single-user mode (no token, no authenticated user)', () => {
+ const getState = buildGetState(null);
+ expect(getEventScope(getState, { user_id: 'anyone' })).toBe('own');
+ expect(getEventScope(getState, {})).toBe('own');
+ });
+
+ it('classifies events as foreign while multiuser auth is hydrating (token present, user not yet loaded)', () => {
+ // useSocketIO defers the socket connection until auth.user hydrates, so no events should
+ // arrive in this window — but if one does, it cannot be attributed yet and must not be
+ // treated as the client's own.
+ const getState = buildGetState(null, 'token-1');
+ expect(getEventScope(getState, { user_id: 'other-user' })).toBe('foreign');
+ expect(getEventScope(getState, { user_id: 'anyone' })).toBe('foreign');
+ });
+});
diff --git a/invokeai/frontend/web/src/services/events/eventScope.ts b/invokeai/frontend/web/src/services/events/eventScope.ts
new file mode 100644
index 0000000000..a33b22085b
--- /dev/null
+++ b/invokeai/frontend/web/src/services/events/eventScope.ts
@@ -0,0 +1,50 @@
+import type { AppGetState } from 'app/store/store';
+import { selectAuthToken, selectCurrentUser } from 'features/auth/store/authSlice';
+
+/**
+ * Who a socket event belongs to, relative to this client:
+ *
+ * - 'own': the current user's event. In single-user mode there is no authenticated user and every
+ * event is 'own'.
+ * - 'foreign': another user's event, carrying that user's real user_id. Admin clients receive
+ * these via the "admin" socket room; regular users never do.
+ * - 'sanitized': the redacted companion event the backend broadcasts to non-owner queue
+ * subscribers so their queue lists and badge counts stay in sync. Identified by the
+ * user_id="redacted" sentinel; identifiers and error fields are cleared. Only queue events
+ * (queue_item_status_changed, queue_cleared, queue_items_retried) have sanitized companions —
+ * invocation events are never sanitized.
+ */
+type EventScope = 'own' | 'foreign' | 'sanitized';
+
+export const REDACTED_USER_ID = 'redacted';
+
+/**
+ * Classifies a socket event by ownership. Listeners use this to route events: only 'own' events
+ * may drive personal UI state (progress, node execution states, gallery selection, toasts);
+ * 'foreign' and 'sanitized' events are limited to cache invalidation at most.
+ */
+export const getEventScope = (getState: AppGetState, data: { user_id?: string | null }): EventScope => {
+ if (data.user_id === REDACTED_USER_ID) {
+ return 'sanitized';
+ }
+ const state = getState();
+ const currentUser = selectCurrentUser(state);
+ if (!currentUser) {
+ // No authenticated user can mean two things:
+ //
+ // - Single-user mode: there is no auth token and auth.user never populates. Every event is
+ // the client's own.
+ // - Multiuser mode before hydration: useSocketIO defers the socket connection until
+ // auth.user has hydrated from /me, so no events should arrive in this window. Should one
+ // arrive anyway, it cannot be attributed yet — classify it as foreign (cache invalidation
+ // at most) rather than let an event that may be another user's drive personal UI.
+ // Ownership-driven one-shot side effects (progress, node execution states, gallery
+ // auto-switch, the failure toast) never replay, which is exactly why the connection is
+ // deferred instead of events being buffered here.
+ //
+ // The token distinguishes the two: it is hydrated synchronously from localStorage, and
+ // ProtectedRoute clears a stale token when the server reports single-user mode.
+ return selectAuthToken(state) ? 'foreign' : 'own';
+ }
+ return data.user_id === currentUser.user_id ? 'own' : 'foreign';
+};
diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts
new file mode 100644
index 0000000000..b9578ca1a2
--- /dev/null
+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts
@@ -0,0 +1,205 @@
+import { boardIdSelected, imageSelected } from 'features/gallery/store/gallerySlice';
+import { api } from 'services/api';
+import { getImageDTOSafe } from 'services/api/endpoints/images';
+import type { ImageDTO, S } from 'services/api/types';
+import { $lastProgressEvent } from 'services/events/stores';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ buildOnForeignInvocationComplete,
+ buildOnInvocationComplete,
+ FOREIGN_GALLERY_REFRESH_TAGS,
+} from './onInvocationComplete';
+
+vi.mock('app/logging/logger', () => ({
+ logger: () => ({
+ debug: vi.fn(),
+ trace: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+vi.mock('services/api', () => ({
+ LIST_TAG: 'LIST',
+ LIST_ALL_TAG: 'LIST_ALL',
+ api: {
+ util: {
+ invalidateTags: vi.fn((tags) => ({ type: 'api/invalidateTags', payload: tags })),
+ },
+ },
+}));
+
+vi.mock('services/api/endpoints/images', () => ({
+ getImageDTOSafe: vi.fn(),
+ imagesApi: {
+ util: {
+ updateQueryData: vi.fn(() => ({ type: 'imagesApi/updateQueryData' })),
+ invalidateTags: vi.fn(() => ({ type: 'imagesApi/invalidateTags' })),
+ },
+ },
+}));
+
+vi.mock('services/api/endpoints/boards', () => ({
+ boardsApi: {
+ endpoints: {
+ getBoardImagesTotal: {
+ select: vi.fn(() => () => ({ data: undefined })),
+ },
+ },
+ util: {
+ upsertQueryEntries: vi.fn(() => ({ type: 'boardsApi/upsertQueryEntries' })),
+ updateQueryData: vi.fn(() => ({ type: 'boardsApi/updateQueryData' })),
+ },
+ },
+}));
+
+vi.mock('services/api/endpoints/queue', () => ({
+ queueApi: {
+ util: {
+ invalidateTags: vi.fn(() => ({ type: 'queueApi/invalidateTags' })),
+ },
+ },
+}));
+
+vi.mock('features/gallery/store/gallerySelectors', () => ({
+ selectAutoSwitch: () => true,
+ selectGalleryView: () => 'images',
+ selectGetImageNamesQueryArgs: () => ({ search_term: '', starred_first: true, order_dir: 'DESC' }),
+ selectListBoardsQueryArgs: () => ({}),
+ selectSelectedBoardId: () => 'other-board',
+}));
+
+vi.mock('features/nodes/hooks/useNodeExecutionState', () => ({
+ $nodeExecutionStates: { get: () => ({}) },
+ upsertExecutionState: vi.fn(),
+}));
+
+vi.mock('features/controlLayers/store/canvasWorkflowIntegrationSlice', () => ({
+ canvasWorkflowIntegrationProcessingCompleted: vi.fn(() => ({
+ type: 'canvasWorkflowIntegration/processingCompleted',
+ })),
+}));
+
+vi.mock('services/events/nodeExecutionState', () => ({
+ getUpdatedNodeExecutionStateOnInvocationComplete: vi.fn(() => undefined),
+}));
+
+vi.mock('services/events/stores', () => ({
+ $lastProgressEvent: { set: vi.fn() },
+}));
+
+const imageDTO = {
+ image_name: 'img-1.png',
+ board_id: 'user-board',
+ is_intermediate: false,
+ image_category: 'general',
+} as ImageDTO;
+
+const buildEvent = (overrides: Record<string, unknown> = {}): S['InvocationCompleteEvent'] =>
+ ({
+ item_id: 1,
+ batch_id: 'batch-1',
+ session_id: 'session-1',
+ queue_id: 'default',
+ user_id: 'user-1',
+ origin: null,
+ destination: null,
+ invocation: { id: 'node-1', type: 'l2i' },
+ invocation_source_id: 'node-1',
+ result: { image: { image_name: imageDTO.image_name } },
+ ...overrides,
+ }) as unknown as S['InvocationCompleteEvent'];
+
+const dispatchedActionTypes = (dispatch: ReturnType<typeof vi.fn>) =>
+ dispatch.mock.calls.map(([action]) => (action as { type?: string }).type);
+
+describe('buildOnInvocationComplete gallery auto-switch', () => {
+ const buildHandler = () => {
+ const dispatch = vi.fn();
+ const getState = vi.fn(() => ({}));
+ const handler = buildOnInvocationComplete(getState as never, dispatch as never, new Map());
+ return { handler, dispatch };
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(getImageDTOSafe).mockResolvedValue(imageDTO);
+ });
+
+ // The socket listener routes only the current user's own events here (single-user mode included),
+ // so the handler runs unconditionally — ownership is decided upstream via getEventScope.
+ it('switches boards and clears the progress indicator when a generation completes', async () => {
+ const { handler, dispatch } = buildHandler();
+
+ await handler(buildEvent());
+
+ expect(dispatchedActionTypes(dispatch)).toContain(boardIdSelected.type);
+ expect($lastProgressEvent.set).toHaveBeenCalledWith(null);
+ });
+});
+
+describe('buildOnForeignInvocationComplete', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(getImageDTOSafe).mockResolvedValue(imageDTO);
+ });
+
+ it('refreshes gallery caches via tag invalidation only', () => {
+ const dispatch = vi.fn();
+ const handler = buildOnForeignInvocationComplete(dispatch as never);
+
+ handler(buildEvent());
+
+ // Exactly one dispatch: the tag invalidation. No optimistic cache edits, no board/image
+ // selection, no progress clear.
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(api.util.invalidateTags).toHaveBeenCalledWith(FOREIGN_GALLERY_REFRESH_TAGS);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'api/invalidateTags', payload: FOREIGN_GALLERY_REFRESH_TAGS });
+ expect(FOREIGN_GALLERY_REFRESH_TAGS).toEqual(
+ expect.arrayContaining(['ImageNameList', 'BoardImagesTotal', 'VirtualBoards'])
+ );
+
+ const types = dispatchedActionTypes(dispatch);
+ expect(types).not.toContain(boardIdSelected.type);
+ expect(types).not.toContain(imageSelected.type);
+ expect($lastProgressEvent.set).not.toHaveBeenCalled();
+ });
+
+ it('never fetches image DTOs', () => {
+ const dispatch = vi.fn();
+ const handler = buildOnForeignInvocationComplete(dispatch as never);
+
+ handler(buildEvent());
+
+ expect(getImageDTOSafe).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for results without image outputs', () => {
+ const dispatch = vi.fn();
+ const handler = buildOnForeignInvocationComplete(dispatch as never);
+
+ handler(buildEvent({ result: { latents: { latents_name: 'latents-1' } } }));
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for denylisted passthrough node types', () => {
+ const dispatch = vi.fn();
+ const handler = buildOnForeignInvocationComplete(dispatch as never);
+
+ handler(buildEvent({ invocation: { id: 'node-1', type: 'image' } }));
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for intermediate image outputs, which never appear in the gallery', () => {
+ const dispatch = vi.fn();
+ const handler = buildOnForeignInvocationComplete(dispatch as never);
+
+ handler(buildEvent({ invocation: { id: 'node-1', type: 'l2i', is_intermediate: true } }));
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx
index ea6a237d4b..13233a0c04 100644
--- a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx
+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx
@@ -11,7 +11,8 @@ import {
import { boardIdSelected, galleryViewChanged, imageSelected } from 'features/gallery/store/gallerySlice';
import { $nodeExecutionStates, upsertExecutionState } from 'features/nodes/hooks/useNodeExecutionState';
import { isImageField, isImageFieldCollection } from 'features/nodes/types/common';
-import { LIST_ALL_TAG } from 'services/api';
+import type { ApiTagDescription } from 'services/api';
+import { api, LIST_ALL_TAG, LIST_TAG } from 'services/api';
import { boardsApi } from 'services/api/endpoints/boards';
import { getImageDTOSafe, imagesApi } from 'services/api/endpoints/images';
import { queueApi } from 'services/api/endpoints/queue';
@@ -31,8 +32,10 @@ const log = logger('events');
const nodeTypeDenylist = ['load_image', 'image'];
/**
- * Builds the socket event handler for invocation complete events. Adds output images to the gallery and/or updates
- * node execution states for the workflow editor.
+ * Builds the socket event handler for the current user's own invocation complete events. Adds
+ * output images to the gallery and/or updates node execution states for the workflow editor.
+ * The listener routes other users' events to `buildOnForeignInvocationComplete` instead, so this
+ * handler never sees them.
*
* @param getState The Redux getState function.
* @param dispatch The Redux dispatch function.
@@ -274,3 +277,49 @@ export const buildOnInvocationComplete = (
$lastProgressEvent.set(null);
};
};
+
+/**
+ * Tags that refresh gallery queries after another user's generation completes. Type-level tags
+ * because a foreign event's destination board isn't known without fetching image DTOs. RTK Query
+ * only refetches invalidated queries that have active subscribers, so an admin actively viewing
+ * another user's board stays fresh while idle clients do no work.
+ */
+export const FOREIGN_GALLERY_REFRESH_TAGS: ApiTagDescription[] = [
+ 'ImageNameList',
+ 'BoardImagesTotal',
+ { type: 'Board', id: LIST_TAG },
+ 'VirtualBoards',
+];
+
+/**
+ * Builds the handler for other users' invocation complete events, which admin clients receive via
+ * the "admin" socket room. Unlike the user's own completions, these must not fetch image DTOs,
+ * edit caches optimistically, auto-switch the gallery, or touch the progress indicator — they
+ * only mark gallery caches stale so subscribed queries refetch.
+ */
+export const buildOnForeignInvocationComplete = (dispatch: AppDispatch) => {
+ return (data: S['InvocationCompleteEvent']) => {
+ if (nodeTypeDenylist.includes(data.invocation.type)) {
+ return;
+ }
+
+ // Intermediate images never appear in the gallery, so they cannot change any of the
+ // invalidated queries. Saved images inherit this flag from the node, so checking it on the
+ // event's invocation payload is equivalent to the own-event path's DTO check — without the
+ // fetch. Canvas generations mark most outputs intermediate, so this skips the bulk of
+ // foreign completions.
+ if (data.invocation.is_intermediate) {
+ return;
+ }
+
+ const hasImageOutput = objectEntries(data.result).some(
+ ([_name, value]) => isImageField(value) || isImageFieldCollection(value)
+ );
+ if (!hasImageOutput) {
+ return;
+ }
+
+ log.trace({ data } as JsonObject, `Foreign invocation complete (${data.invocation.type})`);
+ dispatch(api.util.invalidateTags(FOREIGN_GALLERY_REFRESH_TAGS));
+ };
+};
diff --git a/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx b/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx
new file mode 100644
index 0000000000..a7911a3612
--- /dev/null
+++ b/invokeai/frontend/web/src/services/events/onQueueItemStatusChanged.tsx
@@ -0,0 +1,162 @@
+import { logger } from 'app/logging/logger';
+import type { AppDispatch } from 'app/store/store';
+import ErrorToastDescription, { getTitle } from 'features/toast/ErrorToastDescription';
+import { toast } from 'features/toast/toast';
+import type { ApiTagDescription } from 'services/api';
+import { queueApi } from 'services/api/endpoints/queue';
+import type { S } from 'services/api/types';
+import { REDACTED_USER_ID } from 'services/events/eventScope';
+import { QUEUE_CHANGED_TAGS } from 'services/events/queueCacheTags';
+import { getUpdatedQueueStatusOnQueueItemStatusChanged } from 'services/events/queueStatusEvents';
+import { $lastProgressEvent } from 'services/events/stores';
+
+const log = logger('events');
+
+type QueueItemStatusChangedEvent = S['QueueItemStatusChangedEvent'];
+
+type Coordinator = {
+ onQueueItemStatusChanged: (data: QueueItemStatusChangedEvent) => boolean;
+};
+
+/**
+ * Builds the handler for the current user's own queue_item_status_changed events: optimistic
+ * queue cache updates, tag invalidation, the failure toast, and clearing the progress indicator
+ * on terminal statuses. The listener routes non-owner events to
+ * `buildOnNonOwnerQueueItemStatusChanged` instead, so this handler never sees them.
+ */
+export const buildOnQueueItemStatusChanged = (dispatch: AppDispatch, coordinator: Coordinator) => {
+ return (data: QueueItemStatusChangedEvent) => {
+ if (!coordinator.onQueueItemStatusChanged(data)) {
+ return;
+ }
+
+ // we've got new status for the queue item, batch and queue
+ const {
+ item_id,
+ status,
+ status_sequence,
+ batch_status,
+ error_type,
+ error_message,
+ destination,
+ started_at,
+ updated_at,
+ completed_at,
+ error_traceback,
+ } = data;
+
+ log.debug({ data }, `Queue item ${item_id} status updated: ${status}`);
+
+ // Update this specific queue item in the list of queue items
+ dispatch(
+ queueApi.util.updateQueryData('getQueueItem', item_id, (draft) => {
+ draft.status = status;
+ draft.status_sequence = status_sequence;
+ draft.started_at = started_at;
+ draft.updated_at = updated_at;
+ draft.completed_at = completed_at;
+ draft.error_type = error_type;
+ draft.error_message = error_message;
+ draft.error_traceback = error_traceback;
+ })
+ );
+
+ // Optimistically update the listAllQueueItems cache for this destination so the canvas
+ // staging area immediately reflects status changes without waiting for a tag-based refetch
+ if (destination) {
+ dispatch(
+ queueApi.util.updateQueryData('listAllQueueItems', { destination }, (draft) => {
+ const item = draft.find((i) => i.item_id === item_id);
+ if (item) {
+ item.status = status;
+ item.status_sequence = status_sequence;
+ item.started_at = started_at;
+ item.updated_at = updated_at;
+ item.completed_at = completed_at;
+ item.error_type = error_type;
+ item.error_message = error_message;
+ item.error_traceback = error_traceback;
+ }
+ })
+ );
+ }
+ dispatch(
+ queueApi.util.updateQueryData('getQueueStatus', undefined, (draft) =>
+ getUpdatedQueueStatusOnQueueItemStatusChanged(draft, data)
+ )
+ );
+
+ // Invalidate caches for things we cannot easily update
+ //
+ // SessionQueueStatus stays in this list even though the optimistic write above already
+ // applied the event's counts (including the owner's per-user counts): the refetch is what
+ // refreshes the processor half of the response — the optimistic write only touches .queue,
+ // never .processor (is_started/is_processing, read by the pause/resume controls) — and it
+ // reconciles drift from missed or out-of-order events (getQueueStatusWithObservedEvents
+ // exists to arbitrate exactly that refetch-vs-event race). Do not remove it as "redundant".
+ const tagsToInvalidate: ApiTagDescription[] = [
+ ...QUEUE_CHANGED_TAGS,
+ 'InvocationCacheStatus',
+ { type: 'SessionQueueItem', id: item_id },
+ { type: 'BatchStatus', id: batch_status.batch_id },
+ ];
+ if (destination) {
+ tagsToInvalidate.push({ type: 'QueueCountsByDestination', id: destination });
+ }
+ dispatch(queueApi.util.invalidateTags(tagsToInvalidate));
+
+ if (status === 'completed' || status === 'failed' || status === 'canceled') {
+ if (status === 'failed' && error_type) {
+ toast({
+ id: `INVOCATION_ERROR_${error_type}`,
+ title: getTitle(error_type),
+ status: 'error',
+ duration: null,
+ updateDescription: true,
+ description: <ErrorToastDescription errorType={error_type} errorMessage={error_message} />,
+ });
+ }
+ // If the queue item is completed, failed, or cancelled, we want to clear the last progress event
+ $lastProgressEvent.set(null);
+ }
+ };
+};
+
+/**
+ * Builds the handler for queue_item_status_changed events that are not the current user's own.
+ * Two kinds land here in multiuser mode:
+ *
+ * 1. The sanitized companion the backend broadcasts to other queue subscribers, with
+ * user_id="redacted" and identifiers/error fields cleared.
+ * 2. Another user's full event, received by admins via the "admin" room (the backend skips owner
+ * and admin sids when broadcasting the sanitized companion, so admins only ever get the full
+ * one).
+ *
+ * In neither case may we run payload-driven cache mutations or per-session side effects — node
+ * state reset, progress clear, completion bookkeeping, workflow reconciliation, or the failure
+ * toast — those belong to the owner. Cache invalidation is the only permitted effect, but it must
+ * cover everything the owner path covers: admin UI also renders the current/next queue item (the
+ * cancel-current button), batch statuses, and the destination queue counts that back the canvas,
+ * and for admins those queries span all users' items. The admin-room full event carries real ids,
+ * so its batch and destination caches are invalidated narrowly; the sanitized companion redacts
+ * batch_id and nulls destination, so only it falls back to the type-level tags.
+ */
+export const buildOnNonOwnerQueueItemStatusChanged = (dispatch: AppDispatch) => {
+ return (data: QueueItemStatusChangedEvent) => {
+ log.trace({ data }, `Non-owner queue_item_status_changed for item ${data.item_id}`);
+ const tags: ApiTagDescription[] = [
+ ...QUEUE_CHANGED_TAGS,
+ 'InvocationCacheStatus',
+ { type: 'SessionQueueItem', id: data.item_id },
+ ];
+ if (data.user_id === REDACTED_USER_ID) {
+ tags.push('BatchStatus', 'QueueCountsByDestination');
+ } else {
+ tags.push({ type: 'BatchStatus', id: data.batch_status.batch_id });
+ if (data.destination) {
+ tags.push({ type: 'QueueCountsByDestination', id: data.destination });
+ }
+ }
+ dispatch(queueApi.util.invalidateTags(tags));
+ };
+};
diff --git a/invokeai/frontend/web/src/services/events/queueCacheTags.ts b/invokeai/frontend/web/src/services/events/queueCacheTags.ts
new file mode 100644
index 0000000000..0011fb1d50
--- /dev/null
+++ b/invokeai/frontend/web/src/services/events/queueCacheTags.ts
@@ -0,0 +1,19 @@
+import type { ApiTagDescription } from 'services/api';
+import { LIST_ALL_TAG, LIST_TAG } from 'services/api';
+
+/**
+ * The queue caches that every queue-changing socket event must refetch. Shared by the
+ * queue_item_status_changed (owner and non-owner), queue_cleared, batch_enqueued, and bulk
+ * retried/canceled handlers: each spreads this base and appends its event-specific tags
+ * (id-scoped BatchStatus / QueueCountsByDestination, per-item SessionQueueItem ids, etc.).
+ * Keeping the shared core in one place prevents the handlers drifting apart when a new queue
+ * cache is added — one class of recipient silently missing an invalidation is a stale-UI bug.
+ */
+export const QUEUE_CHANGED_TAGS: readonly ApiTagDescription[] = [
+ 'SessionQueueStatus',
+ 'CurrentSessionQueueItem',
+ 'NextSessionQueueItem',
+ 'SessionQueueItemIdList',
+ { type: 'SessionQueueItem', id: LIST_TAG },
+ { type: 'SessionQueueItem', id: LIST_ALL_TAG },
+];
diff --git a/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts b/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts
index 9c7dab37c9..e26e351450 100644
--- a/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts
+++ b/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts
@@ -65,6 +65,34 @@ describe(getUpdatedQueueStatusOnQueueItemStatusChanged.name, () => {
processor: current.processor,
});
});
+
+ it('retains the cached per-user counts when the event queue status carries none', () => {
+ // e.g. a sanitized status (user counts nulled by the backend): the cached counts must not be
+ // lost, else personal UI falls back to the global counts and reacts to other users' activity.
+ const current = buildQueueStatus({ user_pending: 0, user_in_progress: 0 });
+ const event = buildQueueStatusChangedEvent();
+
+ const updated = getUpdatedQueueStatusOnQueueItemStatusChanged(current, event);
+
+ expect(updated.queue.user_pending).toBe(0);
+ expect(updated.queue.user_in_progress).toBe(0);
+ expect(updated.queue.completed).toBe(1);
+ });
+
+ it("prefers the event's per-user counts when it carries them", () => {
+ // The owner's full event embeds the owner's fresh per-user counts, so personal UI (progress
+ // bar, spinner, favicon) must update from the event immediately — e.g. the spinner stops the
+ // moment the user's last item completes, not a refetch round-trip later.
+ const current = buildQueueStatus({ user_pending: 1, user_in_progress: 1 });
+ const event = buildQueueStatusChangedEvent();
+ event.queue_status.user_pending = 0;
+ event.queue_status.user_in_progress = 0;
+
+ const updated = getUpdatedQueueStatusOnQueueItemStatusChanged(current, event);
+
+ expect(updated.queue.user_pending).toBe(0);
+ expect(updated.queue.user_in_progress).toBe(0);
+ });
});
describe(getQueueStatusWithObservedEvents.name, () => {
diff --git a/invokeai/frontend/web/src/services/events/queueStatusEvents.ts b/invokeai/frontend/web/src/services/events/queueStatusEvents.ts
index 01b635a3ad..1f8613b309 100644
--- a/invokeai/frontend/web/src/services/events/queueStatusEvents.ts
+++ b/invokeai/frontend/web/src/services/events/queueStatusEvents.ts
@@ -41,12 +41,29 @@ const recordQueueItemStatusChangedEvent = (event: QueueItemStatusChangedEvent):
latestObservedQueueStatus = event.queue_status;
};
+/**
+ * The queue status embedded in a full queue_item_status_changed event carries the OWNER's
+ * per-user counts, so the owner's optimistic cache write below is complete and personal UI
+ * (progress bar, spinner, favicon) updates without waiting for a refetch. Statuses without
+ * per-user counts still occur — the sanitized companion nulls them — and for those, retain the
+ * previous cached per-user counts: for a non-owner recipient they are still accurate, and the
+ * tag invalidation that accompanies every status change refetches fresh counts immediately.
+ */
+const withRetainedUserCounts = (
+ next: S['SessionQueueStatus'],
+ previous: S['SessionQueueStatus']
+): S['SessionQueueStatus'] => ({
+ ...next,
+ user_pending: next.user_pending ?? previous.user_pending,
+ user_in_progress: next.user_in_progress ?? previous.user_in_progress,
+});
+
export const getQueueStatusWithObservedEvents = (queueStatus: QueueStatusResponse): QueueStatusResponse => {
const currentItemId = queueStatus.queue.item_id;
if (latestObservedQueueStatus && currentItemId !== null && observedTerminalItemIds.has(currentItemId)) {
return {
...queueStatus,
- queue: latestObservedQueueStatus,
+ queue: withRetainedUserCounts(latestObservedQueueStatus, queueStatus.queue),
};
}
@@ -60,7 +77,7 @@ export const getUpdatedQueueStatusOnQueueItemStatusChanged = (
recordQueueItemStatusChangedEvent(event);
return {
...queueStatus,
- queue: event.queue_status,
+ queue: withRetainedUserCounts(event.queue_status, queueStatus.queue),
};
};
diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.test.ts b/invokeai/frontend/web/src/services/events/setEventListeners.test.ts
index 5b69bc49f6..10f8aa4438 100644
--- a/invokeai/frontend/web/src/services/events/setEventListeners.test.ts
+++ b/invokeai/frontend/web/src/services/events/setEventListeners.test.ts
@@ -1,7 +1,10 @@
+import { $nodeExecutionStates } from 'features/nodes/hooks/useNodeExecutionState';
+import { toast } from 'features/toast/toast';
import { LIST_TAG } from 'services/api';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { setEventListeners } from './setEventListeners';
+import { $lastProgressEvent } from './stores';
vi.mock('app/logging/logger', () => ({
logger: () => ({
@@ -17,8 +20,22 @@ vi.mock('features/toast/toast', () => ({
toast: vi.fn(),
}));
+// Expose the built handlers and the completed-invocation tracking map that setEventListeners
+// hands to both the coordinator and the gallery handler, so tests can assert routing: own events
+// reach the own handler via the coordinator, foreign events reach only the foreign handler.
+const mockOnInvocationComplete = vi.fn();
+const mockOnForeignInvocationComplete = vi.fn();
+let capturedCompletedInvocationKeys: Map<number, Set<string>> | null = null;
vi.mock('./onInvocationComplete', () => ({
- buildOnInvocationComplete: () => vi.fn(),
+ buildOnInvocationComplete: (
+ _getState: unknown,
+ _dispatch: unknown,
+ completedInvocationKeysByItemId: Map<number, Set<string>>
+ ) => {
+ capturedCompletedInvocationKeys = completedInvocationKeysByItemId;
+ return mockOnInvocationComplete;
+ },
+ buildOnForeignInvocationComplete: () => mockOnForeignInvocationComplete,
}));
vi.mock('./onModelInstallError', () => ({
@@ -298,3 +315,330 @@ describe('setEventListeners workflow live updates', () => {
);
});
});
+
+/**
+ * In multiuser mode admins are subscribed to the "admin" socket room and receive every user's
+ * invocation and queue-item events, carrying that user's real user_id. None of them may drive this
+ * client's local execution/progress state. The routing happens at the socket listener, before the
+ * workflow execution coordinator records the event, so these tests drive the real listeners + real
+ * coordinator rather than calling a downstream handler directly.
+ */
+describe('setEventListeners cross-user isolation', () => {
+ const ADMIN_USER = { user_id: 'admin-1', is_admin: true };
+ const FOREIGN_USER_ID = 'other-user';
+ const NODE_ID = 'node-1';
+
+ const buildInvocationEvent = (overrides: Record<string, unknown> = {}) => ({
+ queue_id: 'default',
+ item_id: 99,
+ batch_id: 'batch-foreign',
+ session_id: 'sess-foreign',
+ invocation: { id: 'inv-1', type: 'some_node' },
+ invocation_source_id: NODE_ID,
+ origin: 'workflows',
+ destination: 'canvas',
+ user_id: FOREIGN_USER_ID,
+ ...overrides,
+ });
+
+ const buildQueueItemStatusChangedEvent = (overrides: Record<string, unknown> = {}) => ({
+ queue_id: 'default',
+ item_id: 99,
+ batch_id: 'batch-foreign',
+ session_id: 'sess-foreign',
+ origin: 'workflows',
+ destination: 'canvas',
+ user_id: FOREIGN_USER_ID,
+ status: 'in_progress',
+ status_sequence: 1,
+ error_type: null,
+ error_message: null,
+ error_traceback: null,
+ created_at: '2026-01-01T00:00:00',
+ updated_at: '2026-01-01T00:01:00',
+ started_at: '2026-01-01T00:00:30',
+ completed_at: null,
+ batch_status: { queue_id: 'default', batch_id: 'batch-foreign', origin: 'workflows', destination: 'canvas' },
+ queue_status: { queue_id: 'default' },
+ ...overrides,
+ });
+
+ /**
+ * A node execution state the admin owns locally, sharing a node id with the foreign workflow —
+ * common node ids make this realistic. Seeded PENDING (i.e. not running) so that any
+ * foreign-driven transition to IN_PROGRESS/FAILED/COMPLETED changes the object and is visible to
+ * a toEqual assertion.
+ */
+ const seedNodeExecutionState = () => {
+ const state = {
+ nodeId: NODE_ID,
+ status: 'PENDING',
+ progress: null,
+ progressImage: null,
+ outputs: [],
+ error: null,
+ } as never;
+ $nodeExecutionStates.set({ [NODE_ID]: state });
+ return state;
+ };
+
+ const seedProgressEvent = () => {
+ const progress = { queue_id: 'default', item_id: 1, user_id: ADMIN_USER.user_id } as never;
+ $lastProgressEvent.set(progress);
+ return progress;
+ };
+
+ const setup = (user: { user_id: string; is_admin: boolean } | null) => {
+ const socket = createMockSocket();
+ const dispatch = vi.fn();
+ setEventListeners({
+ socket: socket as never,
+ store: { dispatch, getState: vi.fn(() => ({ auth: { user } })) } as never,
+ setIsConnected: vi.fn(),
+ });
+ return { socket, dispatch };
+ };
+
+ beforeEach(() => {
+ mockOnInvocationComplete.mockReset();
+ mockOnForeignInvocationComplete.mockReset();
+ vi.mocked(toast).mockReset();
+ capturedCompletedInvocationKeys = null;
+ $nodeExecutionStates.set({});
+ $lastProgressEvent.set(null);
+ });
+
+ it.each(['invocation_started', 'invocation_progress', 'invocation_error'])(
+ "drops another user's %s for an authenticated admin",
+ (eventName) => {
+ const seededNodeState = seedNodeExecutionState();
+ const seededProgress = seedProgressEvent();
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ socket.trigger(
+ eventName,
+ buildInvocationEvent({
+ // canvas origin would otherwise stop the admin's own integration spinner
+ origin: 'canvas_workflow_integration',
+ percentage: 0.9,
+ error_type: 'RuntimeError',
+ error_message: 'boom',
+ })
+ );
+
+ // Node execution state must not be created, overwritten, or reset.
+ expect($nodeExecutionStates.get()).toEqual({ [NODE_ID]: seededNodeState });
+ // The admin's own progress event must survive.
+ expect($lastProgressEvent.get()).toBe(seededProgress);
+ // No canvas processing clear, and no gallery/completion handling.
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(mockOnInvocationComplete).not.toHaveBeenCalled();
+ // Completed-invocation tracking must stay empty.
+ expect(capturedCompletedInvocationKeys?.size ?? 0).toBe(0);
+ }
+ );
+
+ it("routes another user's invocation_complete to the foreign gallery handler only", () => {
+ const seededNodeState = seedNodeExecutionState();
+ const seededProgress = seedProgressEvent();
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ const event = buildInvocationEvent({
+ origin: 'canvas_workflow_integration',
+ result: { image: { image_name: 'foreign.png' } },
+ });
+ socket.trigger('invocation_complete', event);
+
+ // The foreign handler is responsible for the (invalidate-only) gallery refresh...
+ expect(mockOnForeignInvocationComplete).toHaveBeenCalledWith(event);
+ // ...while the coordinator and the own-event handler never see the event, and no personal
+ // state is touched.
+ expect(mockOnInvocationComplete).not.toHaveBeenCalled();
+ expect($nodeExecutionStates.get()).toEqual({ [NODE_ID]: seededNodeState });
+ expect($lastProgressEvent.get()).toBe(seededProgress);
+ expect(capturedCompletedInvocationKeys?.size ?? 0).toBe(0);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("does not create node execution state for a foreign workflow's node", () => {
+ // getUpdatedNodeExecutionStateOnInvocationStarted() creates state even when none existed, so an
+ // unfiltered foreign event would materialize a node the admin's editor does not have.
+ $nodeExecutionStates.set({});
+ const { socket } = setup(ADMIN_USER);
+
+ socket.trigger('invocation_started', buildInvocationEvent({ invocation_source_id: 'foreign-node' }));
+
+ expect($nodeExecutionStates.get()).toEqual({});
+ });
+
+ it("ignores another user's full queue_item_status_changed except for queue cache invalidation", () => {
+ const seededNodeState = seedNodeExecutionState();
+ const seededProgress = seedProgressEvent();
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ // in_progress would reset the admin's node states via the coordinator
+ socket.trigger('queue_item_status_changed', buildQueueItemStatusChangedEvent({ status: 'in_progress' }));
+
+ expect($nodeExecutionStates.get()).toEqual({ [NODE_ID]: seededNodeState });
+ expect($lastProgressEvent.get()).toBe(seededProgress);
+ expect(capturedCompletedInvocationKeys?.size ?? 0).toBe(0);
+
+ // The admin's queue list/badge still refetch, but only via tag invalidation — no payload-driven
+ // optimistic cache writes and no reconciliation request for the other user's item.
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ payload: expect.arrayContaining(['SessionQueueStatus']) })
+ );
+ });
+
+ it('routes a sanitized queue_item_status_changed to the same invalidate-only branch', () => {
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ socket.trigger('queue_item_status_changed', buildQueueItemStatusChangedEvent({ user_id: 'redacted' }));
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ payload: expect.arrayContaining(['SessionQueueStatus']) })
+ );
+ });
+
+ it("invalidates id-scoped batch and destination tags for another user's full event", () => {
+ // The admin-room copy of another user's event carries real ids — the handler must not blow
+ // away every BatchStatus/QueueCountsByDestination query on a busy multi-user server.
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ socket.trigger('queue_item_status_changed', buildQueueItemStatusChangedEvent());
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ const { payload } = dispatch.mock.calls[0]?.[0] as { payload: unknown[] };
+ expect(payload).toEqual(
+ expect.arrayContaining([
+ { type: 'BatchStatus', id: 'batch-foreign' },
+ { type: 'QueueCountsByDestination', id: 'canvas' },
+ ])
+ );
+ expect(payload).not.toContain('BatchStatus');
+ expect(payload).not.toContain('QueueCountsByDestination');
+ });
+
+ it('falls back to type-level batch and destination tags for the sanitized companion', () => {
+ // The sanitized companion redacts batch_id and nulls destination, so only the type-level
+ // tags can match the caches these ids would otherwise identify.
+ const { socket, dispatch } = setup(ADMIN_USER);
+
+ socket.trigger(
+ 'queue_item_status_changed',
+ buildQueueItemStatusChangedEvent({
+ user_id: 'redacted',
+ batch_id: 'redacted',
+ destination: null,
+ batch_status: { queue_id: 'default', batch_id: 'redacted', origin: null, destination: null },
+ })
+ );
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ const { payload } = dispatch.mock.calls[0]?.[0] as { payload: unknown[] };
+ expect(payload).toEqual(expect.arrayContaining(['BatchStatus', 'QueueCountsByDestination']));
+ });
+
+ it("does not toast or clear progress on another user's failed queue item", () => {
+ const seededProgress = seedProgressEvent();
+ const { socket } = setup(ADMIN_USER);
+
+ socket.trigger(
+ 'queue_item_status_changed',
+ buildQueueItemStatusChangedEvent({ status: 'failed', error_type: 'RuntimeError', error_message: 'boom' })
+ );
+
+ expect(toast).not.toHaveBeenCalled();
+ expect($lastProgressEvent.get()).toBe(seededProgress);
+ });
+
+ it("still processes the admin's own invocation_progress", () => {
+ const { socket } = setup(ADMIN_USER);
+ const own = buildInvocationEvent({ user_id: ADMIN_USER.user_id, percentage: 0.5 });
+
+ socket.trigger('invocation_progress', own);
+
+ expect($lastProgressEvent.get()).toEqual(own);
+ });
+
+ it("routes the admin's own invocation_complete to the own-event handler", () => {
+ const { socket } = setup(ADMIN_USER);
+ const own = buildInvocationEvent({ user_id: ADMIN_USER.user_id, result: {} });
+
+ socket.trigger('invocation_complete', own);
+
+ expect(mockOnInvocationComplete).toHaveBeenCalledWith(own);
+ expect(mockOnForeignInvocationComplete).not.toHaveBeenCalled();
+ });
+
+ it('still processes events in single-user mode, where there is no authenticated user', () => {
+ const { socket } = setup(null);
+ const own = buildInvocationEvent({ user_id: 'system', percentage: 0.5 });
+
+ socket.trigger('invocation_progress', own);
+
+ expect($lastProgressEvent.get()).toEqual(own);
+ });
+});
+
+/**
+ * A bulk cancel/delete (e.g. cancel-all-except-current) emits no per-item
+ * queue_item_status_changed, so queue_items_canceled is the only signal that pending items left
+ * the queue. Regression: an admin's cancel-all-except-current left other users' badges stale.
+ */
+describe('setEventListeners queue_items_canceled', () => {
+ const setup = () => {
+ const socket = createMockSocket();
+ const dispatch = vi.fn();
+ setEventListeners({
+ socket: socket as never,
+ store: {
+ dispatch,
+ getState: vi.fn(() => ({ auth: { user: { user_id: 'user-a', is_admin: false } } })),
+ } as never,
+ setIsConnected: vi.fn(),
+ });
+ return { socket, dispatch };
+ };
+
+ it('refetches queue caches, including each canceled item, when the full event names item ids', () => {
+ const { socket, dispatch } = setup();
+
+ socket.trigger('queue_items_canceled', {
+ queue_id: 'default',
+ canceled_item_ids: [42, 43],
+ user_ids: ['user-a'],
+ canceled_item_ids_by_user: { 'user-a': [42, 43] },
+ });
+
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.arrayContaining([
+ 'SessionQueueStatus',
+ 'SessionQueueItemIdList',
+ { type: 'SessionQueueItem', id: 42 },
+ { type: 'SessionQueueItem', id: 43 },
+ ]),
+ })
+ );
+ });
+
+ it('still refetches queue caches for the sanitized companion, which names no item ids', () => {
+ const { socket, dispatch } = setup();
+
+ socket.trigger('queue_items_canceled', {
+ queue_id: 'default',
+ canceled_item_ids: [],
+ user_ids: [],
+ canceled_item_ids_by_user: {},
+ });
+
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.arrayContaining(['SessionQueueStatus', 'SessionQueueItemIdList']),
+ })
+ );
+ });
+});
diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.tsx b/invokeai/frontend/web/src/services/events/setEventListeners.tsx
index 21f475f46b..c8066e235d 100644
--- a/invokeai/frontend/web/src/services/events/setEventListeners.tsx
+++ b/invokeai/frontend/web/src/services/events/setEventListeners.tsx
@@ -30,18 +30,22 @@ import { $nodeExecutionStates, upsertExecutionState } from 'features/nodes/hooks
import { fieldValueReset } from 'features/nodes/store/nodesSlice';
import { selectNodesSlice } from 'features/nodes/store/selectors';
import { modelSelected } from 'features/parameters/store/actions';
-import ErrorToastDescription, { getTitle } from 'features/toast/ErrorToastDescription';
import { toast, toastApi } from 'features/toast/toast';
import { t } from 'i18next';
import { Trans } from 'react-i18next';
import type { ApiTagDescription } from 'services/api';
-import { api, LIST_ALL_TAG, LIST_TAG } from 'services/api';
+import { api, LIST_TAG } from 'services/api';
import { imagesApi } from 'services/api/endpoints/images';
import { modelsApi } from 'services/api/endpoints/models';
import { queueApi } from 'services/api/endpoints/queue';
-import { buildOnInvocationComplete } from 'services/events/onInvocationComplete';
+import { getEventScope } from 'services/events/eventScope';
+import { buildOnForeignInvocationComplete, buildOnInvocationComplete } from 'services/events/onInvocationComplete';
import { buildOnModelInstallError, DiscordLink, GitHubIssuesLink } from 'services/events/onModelInstallError';
-import { getUpdatedQueueStatusOnQueueItemStatusChanged } from 'services/events/queueStatusEvents';
+import {
+ buildOnNonOwnerQueueItemStatusChanged,
+ buildOnQueueItemStatusChanged,
+} from 'services/events/onQueueItemStatusChanged';
+import { QUEUE_CHANGED_TAGS } from 'services/events/queueCacheTags';
import type { ClientToServerEvents, ServerToClientEvents } from 'services/events/types';
import { createWorkflowExecutionCoordinator } from 'services/events/workflowExecutionCoordinator';
import type { Socket } from 'socket.io-client';
@@ -84,6 +88,10 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
upsertNodeExecutionState: upsertExecutionState,
});
+ const onForeignInvocationComplete = buildOnForeignInvocationComplete(dispatch);
+ const onQueueItemStatusChanged = buildOnQueueItemStatusChanged(dispatch, workflowExecutionCoordinator);
+ const onNonOwnerQueueItemStatusChanged = buildOnNonOwnerQueueItemStatusChanged(dispatch);
+
socket.on('connect', () => {
log.debug('Connected');
setIsConnected(true);
@@ -172,20 +180,43 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
socket.on('workflow_access_revoked', (data) => {
log.debug({ data }, 'Workflow access revoked');
invalidateWorkflowLibrary();
- const currentUser = getState().auth.user;
+ const currentUser = selectCurrentUser(getState());
if (currentUser?.is_admin || currentUser?.user_id === data.user_id) {
return;
}
clearSavedWorkflowSelection(data.workflow_id);
});
+ // In multiuser mode, admins are subscribed to the "admin" socket room and receive invocation
+ // and queue item events for *every* user, carrying that user's real user_id. Another user's
+ // events must not drive this client's personal state: the workflow execution coordinator, node
+ // execution states, canvas workflow integration processing, completed-invocation bookkeeping,
+ // or $lastProgressEvent. Ownership is decided here at the listener — before the coordinator
+ // records anything — so each handler only ever sees the events it owns:
+ //
+ // - Foreign invocation_started/progress/error are dropped. (The backend already routes progress
+ // to the owner's room only; the client-side check is defense in depth.)
+ // - A foreign invocation_complete downgrades to a cache-invalidation-only gallery refresh so an
+ // admin viewing another user's board stays fresh without optimistic cache work or DTO fetches.
+ // - A non-owner queue_item_status_changed (sanitized companion or admin-room copy) only
+ // invalidates queue tags.
+ //
+ // In single-user mode there is no authenticated user and every event is 'own'.
socket.on('invocation_started', (data) => {
+ if (getEventScope(getState, data) !== 'own') {
+ log.trace({ data } as JsonObject, `Ignoring invocation_started for another user (${data.user_id})`);
+ return;
+ }
const { invocation_source_id, invocation } = data;
log.debug({ data } as JsonObject, `Invocation started (${invocation.type}, ${invocation_source_id})`);
workflowExecutionCoordinator.onInvocationStarted(data);
});
socket.on('invocation_progress', (data) => {
+ if (getEventScope(getState, data) !== 'own') {
+ log.trace({ data } as JsonObject, `Ignoring invocation_progress for another user (${data.user_id})`);
+ return;
+ }
if (!workflowExecutionCoordinator.onInvocationProgress(data)) {
log.trace({ data } as JsonObject, `Received event for already-finished queue item ${data.item_id}`);
return;
@@ -207,13 +238,21 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
});
socket.on('invocation_error', (data) => {
+ if (getEventScope(getState, data) !== 'own') {
+ log.trace({ data } as JsonObject, `Ignoring invocation_error for another user (${data.user_id})`);
+ return;
+ }
const { invocation_source_id, invocation } = data;
log.error({ data } as JsonObject, `Invocation error (${invocation.type}, ${invocation_source_id})`);
workflowExecutionCoordinator.onInvocationError(data);
});
socket.on('invocation_complete', (data) => {
- workflowExecutionCoordinator.onInvocationComplete(data);
+ if (getEventScope(getState, data) === 'own') {
+ workflowExecutionCoordinator.onInvocationComplete(data);
+ } else {
+ onForeignInvocationComplete(data);
+ }
});
socket.on('model_load_started', (data) => {
@@ -426,115 +465,10 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
});
socket.on('queue_item_status_changed', (data) => {
- // Sanitized companion event sent to non-owner queue subscribers in multiuser mode. The
- // backend sets user_id="redacted" and clears identifiers/error fields. We must not run
- // payload-driven cache mutations or per-session side effects (node state reset, progress
- // clear, completion bookkeeping) — those belong to the owner. Just invalidate queue tags
- // so the non-owner's queue list and badge counts refetch with sanitized data.
- if (data.user_id === 'redacted') {
- log.trace({ data }, `Sanitized queue_item_status_changed for item ${data.item_id}`);
- const tags: ApiTagDescription[] = [
- 'SessionQueueStatus',
- 'SessionQueueItemIdList',
- { type: 'SessionQueueItem', id: data.item_id },
- { type: 'SessionQueueItem', id: LIST_TAG },
- { type: 'SessionQueueItem', id: LIST_ALL_TAG },
- ];
- dispatch(queueApi.util.invalidateTags(tags));
- return;
- }
-
- if (!workflowExecutionCoordinator.onQueueItemStatusChanged(data)) {
- return;
- }
-
- // we've got new status for the queue item, batch and queue
- const {
- item_id,
- status,
- status_sequence,
- batch_status,
- error_type,
- error_message,
- destination,
- started_at,
- updated_at,
- completed_at,
- error_traceback,
- } = data;
-
- log.debug({ data }, `Queue item ${item_id} status updated: ${status}`);
-
- // // Update this specific queue item in the list of queue items
- dispatch(
- queueApi.util.updateQueryData('getQueueItem', item_id, (draft) => {
- draft.status = status;
- draft.status_sequence = status_sequence;
- draft.started_at = started_at;
- draft.updated_at = updated_at;
- draft.completed_at = completed_at;
- draft.error_type = error_type;
- draft.error_message = error_message;
- draft.error_traceback = error_traceback;
- })
- );
-
- // Optimistically update the listAllQueueItems cache for this destination so the canvas
- // staging area immediately reflects status changes without waiting for a tag-based refetch
- if (destination) {
- dispatch(
- queueApi.util.updateQueryData('listAllQueueItems', { destination }, (draft) => {
- const item = draft.find((i) => i.item_id === item_id);
- if (item) {
- item.status = status;
- item.status_sequence = status_sequence;
- item.started_at = started_at;
- item.updated_at = updated_at;
- item.completed_at = completed_at;
- item.error_type = error_type;
- item.error_message = error_message;
- item.error_traceback = error_traceback;
- }
- })
- );
- }
- dispatch(
- queueApi.util.updateQueryData('getQueueStatus', undefined, (draft) =>
- getUpdatedQueueStatusOnQueueItemStatusChanged(draft, data)
- )
- );
-
- // Invalidate caches for things we cannot easily update
- // Invalidate SessionQueueStatus to refetch with user-specific counts
- const tagsToInvalidate: ApiTagDescription[] = [
- 'CurrentSessionQueueItem',
- 'NextSessionQueueItem',
- 'InvocationCacheStatus',
- 'SessionQueueStatus',
- 'SessionQueueItemIdList',
- { type: 'SessionQueueItem', id: item_id },
- { type: 'SessionQueueItem', id: LIST_TAG },
- { type: 'SessionQueueItem', id: LIST_ALL_TAG },
- { type: 'BatchStatus', id: batch_status.batch_id },
- ];
- if (destination) {
- tagsToInvalidate.push({ type: 'QueueCountsByDestination', id: destination });
- }
- dispatch(queueApi.util.invalidateTags(tagsToInvalidate));
-
- if (status === 'completed' || status === 'failed' || status === 'canceled') {
- if (status === 'failed' && error_type) {
- toast({
- id: `INVOCATION_ERROR_${error_type}`,
- title: getTitle(error_type),
- status: 'error',
- duration: null,
- updateDescription: true,
- description: <ErrorToastDescription errorType={error_type} errorMessage={error_message} />,
- });
- }
- // If the queue item is completed, failed, or cancelled, we want to clear the last progress event
- $lastProgressEvent.set(null);
+ if (getEventScope(getState, data) === 'own') {
+ onQueueItemStatusChanged(data);
+ } else {
+ onNonOwnerQueueItemStatusChanged(data);
}
});
@@ -553,53 +487,41 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis
}
dispatch(
queueApi.util.invalidateTags([
- 'SessionQueueStatus',
+ ...QUEUE_CHANGED_TAGS,
'SessionProcessorStatus',
'BatchStatus',
- 'CurrentSessionQueueItem',
- 'NextSessionQueueItem',
'QueueCountsByDestination',
- 'SessionQueueItemIdList',
- { type: 'SessionQueueItem', id: LIST_TAG },
- { type: 'SessionQueueItem', id: LIST_ALL_TAG },
])
);
});
socket.on('batch_enqueued', (data) => {
log.debug({ data }, 'Batch enqueued');
- dispatch(
- queueApi.util.invalidateTags([
- 'SessionQueueStatus',
- 'CurrentSessionQueueItem',
- 'NextSessionQueueItem',
- 'QueueCountsByDestination',
- 'SessionQueueItemIdList',
- { type: 'SessionQueueItem', id: LIST_TAG },
- { type: 'SessionQueueItem', id: LIST_ALL_TAG },
- ])
- );
- });
+ dispatch(queueApi.util.invalidateTags([...QUEUE_CHANGED_TAGS, 'QueueCountsByDestination']));
+ });
+
+ // Bulk queue item events (retried/canceled) are the only signal other clients get for a bulk
+ // operation, which changes many rows in one SQL statement and emits no per-item
+ // queue_item_status_changed. Owners receive their own item ids, admins receive all of them,
+ // and other users receive a sanitized companion with no ids — in every case, refetch the
+ // queue caches so lists and badge counts update.
+ const invalidateQueueTagsForBulkItemEvent = (itemIds: number[]) => {
+ const tagsToInvalidate: ApiTagDescription[] = [...QUEUE_CHANGED_TAGS, 'BatchStatus', 'QueueCountsByDestination'];
+ // Invalidate each affected item specifically
+ for (const itemId of itemIds) {
+ tagsToInvalidate.push({ type: 'SessionQueueItem', id: itemId });
+ }
+ dispatch(queueApi.util.invalidateTags(tagsToInvalidate));
+ };
socket.on('queue_items_retried', (data) => {
log.debug({ data }, 'Queue items retried');
- const tagsToInvalidate: ApiTagDescription[] = [
- 'SessionQueueStatus',
- 'BatchStatus',
- 'CurrentSessionQueueItem',
- 'NextSessionQueueItem',
- 'QueueCountsByDestination',
- 'SessionQueueItemIdList',
- { type: 'SessionQueueItem', id: LIST_TAG },
- { type: 'SessionQueueItem', id: LIST_ALL_TAG },
- ];
- // Invalidate each retried item specifically
- if (data.retried_item_ids) {
- for (const itemId of data.retried_item_ids) {
- tagsToInvalidate.push({ type: 'SessionQueueItem', id: itemId });
- }
- }
- dispatch(queueApi.util.invalidateTags(tagsToInvalidate));
+ invalidateQueueTagsForBulkItemEvent(data.retried_item_ids ?? []);
+ });
+
+ socket.on('queue_items_canceled', (data) => {
+ log.debug({ data }, 'Queue items canceled');
+ invalidateQueueTagsForBulkItemEvent(data.canceled_item_ids);
});
socket.on('recall_parameters_updated', (data) => {
diff --git a/invokeai/frontend/web/src/services/events/types.ts b/invokeai/frontend/web/src/services/events/types.ts
index 72239986fb..f374a4d9c4 100644
--- a/invokeai/frontend/web/src/services/events/types.ts
+++ b/invokeai/frontend/web/src/services/events/types.ts
@@ -33,6 +33,7 @@ export type ServerToClientEvents = {
queue_cleared: (payload: S['QueueClearedEvent']) => void;
batch_enqueued: (payload: S['BatchEnqueuedEvent']) => void;
queue_items_retried: (payload: S['QueueItemsRetriedEvent']) => void;
+ queue_items_canceled: (payload: S['QueueItemsCanceledEvent']) => void;
recall_parameters_updated: (payload: S['RecallParametersUpdatedEvent']) => void;
bulk_download_started: (payload: S['BulkDownloadStartedEvent']) => void;
bulk_download_complete: (payload: S['BulkDownloadCompleteEvent']) => void;
diff --git a/invokeai/frontend/web/src/services/events/useSocketIO.ts b/invokeai/frontend/web/src/services/events/useSocketIO.ts
index dcbe2501f3..f8b5a7b34c 100644
--- a/invokeai/frontend/web/src/services/events/useSocketIO.ts
+++ b/invokeai/frontend/web/src/services/events/useSocketIO.ts
@@ -1,5 +1,6 @@
-import { useAppStore } from 'app/store/storeHooks';
+import { useAppSelector, useAppStore } from 'app/store/storeHooks';
import { useAssertSingleton } from 'common/hooks/useAssertSingleton';
+import { selectAuthToken, selectCurrentUser } from 'features/auth/store/authSlice';
import type { MapStore } from 'nanostores';
import { useEffect, useMemo } from 'react';
import { selectQueueStatus } from 'services/api/endpoints/queue';
@@ -24,13 +25,31 @@ export const useSocketIO = () => {
useAssertSingleton('useSocketIO');
const store = useAppStore();
+ // In multiuser mode the socket must not connect until auth.user has hydrated from /me: the
+ // event listeners classify every event's ownership against auth.user (see getEventScope), and
+ // events received while it is still null would be misclassified as another user's — silently
+ // dropping one-shot side effects (progress, node execution states, gallery auto-switch, the
+ // failure toast) that never replay after hydration. No token means single-user mode (or a
+ // stale token that ProtectedRoute has cleared), where every event is the client's own and the
+ // socket can connect immediately.
+ //
+ // The token also feeds socketOptions, making it a dependency of the connect effect: an in-tab
+ // logout or session expiry (which nulls the token) tears the authenticated socket down instead
+ // of letting it keep the old user's room membership — and private events — until the next full
+ // page reload.
+ const token = useAppSelector(selectAuthToken);
+ const currentUser = useAppSelector(selectCurrentUser);
+ const isAuthHydrated = !token || currentUser !== null;
+
const socketUrl = useMemo(() => {
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
return `${wsProtocol}://${window.location.host}`;
}, []);
+ // Derived from the redux token (hydrated synchronously from localStorage) rather than a
+ // one-time localStorage read, so the socket always authenticates with the current session's
+ // token and reconnects when it changes.
const socketOptions = useMemo(() => {
- const token = localStorage.getItem('auth_token');
const options: Partial<ManagerOptions & SocketOptions> = {
timeout: 60000,
path: '/ws/socket.io',
@@ -45,9 +64,12 @@ export const useSocketIO = () => {
};
return options;
- }, []);
+ }, [token]);
useEffect(() => {
+ if (!isAuthHydrated) {
+ return;
+ }
const socket: AppSocket = io(socketUrl, socketOptions);
$socket.set(socket);
@@ -77,6 +99,7 @@ export const useSocketIO = () => {
}
unsubscribeQueueStatusListener();
socket.disconnect();
+ $socket.set(null);
};
- }, [socketOptions, socketUrl, store]);
+ }, [isAuthHydrated, socketOptions, socketUrl, store]);
};
diff --git a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts
index 3c443383aa..bc6bfe55e5 100644
--- a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts
+++ b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts
@@ -44,10 +44,11 @@ type WorkflowExecutionCoordinatorDeps = {
export const createWorkflowExecutionCoordinator = (deps: WorkflowExecutionCoordinatorDeps) => {
const workflowExecutionStates = new LRUCache<number, WorkflowExecutionState>({ max: 100 });
// Each tracked item's owner, recorded from incoming events, lets a user-scoped queue clear be
- // applied to just that user's items. Every event reaching the coordinator carries a real owner:
- // invocation and status events are private to the owner and admins, and the sanitized
- // (user_id="redacted") companions are filtered out before the coordinator. Sized to match
- // workflowExecutionStates - an item without a tracked state needs no owner.
+ // applied to just that user's items. The socket listeners route only the current user's own
+ // events into the coordinator (foreign and sanitized events are handled upstream in
+ // setEventListeners), so in practice this map only ever holds the current user's items; it is
+ // kept as a guard for queue_cleared scoping in single-user mode and edge event orderings.
+ // Sized to match workflowExecutionStates - an item without a tracked state needs no owner.
const itemOwnerUserIds = new LRUCache<number, string>({ max: 100 });
const pendingWorkflowReconciliationRequests = new Map<number, ReconciliationRequest>();
let activeWorkflowQueueItemId: number | null = null;
diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.py
index 5a7e673b18..0475d99ce1 100644
--- a/tests/app/routers/test_multiuser_authorization.py
+++ b/tests/app/routers/test_multiuser_authorization.py
@@ -1440,14 +1440,16 @@ class TestQueueStatusScoping:
assert queue_status["user_pending"] == 2
assert queue_status["user_in_progress"] == 0
- # Admin caller sees the same global total. Admins query with user_id=None, so no
- # per-user counts are computed (the badge falls back to the global total for admins).
+ # Admin caller sees the same global total plus their own per-user counts (zero here -
+ # the admin owns no items), so personal UI like the progress bar can distinguish the
+ # admin's own activity from other users'.
r = client.get("/api/v1/queue/default/status", headers=_auth(admin_tok))
assert r.status_code == 200
queue_status = r.json()["queue"]
assert queue_status["pending"] == 3
assert queue_status["total"] == 3
- assert queue_status["user_pending"] is None
+ assert queue_status["user_pending"] == 0
+ assert queue_status["user_in_progress"] == 0
# ===========================================================================
@@ -1890,11 +1892,13 @@ class TestWebSocketAuth:
(c.kwargs.get("room"), c.kwargs.get("data"), c.kwargs.get("skip_sid")) for c in mock_emit.call_args_list
]
- # Full event must go to owner room and admin room with original sensitive fields
- owner_emits = [(p, s) for r, p, s in emits if r == "user:owner-xyz"]
- admin_emits = [(p, s) for r, p, s in emits if r == "admin"]
- assert len(owner_emits) == 1 and len(admin_emits) == 1
- for payload, _ in owner_emits + admin_emits:
+ # Full event must go to owner + admin rooms with original sensitive fields, in a SINGLE
+ # emit to the room list — python-socketio dedups recipients across a room list, so an
+ # admin owner (or the single-user "system" user, which is in both rooms) receives
+ # exactly one copy instead of running the frontend handler twice.
+ full_emits = [(p, s) for r, p, s in emits if r == ["user:owner-xyz", "admin"]]
+ assert len(full_emits) == 1
+ for payload, _ in full_emits:
assert payload["user_id"] == "owner-xyz"
assert payload["batch_id"] == "batch-private"
assert payload["session_id"] == "sess-private"
@@ -1962,11 +1966,11 @@ class TestWebSocketAuth:
(c.kwargs.get("room"), c.kwargs.get("data"), c.kwargs.get("skip_sid")) for c in mock_emit.call_args_list
]
- # Full event to owner + admin contains the real batch_id and origin
- owner_emits = [(p, s) for r, p, s in emits if r == "user:owner-zzz"]
- admin_emits = [(p, s) for r, p, s in emits if r == "admin"]
- assert len(owner_emits) == 1 and len(admin_emits) == 1
- for payload, _ in owner_emits + admin_emits:
+ # Full event to owner + admin contains the real batch_id and origin, in a single emit to
+ # the room list so a socket in both rooms receives exactly one copy
+ full_emits = [(p, s) for r, p, s in emits if r == ["user:owner-zzz", "admin"]]
+ assert len(full_emits) == 1
+ for payload, _ in full_emits:
assert payload["user_id"] == "owner-zzz"
assert payload["batch_id"] == "batch-pvt"
assert payload["origin"] == "workflows"
@@ -2000,7 +2004,10 @@ class TestWebSocketAuth:
assert event.queue_id == "default"
def test_queue_items_retried_routed_privately(self, socketio: Any) -> None:
- """Verify that queue_items_retried is emitted only to owner/admin rooms."""
+ """The FULL queue_items_retried event, which carries owners' item ids, must reach only the
+ owner/admin rooms. A sanitized companion carrying no ids is broadcast to the queue room so
+ other users' badge totals refresh — see test_queue_items_retried_broadcasts_sanitized_companion.
+ """
import asyncio
from unittest.mock import AsyncMock
@@ -2022,7 +2029,61 @@ class TestWebSocketAuth:
assert "user:owner-123" in rooms_emitted_to
assert "user:owner-456" in rooms_emitted_to
assert "admin" in rooms_emitted_to
- assert "default" not in rooms_emitted_to
+
+ # CRITICAL: nothing identifying may reach the queue room. The only emit there is the
+ # sanitized companion, which must not name any owner or any retried item.
+ queue_room_payloads = [c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]
+ assert len(queue_room_payloads) == 1
+ assert queue_room_payloads[0]["retried_item_ids"] == []
+ assert queue_room_payloads[0]["user_ids"] == []
+ assert queue_room_payloads[0]["retried_item_ids_by_user"] == {}
+
+ def test_queue_items_retried_broadcasts_sanitized_companion(self, socketio: Any) -> None:
+ """Retried items are re-enqueued and raise the queue's global total, but retrying emits no
+ per-item queue_item_status_changed. A sanitized companion must therefore reach every other
+ subscriber so their badge total refetches, while owners and admins — who already got the
+ full event — are skipped.
+ """
+ import asyncio
+ from unittest.mock import AsyncMock
+
+ from invokeai.app.services.events.events_common import QueueItemsRetriedEvent
+ from invokeai.app.services.session_queue.session_queue_common import RetryItemsResult
+
+ event = QueueItemsRetriedEvent.build(
+ RetryItemsResult(queue_id="default", retried_item_ids=[10, 20]),
+ user_ids=["owner-123", "owner-456"],
+ retried_item_ids_by_user={"owner-123": [10], "owner-456": [20]},
+ )
+
+ # A retry batch can span several owners — every one of them must be skipped, not just the first.
+ socketio._socket_users["sid-owner-123"] = {"user_id": "owner-123", "is_admin": False}
+ socketio._socket_users["sid-owner-456"] = {"user_id": "owner-456", "is_admin": False}
+ socketio._socket_users["sid-admin"] = {"user_id": "admin-1", "is_admin": True}
+ socketio._socket_users["sid-other"] = {"user_id": "other-user", "is_admin": False}
+
+ mock_emit = AsyncMock()
+ socketio._sio.emit = mock_emit
+
+ asyncio.run(socketio._handle_queue_event(("queue_items_retried", event)))
+
+ queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]
+ assert len(queue_emits) == 1, "expected exactly one sanitized emit to the queue room"
+ payload = queue_emits[0].kwargs["data"]
+ skip_sid = queue_emits[0].kwargs["skip_sid"]
+
+ # Non-sensitive: the queue_id is all a non-owner needs to refetch its redacted status.
+ assert payload["queue_id"] == "default"
+ assert payload["retried_item_ids"] == []
+ assert payload["user_ids"] == []
+ assert payload["retried_item_ids_by_user"] == {}
+
+ # Both owners and the admin already received the full event and must not get a second copy.
+ assert "sid-owner-123" in skip_sid
+ assert "sid-owner-456" in skip_sid
+ assert "sid-admin" in skip_sid
+ # The unrelated user is the whole point — they must receive it.
+ assert "sid-other" not in skip_sid
def test_queue_items_retried_payload_is_filtered_per_owner_room(self, socketio: Any) -> None:
"""Each owner room should only receive retry payload for that owner."""
@@ -2060,6 +2121,132 @@ class TestWebSocketAuth:
assert admin_calls[0].kwargs["data"]["user_ids"] == ["owner-123", "owner-456"]
assert admin_calls[0].kwargs["data"]["retried_item_ids_by_user"] == {"owner-123": [10], "owner-456": [20]}
+ def test_queue_items_canceled_routed_privately_per_owner(self, socketio: Any) -> None:
+ """The FULL queue_items_canceled event, which carries owners' item ids, must reach only the
+ owner/admin rooms, and each owner room may only see that owner's own item ids. A bulk
+ cancel emits no per-item queue_item_status_changed, so this event is each owner's only
+ signal that their pending items were canceled (e.g. by an admin's cancel-all-except-current).
+ """
+ import asyncio
+ from unittest.mock import AsyncMock
+
+ from invokeai.app.services.events.events_common import QueueItemsCanceledEvent
+
+ event = QueueItemsCanceledEvent.build(
+ queue_id="default",
+ canceled_item_ids_by_user={"owner-123": [10, 11], "owner-456": [20]},
+ )
+
+ mock_emit = AsyncMock()
+ socketio._sio.emit = mock_emit
+
+ asyncio.run(socketio._handle_queue_event(("queue_items_canceled", event)))
+
+ owner_123_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "user:owner-123"]
+ owner_456_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "user:owner-456"]
+ admin_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "admin"]
+
+ assert len(owner_123_calls) == 1
+ assert len(owner_456_calls) == 1
+ assert len(admin_calls) == 1
+ assert owner_123_calls[0].kwargs["data"]["canceled_item_ids"] == [10, 11]
+ assert owner_123_calls[0].kwargs["data"]["user_ids"] == ["owner-123"]
+ assert owner_123_calls[0].kwargs["data"]["canceled_item_ids_by_user"] == {"owner-123": [10, 11]}
+ assert owner_456_calls[0].kwargs["data"]["canceled_item_ids"] == [20]
+ assert admin_calls[0].kwargs["data"]["canceled_item_ids"] == [10, 11, 20]
+ assert admin_calls[0].kwargs["data"]["canceled_item_ids_by_user"] == {
+ "owner-123": [10, 11],
+ "owner-456": [20],
+ }
+
+ # Nothing identifying may reach the queue room: the only emit there is the sanitized
+ # companion, which must not name any owner or any canceled item.
+ queue_room_payloads = [c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]
+ assert len(queue_room_payloads) == 1
+ assert queue_room_payloads[0]["canceled_item_ids"] == []
+ assert queue_room_payloads[0]["user_ids"] == []
+ assert queue_room_payloads[0]["canceled_item_ids_by_user"] == {}
+
+ def test_queue_items_canceled_broadcasts_sanitized_companion(self, socketio: Any) -> None:
+ """Canceled items lower the queue's global total, so every other subscriber's badge must
+ refetch. The sanitized companion reaches them while owners and admins — who already got
+ the full event — are skipped.
+ """
+ import asyncio
+ from unittest.mock import AsyncMock
+
+ from invokeai.app.services.events.events_common import QueueItemsCanceledEvent
+
+ event = QueueItemsCanceledEvent.build(
+ queue_id="default",
+ canceled_item_ids_by_user={"owner-123": [10], "owner-456": [20]},
+ )
+
+ # A bulk cancel can span several owners — every one of them must be skipped, not just the first.
+ socketio._socket_users["sid-owner-123"] = {"user_id": "owner-123", "is_admin": False}
+ socketio._socket_users["sid-owner-456"] = {"user_id": "owner-456", "is_admin": False}
+ socketio._socket_users["sid-admin"] = {"user_id": "admin-1", "is_admin": True}
+ socketio._socket_users["sid-other"] = {"user_id": "other-user", "is_admin": False}
+
+ mock_emit = AsyncMock()
+ socketio._sio.emit = mock_emit
+
+ asyncio.run(socketio._handle_queue_event(("queue_items_canceled", event)))
+
+ queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]
+ assert len(queue_emits) == 1, "expected exactly one sanitized emit to the queue room"
+ payload = queue_emits[0].kwargs["data"]
+ skip_sid = queue_emits[0].kwargs["skip_sid"]
+
+ # Non-sensitive: the queue_id is all a non-owner needs to refetch its redacted status.
+ assert payload["queue_id"] == "default"
+ assert payload["canceled_item_ids"] == []
+ assert payload["user_ids"] == []
+ assert payload["canceled_item_ids_by_user"] == {}
+
+ # Both owners and the admin already received the full event and must not get a second copy.
+ assert "sid-owner-123" in skip_sid
+ assert "sid-owner-456" in skip_sid
+ assert "sid-admin" in skip_sid
+ # The unrelated user is the whole point — they must receive it.
+ assert "sid-other" not in skip_sid
+
+ def test_bulk_event_admin_owner_receives_exactly_one_copy(self, socketio: Any) -> None:
+ """An admin who also owns affected items is in both their user room and the admin room.
+ The owner-room emit must skip admin sids so such a socket receives only the full
+ admin-room copy — two copies would double-refetch every queue endpoint (single-user
+ mode hits this on every bulk cancel, since the "system" user is an admin)."""
+ import asyncio
+ from unittest.mock import AsyncMock
+
+ from invokeai.app.services.events.events_common import QueueItemsCanceledEvent
+
+ event = QueueItemsCanceledEvent.build(
+ queue_id="default",
+ canceled_item_ids_by_user={"admin-1": [10], "owner-456": [20]},
+ )
+
+ socketio._socket_users["sid-admin-owner"] = {"user_id": "admin-1", "is_admin": True}
+ socketio._socket_users["sid-owner-456"] = {"user_id": "owner-456", "is_admin": False}
+
+ mock_emit = AsyncMock()
+ socketio._sio.emit = mock_emit
+
+ asyncio.run(socketio._handle_queue_event(("queue_items_canceled", event)))
+
+ # The admin-owner's user-room emit skips their sid; the admin-room emit is their one copy.
+ owner_room_calls = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "user:admin-1"]
+ assert len(owner_room_calls) == 1
+ assert "sid-admin-owner" in owner_room_calls[0].kwargs["skip_sid"]
+
+ # The non-admin owner's room emit must not skip their sid.
+ other_owner_calls = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "user:owner-456"]
+ assert len(other_owner_calls) == 1
+ assert "sid-owner-456" not in other_owner_calls[0].kwargs["skip_sid"]
+
+ admin_calls = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "admin"]
+ assert len(admin_calls) == 1
+
def test_unscoped_queue_cleared_still_broadcast(self, socketio: Any) -> None:
"""An unscoped QueueClearedEvent (user_id=None — an admin or single-user clear that
deleted every user's items) should still be broadcast to all queue subscribers."""
@@ -2271,3 +2458,128 @@ class TestCustomNodesAuthorization:
data = r.json()
assert data["success"] is True
assert data["name"] == "test-pack"
+
+
+# ===========================================================================
+# Image list/names ownership isolation (omitted board_id)
+# ===========================================================================
+
+
+class TestImageListOwnershipIsolation:
+ """/api/v1/images/ and /api/v1/images/names must not leak other users' images
+ when board_id is omitted.
+
+ Without the omitted-board ownership predicate, a non-admin could enumerate every
+ user's image names, dimensions, timestamps, and board associations simply by
+ leaving off the board_id query parameter.
+ """
+
+ @pytest.fixture
+ def seeded_boards(
+ self, client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str
+ ) -> dict[str, str]:
+ """user1: private board with one image + one uncategorized image + a shared board
+ with one image. user2: one uncategorized image."""
+ 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-private-boarded", user1.user_id)
+ _save_image(mock_invoker, "u1-uncat", user1.user_id)
+ _save_image(mock_invoker, "u1-shared-boarded", user1.user_id)
+ _save_image(mock_invoker, "u2-uncat", user2.user_id)
+
+ private_board_id = _create_board(client, user1_token, "User1 Private List Board")
+ shared_board_id = _create_board(client, user1_token, "User1 Shared List Board")
+ _share_board(client, user1_token, shared_board_id)
+
+ # Associate via the record storage directly — the board_images *service* is
+ # replaced with a MagicMock by the enable_multiuser fixture.
+ mock_invoker.services.board_image_records.add_image_to_board(private_board_id, "u1-private-boarded")
+ mock_invoker.services.board_image_records.add_image_to_board(shared_board_id, "u1-shared-boarded")
+
+ # The DTO list route resolves URLs through the urls service, which is None in
+ # the test harness.
+ mock_urls = MagicMock()
+ mock_urls.get_image_url.return_value = "http://test/image.png"
+ mock_invoker.services.urls = mock_urls
+
+ return {"private_board_id": private_board_id, "shared_board_id": shared_board_id}
+
+ def _list_names(self, client: TestClient, token: str, **params: str) -> list[str]:
+ r = client.get("/api/v1/images/", params=params, headers=_auth(token))
+ assert r.status_code == status.HTTP_200_OK
+ return [item["image_name"] for item in r.json()["items"]]
+
+ def _image_names(self, client: TestClient, token: str, **params: str) -> list[str]:
+ r = client.get("/api/v1/images/names", params=params, headers=_auth(token))
+ assert r.status_code == status.HTTP_200_OK
+ return r.json()["image_names"]
+
+ def test_list_omitted_board_excludes_other_users(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ assert self._list_names(client, user2_token) == ["u2-uncat"]
+
+ def test_list_omitted_board_owner_sees_own_boarded_and_uncategorized(
+ self, client: TestClient, seeded_boards: dict[str, str], user1_token: str
+ ) -> None:
+ assert set(self._list_names(client, user1_token)) == {"u1-private-boarded", "u1-uncat", "u1-shared-boarded"}
+
+ def test_list_omitted_board_admin_sees_all(
+ self, client: TestClient, seeded_boards: dict[str, str], admin_token: str
+ ) -> None:
+ assert set(self._list_names(client, admin_token)) == {
+ "u1-private-boarded",
+ "u1-uncat",
+ "u1-shared-boarded",
+ "u2-uncat",
+ }
+
+ def test_list_none_board_scopes_to_owner(
+ self, client: TestClient, seeded_boards: dict[str, str], user1_token: str
+ ) -> None:
+ assert self._list_names(client, user1_token, board_id="none") == ["u1-uncat"]
+
+ def test_list_private_board_forbidden_for_non_owner(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ r = client.get(
+ "/api/v1/images/", params={"board_id": seeded_boards["private_board_id"]}, headers=_auth(user2_token)
+ )
+ assert r.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_list_shared_board_readable_by_non_owner(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ assert self._list_names(client, user2_token, board_id=seeded_boards["shared_board_id"]) == ["u1-shared-boarded"]
+
+ def test_names_omitted_board_excludes_other_users(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ assert self._image_names(client, user2_token) == ["u2-uncat"]
+
+ def test_names_omitted_board_admin_sees_all(
+ self, client: TestClient, seeded_boards: dict[str, str], admin_token: str
+ ) -> None:
+ assert set(self._image_names(client, admin_token)) == {
+ "u1-private-boarded",
+ "u1-uncat",
+ "u1-shared-boarded",
+ "u2-uncat",
+ }
+
+ def test_names_none_board_scopes_to_owner(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ assert self._image_names(client, user2_token, board_id="none") == ["u2-uncat"]
+
+ def test_names_private_board_forbidden_for_non_owner(
+ self, client: TestClient, seeded_boards: dict[str, str], user2_token: str
+ ) -> None:
+ r = client.get(
+ "/api/v1/images/names",
+ params={"board_id": seeded_boards["private_board_id"]},
+ headers=_auth(user2_token),
+ )
+ assert r.status_code == status.HTTP_403_FORBIDDEN
diff --git a/tests/app/services/image_records/test_image_records_sqlite.py b/tests/app/services/image_records/test_image_records_sqlite.py
index 6b262d3414..bd73c04fdb 100644
--- a/tests/app/services/image_records/test_image_records_sqlite.py
+++ b/tests/app/services/image_records/test_image_records_sqlite.py
@@ -1,11 +1,14 @@
"""DB-backed tests for SqliteImageRecordStorage.
Verifies that image_subfolder round-trips correctly through save(), get(),
-get_many(), and delete_intermediates() against a real (in-memory) SQLite database.
+get_many(), and delete_intermediates() against a real (in-memory) SQLite database,
+and that get_many()/get_image_names() enforce per-user ownership isolation.
"""
import pytest
+from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
+from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
@@ -22,7 +25,26 @@ def store() -> SqliteImageRecordStorage:
return SqliteImageRecordStorage(db=db)
-def _save(store: SqliteImageRecordStorage, name: str, subfolder: str = "", is_intermediate: bool = False) -> None:
+def stores() -> tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage]:
+ """Image, board, and board-image storages sharing one in-memory database."""
+ config = InvokeAIAppConfig(use_memory_db=True)
+ logger = InvokeAILogger.get_logger(config=config)
+ db = create_mock_sqlite_database(config, logger)
+ return (
+ SqliteImageRecordStorage(db=db),
+ SqliteBoardRecordStorage(db=db),
+ SqliteBoardImageRecordStorage(db=db),
+ )
+
+
+def _save(
+ store: SqliteImageRecordStorage,
+ name: str,
+ subfolder: str = "",
+ is_intermediate: bool = False,
+ user_id: str | None = None,
+) -> None:
store.save(
image_name=name,
image_origin=ResourceOrigin.INTERNAL,
@@ -32,6 +54,7 @@ def _save(store: SqliteImageRecordStorage, name: str, subfolder: str = "", is_in
has_workflow=False,
is_intermediate=is_intermediate,
image_subfolder=subfolder,
+ user_id=user_id,
)
@@ -98,3 +121,142 @@ class TestDeleteIntermediatesSubfolder:
with pytest.raises(ImageRecordNotFoundException):
store.get("tmp.png")
+
+
+class TestOwnershipFilteringOmittedBoard:
+ """get_many()/get_image_names() enforce per-user isolation when board_id is omitted.
+
+ Without this, a non-admin could enumerate every user's images (including images
+ on other users' private boards) simply by omitting the board_id query parameter.
+ """
+
+ def _seed_two_users(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> str:
+ """user1: one image on a private board + one uncategorized. user2: one uncategorized."""
+ image_store, board_store, board_image_store = stores
+ _save(image_store, "u1-boarded.png", user_id="user1")
+ _save(image_store, "u1-uncat.png", user_id="user1")
+ _save(image_store, "u2-uncat.png", user_id="user2")
+ board = board_store.save(board_name="User1 Private Board", user_id="user1")
+ board_image_store.add_image_to_board(board_id=board.board_id, image_name="u1-boarded.png")
+ return board.board_id
+
+ def test_get_many_omitted_board_filters_by_owner(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, user_id="user2", is_admin=False)
+
+ assert {r.image_name for r in result.items} == {"u2-uncat.png"}
+ assert result.total == 1
+
+ def test_get_many_omitted_board_owner_sees_boarded_and_uncategorized(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, user_id="user1", is_admin=False)
+
+ assert {r.image_name for r in result.items} == {"u1-boarded.png", "u1-uncat.png"}
+ assert result.total == 2
+
+ def test_get_many_omitted_board_admin_sees_all(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, user_id="admin", is_admin=True)
+
+ assert {r.image_name for r in result.items} == {"u1-boarded.png", "u1-uncat.png", "u2-uncat.png"}
+ assert result.total == 3
+
+ def test_get_many_omitted_board_single_user_mode_sees_all(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ """user_id=None (single-user mode) applies no ownership filter."""
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, user_id=None, is_admin=False)
+
+ assert result.total == 3
+
+ def test_get_many_none_board_still_filters_by_owner(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ """board_id="none" (uncategorized) keeps its existing per-user isolation."""
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, board_id="none", user_id="user1", is_admin=False)
+
+ assert {r.image_name for r in result.items} == {"u1-uncat.png"}
+
+ def test_get_many_explicit_board_returns_board_contents(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ """An explicit board_id lists that board's images; read access is the router's job."""
+ board_id = self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_many(limit=10, board_id=board_id, user_id="user1", is_admin=False)
+
+ assert {r.image_name for r in result.items} == {"u1-boarded.png"}
+
+ def test_get_image_names_omitted_board_filters_by_owner(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_image_names(user_id="user2", is_admin=False)
+
+ assert result.image_names == ["u2-uncat.png"]
+ assert result.total_count == 1
+
+ def test_get_image_names_omitted_board_admin_sees_all(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_image_names(user_id="admin", is_admin=True)
+
+ assert set(result.image_names) == {"u1-boarded.png", "u1-uncat.png", "u2-uncat.png"}
+ assert result.total_count == 3
+
+ def test_get_image_names_omitted_board_single_user_mode_sees_all(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_image_names(user_id=None, is_admin=False)
+
+ assert result.total_count == 3
+
+ def test_get_image_names_none_board_still_filters_by_owner(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ self._seed_two_users(stores)
+ image_store = stores[0]
+
+ result = image_store.get_image_names(board_id="none", user_id="user1", is_admin=False)
+
+ assert result.image_names == ["u1-uncat.png"]
diff --git a/tests/app/services/session_queue/test_session_queue_bulk_cancel_events.py b/tests/app/services/session_queue/test_session_queue_bulk_cancel_events.py
new file mode 100644
index 0000000000..0aa9149911
--- /dev/null
+++ b/tests/app/services/session_queue/test_session_queue_bulk_cancel_events.py
@@ -0,0 +1,222 @@
+"""Tests that bulk cancel/delete operations emit queue_items_canceled.
+
+A bulk cancel (e.g. cancel-all-except-current) updates rows in a single SQL statement and emits no
+per-item queue_item_status_changed events. Without a bulk event, other connected clients never
+learn that pending items left the queue — an owner's badge kept showing stale counts after an
+admin canceled their items. The queue_items_canceled event is that signal; these tests are the
+regression tests for its emission.
+"""
+
+import uuid
+
+import pytest
+
+from invokeai.app.services.events.events_common import QueueItemsCanceledEvent
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from tests.test_nodes import PromptTestInvocation
+
+
+def session_queue(mock_invoker: Invoker) -> SqliteSessionQueue:
+ """Create a SqliteSessionQueue backed by the mock invoker's in-memory database."""
+ db = mock_invoker.services.board_records._db
+ queue = SqliteSessionQueue(db=db)
+ queue.start(mock_invoker)
+ return queue
+
+
+def _insert_queue_item(
+ session_queue: SqliteSessionQueue,
+ queue_id: str,
+ user_id: str,
+ batch_id: str | None = None,
+ destination: str | None = None,
+) -> int:
+ """Directly insert a minimal pending queue item for the given user and return its item_id."""
+ session_id = str(uuid.uuid4())
+ batch_id = batch_id or str(uuid.uuid4())
+ with session_queue._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (queue_id, "{}", session_id, batch_id, None, 0, None, None, destination, None, user_id),
+ )
+ assert cursor.lastrowid is not None
+ return cursor.lastrowid
+
+
+def _insert_dequeueable_queue_item(
+ session_queue: SqliteSessionQueue,
+ queue_id: str,
+ user_id: str,
+ destination: str | None = None,
+) -> int:
+ """Insert a pending queue item with a real parseable session, for tests that dequeue it."""
+ graph = Graph()
+ graph.add_node(PromptTestInvocation(id="prompt", prompt="test"))
+ session = GraphExecutionState(graph=graph)
+ session_json = session.model_dump_json(warnings=False, exclude_none=True)
+ batch_id = str(uuid.uuid4())
+ with session_queue._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (queue_id, session_json, session.id, batch_id, None, 0, None, None, destination, None, user_id),
+ )
+ assert cursor.lastrowid is not None
+ return cursor.lastrowid
+
+
+def _canceled_events(mock_invoker: Invoker) -> list[QueueItemsCanceledEvent]:
+ return [e for e in mock_invoker.services.events.events if isinstance(e, QueueItemsCanceledEvent)]
+
+
+def test_cancel_all_except_current_emits_queue_items_canceled_grouped_by_owner(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """An admin cancel (no user_id) affects every user's pending items; each owner's client needs
+ its own item ids so its queue list and badge counts refetch."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a")
+ a2 = _insert_queue_item(session_queue, "default", "user_a")
+ b1 = _insert_queue_item(session_queue, "default", "user_b")
+
+ result = session_queue.cancel_all_except_current("default")
+
+ assert result.canceled == 3
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ event = events[0]
+ assert event.queue_id == "default"
+ assert event.canceled_item_ids_by_user == {"user_a": [a1, a2], "user_b": [b1]}
+ assert sorted(event.canceled_item_ids) == sorted([a1, a2, b1])
+ assert sorted(event.user_ids) == ["user_a", "user_b"]
+
+
+def test_cancel_all_except_current_scoped_to_user_only_names_their_items(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """A non-admin cancel is scoped to the caller; other users' items are untouched and must not
+ appear in the event."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a")
+ _insert_queue_item(session_queue, "default", "user_b")
+
+ result = session_queue.cancel_all_except_current("default", user_id="user_a")
+
+ assert result.canceled == 1
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1]}
+
+
+def test_delete_all_except_current_emits_queue_items_canceled(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """Bulk delete removes rows entirely — same notification requirement as bulk cancel."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a")
+ b1 = _insert_queue_item(session_queue, "default", "user_b")
+
+ result = session_queue.delete_all_except_current("default")
+
+ assert result.deleted == 2
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1], "user_b": [b1]}
+
+
+def test_no_event_when_nothing_was_canceled(session_queue: SqliteSessionQueue, mock_invoker: Invoker) -> None:
+ """An empty result must not broadcast a pointless refetch signal to every client."""
+ result = session_queue.cancel_all_except_current("default")
+
+ assert result.canceled == 0
+ assert _canceled_events(mock_invoker) == []
+
+
+def test_cancel_by_batch_ids_emits_queue_items_canceled(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """Canceling batches bulk-updates pending rows with no per-item events; other clients need
+ the bulk event to learn the items left the queue."""
+ batch_id = str(uuid.uuid4())
+ a1 = _insert_queue_item(session_queue, "default", "user_a", batch_id=batch_id)
+ a2 = _insert_queue_item(session_queue, "default", "user_a", batch_id=batch_id)
+ _insert_queue_item(session_queue, "default", "user_b") # different batch - untouched
+
+ result = session_queue.cancel_by_batch_ids("default", [batch_id])
+
+ assert result.canceled == 2
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1, a2]}
+
+
+def test_cancel_by_destination_emits_queue_items_canceled(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """Discarding a canvas staging area cancels by destination; the bulk event keeps other
+ clients' queue badges in sync."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a", destination="canvas:sess-1")
+ b1 = _insert_queue_item(session_queue, "default", "user_b", destination="canvas:sess-1")
+ _insert_queue_item(session_queue, "default", "user_b", destination="other")
+
+ result = session_queue.cancel_by_destination("default", "canvas:sess-1")
+
+ assert result.canceled == 2
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1], "user_b": [b1]}
+
+
+def test_delete_by_destination_emits_queue_items_canceled(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """Bulk delete by destination removes rows entirely - same notification requirement."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a", destination="canvas:sess-1")
+ _insert_queue_item(session_queue, "default", "user_a", destination="other")
+
+ result = session_queue.delete_by_destination("default", "canvas:sess-1")
+
+ assert result.deleted == 1
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1]}
+
+
+def test_delete_by_destination_excludes_separately_canceled_current_item(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """The in-progress current item matching the destination is canceled via cancel_queue_item,
+ which emits its own per-item queue_item_status_changed - the bulk event must not signal the
+ same item a second time. The row is still deleted and still counted in the returned total."""
+ current_id = _insert_dequeueable_queue_item(session_queue, "default", "user_a", destination="canvas:sess-1")
+ pending_id = _insert_queue_item(session_queue, "default", "user_a", destination="canvas:sess-1")
+
+ in_progress = session_queue.dequeue()
+ assert in_progress is not None and in_progress.item_id == current_id
+
+ result = session_queue.delete_by_destination("default", "canvas:sess-1")
+
+ assert result.deleted == 2
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [pending_id]}
+
+
+def test_cancel_by_queue_id_emits_queue_items_canceled(
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker
+) -> None:
+ """Canceling a whole queue bulk-updates every user's non-terminal items."""
+ a1 = _insert_queue_item(session_queue, "default", "user_a")
+ b1 = _insert_queue_item(session_queue, "default", "user_b")
+
+ result = session_queue.cancel_by_queue_id("default")
+
+ assert result.canceled == 2
+ events = _canceled_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].canceled_item_ids_by_user == {"user_a": [a1], "user_b": [b1]}
diff --git a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py b/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
index ecef76f1eb..56e66ff6aa 100644
--- a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
+++ b/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
@@ -253,6 +253,35 @@ def test_event_preserves_identifiers_when_current_item_is_the_changed_item(
assert a_event.queue_status.batch_id == in_progress.batch_id
+def test_event_carries_owner_per_user_counts(session_queue: SqliteSessionQueue, mock_invoker: Invoker) -> None:
+ """The embedded queue_status carries the event owner's per-user counts so the owner's client
+ can update personal UI (progress bar, spinner, favicon) from the event immediately, without
+ waiting for a status refetch. The sanitized companion nulls these before reaching non-owners."""
+ user_a = "user-a"
+ user_b = "user-b"
+
+ b_item_id = _insert_queue_item(session_queue, user_id=user_b)
+ a_item_1 = _insert_queue_item(session_queue, user_id=user_a)
+ _a_item_2 = _insert_queue_item(session_queue, user_id=user_a)
+
+ in_progress = session_queue.dequeue()
+ assert in_progress is not None and in_progress.item_id == b_item_id
+
+ event_bus: TestEventService = mock_invoker.services.events
+ event_bus.events.clear()
+
+ session_queue.cancel_queue_item(a_item_1)
+
+ a_event = _last_status_event_for_item(event_bus, a_item_1)
+ assert a_event.user_id == user_a
+ # Global counts: A's remaining pending item, B's in-progress item.
+ assert a_event.queue_status.pending == 1
+ assert a_event.queue_status.in_progress == 1
+ # Owner-scoped counts: A has one pending item left and nothing in progress.
+ assert a_event.queue_status.user_pending == 1
+ assert a_event.queue_status.user_in_progress == 0
+
+
def test_workflow_call_child_enqueue_event_redacts_other_users_current_item_identifiers(
session_queue: SqliteSessionQueue, mock_invoker: Invoker
) -> None:
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.py
index d58933879f..c9e2147b0e 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
@@ -107,6 +107,32 @@ def test_status_current_item_redacted_for_non_owner_but_counts_global(session_qu
assert status.user_pending == 1 # A's single pending item
+def test_status_admin_caller_gets_user_subcounts_and_current_item_identifiers(
+ session_queue: SqliteSessionQueue,
+) -> None:
+ """An admin caller (user_id set, is_admin=True) gets their own subcounts - so personal UI
+ like the progress bar can distinguish the admin's own activity from other users' - while
+ still seeing the identifiers of another user's current item."""
+ admin_id = "admin-1"
+ user_b = "user-b"
+ b_item_id = _insert_queue_item(session_queue, user_id=user_b)
+ _insert_queue_item(session_queue, user_id=admin_id)
+
+ in_progress = session_queue.dequeue()
+ assert in_progress is not None and in_progress.item_id == b_item_id
+
+ status = session_queue.get_queue_status(queue_id="default", user_id=admin_id, is_admin=True)
+
+ # Admins are not subject to current-item redaction.
+ assert status.item_id == b_item_id
+ assert status.session_id is not None
+ assert status.batch_id is not None
+ # Global counts plus the admin's own subcounts.
+ assert status.in_progress == 1 # B's item, counted globally
+ assert status.user_in_progress == 0 # the admin owns none in progress
+ assert status.user_pending == 1 # the admin's single pending item
+
+
def test_get_queue_item_ids_returns_all_users_ids(session_queue: SqliteSessionQueue) -> None:
"""get_queue_item_ids returns ids for every user so the virtualized list can show the
(redacted) entries belonging to other users. Redaction happens at hydration time."""
diff --git a/tests/app/test_invocation_event_socketio.py b/tests/app/test_invocation_event_socketio.py
new file mode 100644
index 0000000000..33c71f0cda
--- /dev/null
+++ b/tests/app/test_invocation_event_socketio.py
@@ -0,0 +1,169 @@
+"""Tests for socket routing of invocation events in multiuser mode.
+
+Invocation progress events drive personal UI (the global progress bar and progress image
+previews) and must be delivered only to the owner - admins receiving other users' progress
+would see their own progress display hijacked. The other invocation events (started,
+complete, error) also feed admins' gallery cache updates, so they go to the owner and the
+admin room - but in a single emit so that an admin who owns the queue item (which includes
+the "system" user in single-user mode) receives exactly one copy.
+"""
+
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import FastAPI
+
+from invokeai.app.api.sockets import SocketIO
+from invokeai.app.services.events.events_common import (
+ InvocationCompleteEvent,
+ InvocationErrorEvent,
+ InvocationProgressEvent,
+ InvocationStartedEvent,
+)
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+_COMMON_FIELDS = {
+ "queue_id": "default",
+ "item_id": 1,
+ "batch_id": "batch-1",
+ "user_id": "owner-1",
+ "session_id": "session-1",
+ "invocation": {"type": "add", "id": "node-1", "a": 1, "b": 2},
+ "invocation_source_id": "node-1",
+}
+
+
+async def test_progress_event_is_emitted_only_to_owner() -> None:
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ event = InvocationProgressEvent(**_COMMON_FIELDS, message="denoising", percentage=0.5)
+
+ await socketio._handle_queue_event(("invocation_progress", event))
+
+ socketio._sio.emit.assert_awaited_once_with(
+ event="invocation_progress",
+ data=event.model_dump(mode="json"),
+ room="user:owner-1",
+ )
+
+
+async def test_complete_event_is_emitted_once_to_owner_and_admin_rooms() -> None:
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ event = InvocationCompleteEvent(**_COMMON_FIELDS, result={"type": "integer_output", "value": 3})
+
+ await socketio._handle_queue_event(("invocation_complete", event))
+
+ # A single emit to the union of rooms - python-socketio dedupes recipients across a room
+ # list, so an admin owner (or the single-user "system" user) receives exactly one copy.
+ socketio._sio.emit.assert_awaited_once_with(
+ event="invocation_complete",
+ data=event.model_dump(mode="json"),
+ room=["user:owner-1", "admin"],
+ )
+
+
+async def test_started_event_is_emitted_once_to_owner_and_admin_rooms() -> None:
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ event = InvocationStartedEvent(**_COMMON_FIELDS)
+
+ await socketio._handle_queue_event(("invocation_started", event))
+
+ socketio._sio.emit.assert_awaited_once_with(
+ event="invocation_started",
+ data=event.model_dump(mode="json"),
+ room=["user:owner-1", "admin"],
+ )
+
+
+async def test_error_event_is_emitted_once_to_owner_and_admin_rooms() -> None:
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ event = InvocationErrorEvent(
+ **_COMMON_FIELDS,
+ error_type="ValueError",
+ error_message="oops",
+ error_traceback="Traceback (most recent call last): ...",
+ )
+
+ await socketio._handle_queue_event(("invocation_error", event))
+
+ socketio._sio.emit.assert_awaited_once_with(
+ event="invocation_error",
+ data=event.model_dump(mode="json"),
+ room=["user:owner-1", "admin"],
+ )
+
+
+def _make_model_config():
+ from invokeai.backend.model_manager.configs.factory import AnyModelConfigValidator
+
+ return AnyModelConfigValidator.validate_python(
+ {
+ "key": "model-key-1",
+ "hash": "hash-1",
+ "path": "/models/some-model",
+ "name": "some-model",
+ "base": "sd-1",
+ "type": "vae",
+ "format": "diffusers",
+ "source": "/models/some-model",
+ "source_type": "path",
+ "file_size": 1024,
+ }
+ )
+
+
+async def test_model_load_events_are_emitted_only_to_triggering_user() -> None:
+ from invokeai.app.services.events.events_common import ModelLoadCompleteEvent, ModelLoadStartedEvent
+
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ config = _make_model_config()
+ started = ModelLoadStartedEvent.build(config, user_id="owner-1")
+ complete = ModelLoadCompleteEvent.build(config, user_id="owner-1")
+
+ await socketio._handle_model_event(("model_load_started", started))
+ await socketio._handle_model_event(("model_load_complete", complete))
+
+ socketio._sio.emit.assert_any_await(
+ event="model_load_started", data=started.model_dump(mode="json"), room="user:owner-1"
+ )
+ socketio._sio.emit.assert_any_await(
+ event="model_load_complete", data=complete.model_dump(mode="json"), room="user:owner-1"
+ )
+ assert socketio._sio.emit.await_count == 2
+
+
+async def test_model_install_events_remain_broadcast() -> None:
+ from invokeai.app.services.events.events_common import ModelInstallStartedEvent
+
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+
+ from types import SimpleNamespace
+
+ event = SimpleNamespace(model_dump=lambda mode="json": {"id": 1})
+ # Not a load event, so it takes the broadcast path (no room argument).
+ assert not isinstance(event, ModelInstallStartedEvent)
+
+ await socketio._handle_model_event(("model_install_started", event))
+
+ socketio._sio.emit.assert_awaited_once_with(event="model_install_started", data={"id": 1})