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(gallery): refresh the gallery when media is uploaded elsewhere

Lincoln Stein7e23aea1ca73
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.py
index 85d376d7d7..ae57226217 100644
--- a/invokeai/app/api/routers/_access.py
+++ b/invokeai/app/api/routers/_access.py
@@ -133,7 +133,7 @@ def assert_image_read_access(image_name: str, current_user: CurrentUserOrDefault
raise HTTPException(status_code=403, detail="Not authorized to access this image")
-def assert_board_write_access(board_id: str | None, current_user: CurrentUserOrDefault) -> None:
+def assert_board_write_access(board_id: str | None, current_user: CurrentUserOrDefault) -> BoardRecord | None:
"""Raise if the current user may not put media on this board.
`None` means "no board" — always allowed, so upload routes can pass their optional board
@@ -141,22 +141,38 @@ def assert_board_write_access(board_id: str | None, current_user: CurrentUserOrD
the board is Public (public boards accept contributions from any user).
Shared boards are deliberately read-only here: `Shared` grants visibility, not contribution.
+
+ Returns the board record it checked (None for no board) so callers that need the board — the
+ upload routes announce the upload with its visibility — do not look it up a second time.
"""
if board_id is None:
- return
+ return None
board = _get_board_record(board_id)
if current_user.is_admin:
- return
+ return board
if board.user_id == current_user.user_id:
- return
+ return board
if board.board_visibility == BoardVisibility.Public:
- return
+ return board
raise HTTPException(status_code=403, detail="Not authorized to modify this board")
+def board_share_recipients(board: BoardRecord | None) -> list[str]:
+ """The users who can see a private board through an explicit share.
+
+ Empty for no board and for Shared/Public boards, whose uploads are announced to everyone
+ rather than enumerated. This is how an upload route tells the socket layer which extra
+ users to notify without the socket layer reaching into storage per event.
+ """
+ if board is None or board.board_visibility is not BoardVisibility.Private:
+ return []
+
+ return ApiDependencies.invoker.services.board_records.get_shared_user_ids(board.board_id)
+
+
def assert_video_read_access(video_name: str, current_user: CurrentUserOrDefault) -> None:
"""Raise 403 if the current user may not view the video.
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index c7ce34e49c..49ec786a57 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -26,6 +26,9 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_image_read_access as _assert_image_read_access,
)
+from invokeai.app.api.routers._access import (
+ board_share_recipients as _board_share_recipients,
+)
from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.invocations.fields import MetadataField
@@ -35,6 +38,7 @@ from invokeai.app.services.image_records.image_records_common import (
ImageRecordChanges,
ImageRecordNotFoundException,
ResourceOrigin,
+ is_gallery_category,
)
from invokeai.app.services.images.images_common import (
DeleteImagesResult,
@@ -123,7 +127,7 @@ async def upload_image(
"""Uploads an image for the current user"""
# If uploading into a board, verify the user has write access.
# Public boards allow uploads from any authenticated user.
- await asyncio.to_thread(_assert_board_write_access, board_id, current_user)
+ board = await asyncio.to_thread(_assert_board_write_access, board_id, current_user)
await asyncio.to_thread(assert_image_move_maintenance_inactive)
@@ -189,15 +193,21 @@ async def upload_image(
is_intermediate=is_intermediate,
user_id=current_user.user_id,
)
-
- response.status_code = 201
- response.headers["Location"] = image_dto.image_url
-
- return image_dto
except Exception:
ApiDependencies.invoker.services.logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail="Failed to create image")
+ if not is_intermediate and is_gallery_category(image_category):
+ shared_user_ids = await asyncio.to_thread(_board_share_recipients, board)
+ ApiDependencies.invoker.services.events.emit_image_uploaded(
+ image_dto, user_id=current_user.user_id, board=board, shared_user_ids=shared_user_ids
+ )
+
+ response.status_code = 201
+ response.headers["Location"] = image_dto.image_url
+
+ return image_dto
+
class ImageUploadEntry(BaseModel):
image_dto: ImageDTO = Body(description="The image DTO")
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index 5ec8ddfe32..87b2bed445 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -33,10 +33,13 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_video_read_access as _assert_video_read_access,
)
+from invokeai.app.api.routers._access import (
+ board_share_recipients as _board_share_recipients,
+)
from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE
from invokeai.app.api.routers.images import WorkflowAndGraphResponse
from invokeai.app.invocations.fields import MetadataField, MetadataFieldValidator
-from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin, is_gallery_category
from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.video_records.video_records_common import (
@@ -442,7 +445,7 @@ async def upload_video(
) -> VideoDTO:
"""Uploads a video for the current user."""
# Check board access for uploads to a specific board.
- await run_in_threadpool(_assert_board_write_access, board_id, current_user)
+ board = await run_in_threadpool(_assert_board_write_access, board_id, current_user)
# Stream the upload straight into a tmp file so we can probe it and then hand its path
# to the service. Reading the full body into memory first risked exhausting RAM on
@@ -545,13 +548,19 @@ async def upload_video(
user_id=current_user.user_id,
)
)
-
- response.status_code = 201
- response.headers["Location"] = video_dto.video_url
- return video_dto
except Exception:
ApiDependencies.invoker.services.logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail="Failed to create video")
+
+ if not is_intermediate and is_gallery_category(video_category):
+ shared_user_ids = await run_in_threadpool(_board_share_recipients, board)
+ ApiDependencies.invoker.services.events.emit_video_uploaded(
+ video_dto, user_id=current_user.user_id, board=board, shared_user_ids=shared_user_ids
+ )
+
+ response.status_code = 201
+ response.headers["Location"] = video_dto.video_url
+ return video_dto
finally:
# If create() succeeded the file was moved; this unlink is a no-op then.
try:
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py
index 685d977489..02f58d494f 100644
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@ -11,6 +11,7 @@ from starlette.concurrency import run_in_threadpool
from starlette.types import Message, Receive, Scope, Send
from invokeai.app.services.auth.token_service import verify_token
+from invokeai.app.services.board_records.board_records_common import BoardVisibility
from invokeai.app.services.config.config_default import get_config
from invokeai.app.services.events.events_common import (
BatchEnqueuedEvent,
@@ -29,6 +30,7 @@ from invokeai.app.services.events.events_common import (
ImageIndexStatusEvent,
ImageIndexUpdatedEvent,
ImageMapProjectionReadyEvent,
+ ImageUploadedEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
@@ -37,6 +39,7 @@ from invokeai.app.services.events.events_common import (
LLMTaskErrorEvent,
LLMTaskEventBase,
LLMTaskProgressEvent,
+ MediaUploadedEventBase,
ModelEventBase,
ModelInstallCancelledEvent,
ModelInstallCompleteEvent,
@@ -54,6 +57,7 @@ from invokeai.app.services.events.events_common import (
QueueItemStatusChangedEvent,
RecallParametersUpdatedEvent,
UserAccessChangedEvent,
+ VideoUploadedEvent,
WorkflowAccessRevokedEvent,
WorkflowCreatedEvent,
WorkflowDeletedEvent,
@@ -132,6 +136,7 @@ WORKFLOW_EVENTS = {WorkflowCreatedEvent, WorkflowUpdatedEvent, WorkflowDeletedEv
USER_EVENTS = {UserAccessChangedEvent}
IMAGE_INDEX_EVENTS = {ImageIndexStatusEvent, ImageIndexUpdatedEvent, ImageMapProjectionReadyEvent}
+MEDIA_EVENTS = {ImageUploadedEvent, VideoUploadedEvent}
MODEL_INSTALL_EVENTS = (
ModelInstallDownloadStartedEvent,
@@ -240,6 +245,7 @@ class SocketIO:
register_events(LLM_TASK_EVENTS, self._handle_llm_task_event)
register_events(WORKFLOW_EVENTS, self._handle_workflow_event)
register_events(IMAGE_INDEX_EVENTS, self._handle_image_index_event)
+ register_events(MEDIA_EVENTS, self._handle_media_event)
register_events(USER_EVENTS, self._handle_user_access_changed)
async def _handle_connect(self, sid: str, environ: dict, auth: dict | None) -> bool:
@@ -1222,6 +1228,33 @@ class SocketIO:
# admins only (single-user mode's sole user is an admin).
await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+ async def _handle_media_event(self, event: FastAPIEvent[MediaUploadedEventBase]) -> None:
+ """Route an upload to the clients whose gallery can show it.
+
+ Shared and Public boards are visible to every user, so those uploads go to everyone.
+ Anything else — a private board or no board at all — goes to the uploader, the board's
+ owner (an admin may upload into someone else's private board), the users that board is
+ explicitly shared with, and admins, who see every board. The route resolves the share
+ list, so routing an event stays free of storage access.
+ """
+ event_name, event_data = event
+ payload = event_data.model_dump(mode="json")
+
+ if not self._is_multiuser_enabled():
+ await self._sio.emit(event=event_name, data=payload, room="admin")
+ return
+
+ if event_data.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):
+ await self._sio.emit(event=event_name, data=payload)
+ return
+
+ rooms = [f"user:{event_data.user_id}", "admin"]
+ if event_data.board_owner_id is not None and event_data.board_owner_id != event_data.user_id:
+ rooms.append(f"user:{event_data.board_owner_id}")
+ # A room the socket is already in costs nothing: python-socketio unions a room list by sid.
+ rooms.extend(f"user:{user_id}" for user_id in event_data.shared_user_ids)
+ await self._sio.emit(event=event_name, data=payload, room=rooms)
+
async def _handle_bulk_image_download_event(self, event: FastAPIEvent[BulkDownloadEventBase]) -> None:
event_name, event_data = event
# Route to user-specific + admin rooms so that other authenticated
diff --git a/invokeai/app/services/board_records/board_records_base.py b/invokeai/app/services/board_records/board_records_base.py
index 377f6a70b5..7eb98ccd09 100644
--- a/invokeai/app/services/board_records/board_records_base.py
+++ b/invokeai/app/services/board_records/board_records_base.py
@@ -65,6 +65,11 @@ class BoardRecordStorageBase(ABC):
"""Checks whether a board has been explicitly shared with a specific user."""
pass
+ @abstractmethod
+ def get_shared_user_ids(self, board_id: str) -> list[str]:
+ """Gets the ids of the users a board has been explicitly shared with."""
+ pass
+
@abstractmethod
def get_many(
self,
diff --git a/invokeai/app/services/board_records/board_records_sqlite.py b/invokeai/app/services/board_records/board_records_sqlite.py
index 6573ad40dc..79c3fbb2e4 100644
--- a/invokeai/app/services/board_records/board_records_sqlite.py
+++ b/invokeai/app/services/board_records/board_records_sqlite.py
@@ -149,6 +149,19 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
return cursor.fetchone() is not None
+ def get_shared_user_ids(self, board_id: str) -> list[str]:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT user_id
+ FROM shared_boards
+ WHERE board_id = ?;
+ """,
+ (board_id,),
+ )
+
+ return [row["user_id"] for row in cursor.fetchall()]
+
def update(
self,
board_id: str,
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index f4e3565d71..7c6fa13757 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -18,6 +18,7 @@ from invokeai.app.services.events.events_common import (
ImageIndexStatusEvent,
ImageIndexUpdatedEvent,
ImageMapProjectionReadyEvent,
+ ImageUploadedEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
@@ -40,6 +41,7 @@ from invokeai.app.services.events.events_common import (
QueueItemStatusChangedEvent,
RecallParametersUpdatedEvent,
UserAccessChangedEvent,
+ VideoUploadedEvent,
WorkflowCreatedEvent,
WorkflowDeletedEvent,
WorkflowUpdatedEvent,
@@ -47,7 +49,9 @@ from invokeai.app.services.events.events_common import (
if TYPE_CHECKING:
from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput
+ from invokeai.app.services.board_records.board_records_common import BoardRecord
from invokeai.app.services.download.download_base import DownloadJob
+ from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.model_install.model_install_common import ModelInstallJob
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.session_queue.session_queue_common import (
@@ -57,6 +61,7 @@ if TYPE_CHECKING:
SessionQueueItem,
SessionQueueStatus,
)
+ from invokeai.app.services.videos.videos_common import VideoDTO
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.taxonomy import SubModelType
@@ -354,3 +359,42 @@ class EventServiceBase:
self.dispatch(ImageMapProjectionReadyEvent.build(user_id=user_id, point_count=point_count))
# endregion
+
+ # region Media uploads
+
+ def emit_image_uploaded(
+ self, image_dto: "ImageDTO", user_id: str, board: Optional["BoardRecord"], shared_user_ids: list[str]
+ ) -> None:
+ """Emitted when a gallery-visible image arrives through the upload API; `board` is the one it was sent to"""
+ # The board attach can fail quietly inside create(); the DTO says where the image actually is.
+ board = board if image_dto.board_id is not None else None
+ self.dispatch(
+ ImageUploadedEvent.build(
+ image_name=image_dto.image_name,
+ image_category=image_dto.image_category,
+ user_id=user_id,
+ board_id=image_dto.board_id,
+ board_owner_id=board.user_id if board else None,
+ board_visibility=board.board_visibility if board else None,
+ shared_user_ids=shared_user_ids if board else [],
+ )
+ )
+
+ def emit_video_uploaded(
+ self, video_dto: "VideoDTO", user_id: str, board: Optional["BoardRecord"], shared_user_ids: list[str]
+ ) -> None:
+ """Emitted when a gallery-visible video arrives through the upload API; `board` is the one it was sent to"""
+ board = board if video_dto.board_id is not None else None
+ self.dispatch(
+ VideoUploadedEvent.build(
+ video_name=video_dto.video_name,
+ video_category=video_dto.video_category,
+ user_id=user_id,
+ board_id=video_dto.board_id,
+ board_owner_id=board.user_id if board else None,
+ board_visibility=board.board_visibility if board else None,
+ shared_user_ids=shared_user_ids if board else [],
+ )
+ )
+
+ # endregion
diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.py
index f1837b23fa..a604ef4d77 100644
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@ -4,6 +4,8 @@ from fastapi_events.handlers.local import local_handler
from fastapi_events.registry.payload_schema import registry as payload_schema
from pydantic import BaseModel, ConfigDict, Field
+from invokeai.app.services.board_records.board_records_common import BoardVisibility
+from invokeai.app.services.image_records.image_records_common import ImageCategory
from invokeai.app.services.model_install.model_install_common import ModelInstallJob, ModelSource
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.session_queue.session_queue_common import (
@@ -953,6 +955,90 @@ class ImageMapProjectionReadyEvent(ImageIndexEventBase):
return cls(user_id=user_id, point_count=point_count)
+class MediaUploadedEventBase(EventBase):
+ """Base class for media upload events.
+
+ Tells clients that gallery content appeared through the upload API, which no queue event
+ announces. Emitted for gallery-visible uploads only: intermediates and canvas-owned OTHER
+ category images never show in the gallery, and canvas editing uploads both constantly.
+ """
+
+ user_id: str = Field(description="The user who uploaded the media")
+ board_id: Optional[str] = Field(default=None, description="The board the media was added to, if any")
+ board_owner_id: Optional[str] = Field(
+ default=None, description="The owner of that board, who may differ from the uploader; None for no board"
+ )
+ board_visibility: Optional[BoardVisibility] = Field(
+ default=None, description="The visibility of that board; None when the media landed on no board"
+ )
+ shared_user_ids: list[str] = Field(
+ default_factory=list,
+ description="Users a private board is explicitly shared with, who can see this media too",
+ )
+
+
+@payload_schema.register
+class ImageUploadedEvent(MediaUploadedEventBase):
+ """Event model for image_uploaded"""
+
+ __event_name__ = "image_uploaded"
+
+ image_name: str = Field(description="The name of the uploaded image")
+ image_category: ImageCategory = Field(description="The category of the uploaded image")
+
+ @classmethod
+ def build(
+ cls,
+ image_name: str,
+ image_category: ImageCategory,
+ user_id: str,
+ board_id: Optional[str],
+ board_owner_id: Optional[str],
+ board_visibility: Optional[BoardVisibility],
+ shared_user_ids: list[str],
+ ) -> "ImageUploadedEvent":
+ return cls(
+ image_name=image_name,
+ image_category=image_category,
+ user_id=user_id,
+ board_id=board_id,
+ board_owner_id=board_owner_id,
+ board_visibility=board_visibility,
+ shared_user_ids=shared_user_ids,
+ )
+
+
+@payload_schema.register
+class VideoUploadedEvent(MediaUploadedEventBase):
+ """Event model for video_uploaded"""
+
+ __event_name__ = "video_uploaded"
+
+ video_name: str = Field(description="The name of the uploaded video")
+ video_category: ImageCategory = Field(description="The category of the uploaded video")
+
+ @classmethod
+ def build(
+ cls,
+ video_name: str,
+ video_category: ImageCategory,
+ user_id: str,
+ board_id: Optional[str],
+ board_owner_id: Optional[str],
+ board_visibility: Optional[BoardVisibility],
+ shared_user_ids: list[str],
+ ) -> "VideoUploadedEvent":
+ return cls(
+ video_name=video_name,
+ video_category=video_category,
+ user_id=user_id,
+ board_id=board_id,
+ board_owner_id=board_owner_id,
+ board_visibility=board_visibility,
+ shared_user_ids=shared_user_ids,
+ )
+
+
class UserAccessChangedEvent(EventBase):
"""Event model for user_access_changed.
diff --git a/invokeai/app/services/image_records/image_records_common.py b/invokeai/app/services/image_records/image_records_common.py
index 44faa6305a..d60cecf5b7 100644
--- a/invokeai/app/services/image_records/image_records_common.py
+++ b/invokeai/app/services/image_records/image_records_common.py
@@ -75,6 +75,11 @@ at it — without ever surfacing in the gallery or in a board's counts.
"""
+def is_gallery_category(category: ImageCategory) -> bool:
+ """Whether media of this category shows in a gallery view (Images or Assets)."""
+ return category in IMAGE_CATEGORIES or category in ASSETS_CATEGORIES
+
+
class InvalidImageCategoryException(ValueError):
"""Raised when a provided value is not a valid ImageCategory.
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index fdb5ab8b6f..63fa48f4f3 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -47107,6 +47107,88 @@
"required": ["image_dto", "presigned_url"],
"title": "ImageUploadEntry"
},
+ "ImageUploadedEvent": {
+ "description": "Event model for image_uploaded",
+ "properties": {
+ "timestamp": {
+ "description": "The timestamp of the event",
+ "title": "Timestamp",
+ "type": "integer"
+ },
+ "user_id": {
+ "description": "The user who uploaded the media",
+ "title": "User Id",
+ "type": "string"
+ },
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The board the media was added to, if any",
+ "title": "Board Id"
+ },
+ "board_owner_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The owner of that board, who may differ from the uploader; None for no board",
+ "title": "Board Owner Id"
+ },
+ "board_visibility": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/BoardVisibility"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The visibility of that board; None when the media landed on no board"
+ },
+ "shared_user_ids": {
+ "description": "Users a private board is explicitly shared with, who can see this media too",
+ "items": {
+ "type": "string"
+ },
+ "title": "Shared User Ids",
+ "type": "array"
+ },
+ "image_name": {
+ "description": "The name of the uploaded image",
+ "title": "Image Name",
+ "type": "string"
+ },
+ "image_category": {
+ "$ref": "#/components/schemas/ImageCategory",
+ "description": "The category of the uploaded image"
+ }
+ },
+ "required": [
+ "timestamp",
+ "user_id",
+ "board_id",
+ "board_owner_id",
+ "board_visibility",
+ "shared_user_ids",
+ "image_name",
+ "image_category"
+ ],
+ "title": "ImageUploadedEvent",
+ "type": "object"
+ },
"ImageUrlsDTO": {
"properties": {
"image_name": {
@@ -99465,6 +99547,88 @@
"title": "VideoRecordChanges",
"description": "Allowed mutations on a video record."
},
+ "VideoUploadedEvent": {
+ "description": "Event model for video_uploaded",
+ "properties": {
+ "timestamp": {
+ "description": "The timestamp of the event",
+ "title": "Timestamp",
+ "type": "integer"
+ },
+ "user_id": {
+ "description": "The user who uploaded the media",
+ "title": "User Id",
+ "type": "string"
+ },
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The board the media was added to, if any",
+ "title": "Board Id"
+ },
+ "board_owner_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The owner of that board, who may differ from the uploader; None for no board",
+ "title": "Board Owner Id"
+ },
+ "board_visibility": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/BoardVisibility"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The visibility of that board; None when the media landed on no board"
+ },
+ "shared_user_ids": {
+ "description": "Users a private board is explicitly shared with, who can see this media too",
+ "items": {
+ "type": "string"
+ },
+ "title": "Shared User Ids",
+ "type": "array"
+ },
+ "video_name": {
+ "description": "The name of the uploaded video",
+ "title": "Video Name",
+ "type": "string"
+ },
+ "video_category": {
+ "$ref": "#/components/schemas/ImageCategory",
+ "description": "The category of the uploaded video"
+ }
+ },
+ "required": [
+ "timestamp",
+ "user_id",
+ "board_id",
+ "board_owner_id",
+ "board_visibility",
+ "shared_user_ids",
+ "video_name",
+ "video_category"
+ ],
+ "title": "VideoUploadedEvent",
+ "type": "object"
+ },
"VideoUrlsDTO": {
"properties": {
"video_name": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index bf068ba398..af0650ccda 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -19718,6 +19718,51 @@ export type components = {
*/
presigned_url: string;
};
+ /**
+ * ImageUploadedEvent
+ * @description Event model for image_uploaded
+ */
+ ImageUploadedEvent: {
+ /**
+ * Timestamp
+ * @description The timestamp of the event
+ */
+ timestamp: number;
+ /**
+ * User Id
+ * @description The user who uploaded the media
+ */
+ user_id: string;
+ /**
+ * Board Id
+ * @description The board the media was added to, if any
+ * @default null
+ */
+ board_id: string | null;
+ /**
+ * Board Owner Id
+ * @description The owner of that board, who may differ from the uploader; None for no board
+ * @default null
+ */
+ board_owner_id: string | null;
+ /**
+ * @description The visibility of that board; None when the media landed on no board
+ * @default null
+ */
+ board_visibility: components["schemas"]["BoardVisibility"] | null;
+ /**
+ * Shared User Ids
+ * @description Users a private board is explicitly shared with, who can see this media too
+ */
+ shared_user_ids: string[];
+ /**
+ * Image Name
+ * @description The name of the uploaded image
+ */
+ image_name: string;
+ /** @description The category of the uploaded image */
+ image_category: components["schemas"]["ImageCategory"];
+ };
/**
* ImageUrlsDTO
* @description The URLs for an image and its thumbnail.
@@ -44274,6 +44319,51 @@ export type components = {
} & {
[key: string]: unknown;
};
+ /**
+ * VideoUploadedEvent
+ * @description Event model for video_uploaded
+ */
+ VideoUploadedEvent: {
+ /**
+ * Timestamp
+ * @description The timestamp of the event
+ */
+ timestamp: number;
+ /**
+ * User Id
+ * @description The user who uploaded the media
+ */
+ user_id: string;
+ /**
+ * Board Id
+ * @description The board the media was added to, if any
+ * @default null
+ */
+ board_id: string | null;
+ /**
+ * Board Owner Id
+ * @description The owner of that board, who may differ from the uploader; None for no board
+ * @default null
+ */
+ board_owner_id: string | null;
+ /**
+ * @description The visibility of that board; None when the media landed on no board
+ * @default null
+ */
+ board_visibility: components["schemas"]["BoardVisibility"] | null;
+ /**
+ * Shared User Ids
+ * @description Users a private board is explicitly shared with, who can see this media too
+ */
+ shared_user_ids: string[];
+ /**
+ * Video Name
+ * @description The name of the uploaded video
+ */
+ video_name: string;
+ /** @description The category of the uploaded video */
+ video_category: components["schemas"]["ImageCategory"];
+ };
/**
* VideoUrlsDTO
* @description The URLs for a video and its thumbnail.
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 4e3c4f3f34..bdc7e3e931 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,12 +2,12 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 889734,
+ "brotliBytes": 890011,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 888487,
+ "gzipBytes": 888798,
"imageRawBytes": 156376,
- "initialRawBytes": 2111810,
+ "initialRawBytes": 2112432,
"largestAssetRawBytes": 778932,
"otherAssetRawBytes": 0,
"ownedRawBytes": 87580,
@@ -318,15 +318,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1216517,
+ "brotliBytes": 1220168,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1210216,
+ "gzipBytes": 1214071,
"imageRawBytes": 156376,
- "initialRawBytes": 3109003,
+ "initialRawBytes": 3121862,
"largestAssetRawBytes": 778932,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 139420,
+ "ownedRawBytes": 140544,
"requestCount": 86,
"scriptRequestCount": 70,
"sourceOwners": [
@@ -446,6 +446,7 @@
"source:src/app/AppProviders.tsx",
"source:src/app/BootWidgetHintController.tsx",
"source:src/app/FeatureHintsProvider.tsx",
+ "source:src/app/GalleryRealtimeRuntime.tsx",
"source:src/app/GalleryUiAdapter.tsx",
"source:src/app/GenerateWidgetSyncRuntime.tsx",
"source:src/app/GenerationUiAdapter.tsx",
@@ -482,6 +483,7 @@
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
"source:src/features/gallery/data/queryCache.ts",
+ "source:src/features/gallery/data/realtimeRuntime.ts",
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/picker.ts",
"source:src/features/gallery/queries.ts",
@@ -1028,7 +1030,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-09-18",
+ "capturedAt": "2026-09-19",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index e9193c68c5..fd66fc93a9 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
- "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",
- "capturedAt": "2026-09-18",
+ "browserExecutable": "/home/lstein/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",
+ "capturedAt": "2026-09-19",
"routes": [
{
"activatedResourceBaseline": {
@@ -14,13 +14,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 122.89999999850988,
+ "domContentLoadedMedianMs": 109.89999997615814,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 123.09999999403954,
- "longestTaskMaxMs": 74,
+ "loadMedianMs": 110,
+ "longestTaskMaxMs": 97,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -30,13 +30,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
+ "otherRawBytes": 155792,
"requestCount": 32,
- "scriptRawBytes": 1793708,
+ "scriptRawBytes": 1795098,
"scriptRequestCount": 28,
- "totalRawBytes": 1974032
+ "totalRawBytes": 1976713
},
- "routeReadyMedianMs": 258,
+ "routeReadyMedianMs": 255.89999997615814,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -52,13 +52,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 120.79999999701977,
+ "domContentLoadedMedianMs": 107.29999995231628,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 121,
- "longestTaskMaxMs": 73,
+ "loadMedianMs": 107.39999997615814,
+ "longestTaskMaxMs": 71,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -68,13 +68,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
+ "otherRawBytes": 155792,
"requestCount": 32,
- "scriptRawBytes": 1793708,
+ "scriptRawBytes": 1795098,
"scriptRequestCount": 28,
- "totalRawBytes": 1974032
+ "totalRawBytes": 1976713
},
- "routeReadyMedianMs": 269.1000000014901,
+ "routeReadyMedianMs": 248.19999992847443,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -90,15 +90,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119.70000000298023,
+ "domContentLoadedMedianMs": 98.09999990463257,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 119.89999999850988,
- "longestTaskMaxMs": 154,
+ "loadMedianMs": 98.19999992847443,
+ "longestTaskMaxMs": 143,
"owner": "workbench",
- "projectSwitchMedianMs": 33.100000001490116,
+ "projectSwitchMedianMs": 28.200000047683716,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -106,13 +106,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 101,
- "scriptRawBytes": 3683643,
- "scriptRequestCount": 96,
- "totalRawBytes": 4020343
+ "otherRawBytes": 155792,
+ "requestCount": 100,
+ "scriptRawBytes": 3698663,
+ "scriptRequestCount": 95,
+ "totalRawBytes": 4036654
},
- "routeReadyMedianMs": 410.59999999403954,
+ "routeReadyMedianMs": 347.6999999284744,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -128,15 +128,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118.5,
+ "domContentLoadedMedianMs": 104.29999995231628,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 118.69999999552965,
- "longestTaskMaxMs": 152,
+ "loadMedianMs": 104.39999997615814,
+ "longestTaskMaxMs": 143,
"owner": "workbench",
- "projectSwitchMedianMs": 45.900000005960464,
+ "projectSwitchMedianMs": 42.299999952316284,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -144,13 +144,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 101,
- "scriptRawBytes": 3683643,
- "scriptRequestCount": 96,
- "totalRawBytes": 4020343
+ "otherRawBytes": 155792,
+ "requestCount": 100,
+ "scriptRawBytes": 3698663,
+ "scriptRequestCount": 95,
+ "totalRawBytes": 4036654
},
- "routeReadyMedianMs": 420.6000000014901,
+ "routeReadyMedianMs": 359.2000000476837,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -162,17 +162,17 @@
"largestAssetRawBytes": 309208,
"otherRawBytes": 0,
"requestCount": 10,
- "scriptRawBytes": 503300,
+ "scriptRawBytes": 503283,
"scriptRequestCount": 10,
- "totalRawBytes": 503300
+ "totalRawBytes": 503283
},
- "domContentLoadedMedianMs": 121.29999999701977,
+ "domContentLoadedMedianMs": 99.39999997615814,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 45.19999999552965,
- "layoutSwitchMedianMs": 85.30000000447035,
- "loadMedianMs": 121.39999999850988,
- "longestTaskMaxMs": 151,
+ "layoutAckMedianMs": 2.200000047683716,
+ "layoutReturnSwitchMedianMs": 48.39999997615814,
+ "layoutSwitchMedianMs": 71.39999997615814,
+ "loadMedianMs": 99.60000002384186,
+ "longestTaskMaxMs": 135,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -182,13 +182,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 111,
- "scriptRawBytes": 4186943,
- "scriptRequestCount": 106,
- "totalRawBytes": 4523643
+ "otherRawBytes": 155792,
+ "requestCount": 110,
+ "scriptRawBytes": 4201946,
+ "scriptRequestCount": 105,
+ "totalRawBytes": 4539937
},
- "routeReadyMedianMs": 1109.2999999970198,
+ "routeReadyMedianMs": 1029.1000000238419,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -200,17 +200,17 @@
"largestAssetRawBytes": 309208,
"otherRawBytes": 0,
"requestCount": 10,
- "scriptRawBytes": 503300,
+ "scriptRawBytes": 503283,
"scriptRequestCount": 10,
- "totalRawBytes": 503300
+ "totalRawBytes": 503283
},
- "domContentLoadedMedianMs": 119.39999999850988,
+ "domContentLoadedMedianMs": 100.10000002384186,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.399999998509884,
- "layoutReturnSwitchMedianMs": 44.20000000298023,
- "layoutSwitchMedianMs": 82,
- "loadMedianMs": 119.5,
- "longestTaskMaxMs": 205,
+ "layoutAckMedianMs": 2.399999976158142,
+ "layoutReturnSwitchMedianMs": 45.10000002384186,
+ "layoutSwitchMedianMs": 73,
+ "loadMedianMs": 100.20000004768372,
+ "longestTaskMaxMs": 157,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -220,13 +220,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 111,
- "scriptRawBytes": 4186943,
- "scriptRequestCount": 106,
- "totalRawBytes": 4523643
+ "otherRawBytes": 155792,
+ "requestCount": 110,
+ "scriptRawBytes": 4201946,
+ "scriptRequestCount": 105,
+ "totalRawBytes": 4539937
},
- "routeReadyMedianMs": 1107.0999999940395,
+ "routeReadyMedianMs": 1017,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -238,17 +238,17 @@
"largestAssetRawBytes": 175033,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 385926,
+ "scriptRawBytes": 388639,
"scriptRequestCount": 6,
- "totalRawBytes": 401339
+ "totalRawBytes": 404052
},
- "domContentLoadedMedianMs": 123.79999999701977,
+ "domContentLoadedMedianMs": 99.69999992847443,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 33.5,
- "layoutSwitchMedianMs": 89.70000000298023,
- "loadMedianMs": 124,
- "longestTaskMaxMs": 148,
+ "layoutAckMedianMs": 2.600000023841858,
+ "layoutReturnSwitchMedianMs": 30.100000023841858,
+ "layoutSwitchMedianMs": 75.70000004768372,
+ "loadMedianMs": 99.89999997615814,
+ "longestTaskMaxMs": 134,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -258,13 +258,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 108,
- "scriptRawBytes": 4069569,
- "scriptRequestCount": 102,
- "totalRawBytes": 4421682
+ "otherRawBytes": 155792,
+ "requestCount": 107,
+ "scriptRawBytes": 4087302,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 4440706
},
- "routeReadyMedianMs": 1118.1000000014901,
+ "routeReadyMedianMs": 1032,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -276,17 +276,17 @@
"largestAssetRawBytes": 175033,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 385926,
+ "scriptRawBytes": 388639,
"scriptRequestCount": 6,
- "totalRawBytes": 401339
+ "totalRawBytes": 404052
},
- "domContentLoadedMedianMs": 122.20000000298023,
+ "domContentLoadedMedianMs": 99.69999992847443,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.3000000044703484,
- "layoutReturnSwitchMedianMs": 38.69999999552965,
- "layoutSwitchMedianMs": 131.39999999850988,
- "loadMedianMs": 122.29999999701977,
- "longestTaskMaxMs": 383,
+ "layoutAckMedianMs": 2.299999952316284,
+ "layoutReturnSwitchMedianMs": 35.5,
+ "layoutSwitchMedianMs": 110.39999997615814,
+ "loadMedianMs": 99.89999997615814,
+ "longestTaskMaxMs": 302,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -296,13 +296,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 108,
- "scriptRawBytes": 4069569,
- "scriptRequestCount": 102,
- "totalRawBytes": 4421682
+ "otherRawBytes": 155792,
+ "requestCount": 107,
+ "scriptRawBytes": 4087302,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 4440706
},
- "routeReadyMedianMs": 1159.1000000014901,
+ "routeReadyMedianMs": 1085.2999999523163,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -318,13 +318,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119.89999999850988,
+ "domContentLoadedMedianMs": 94.89999997615814,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 44,
- "loadMedianMs": 120,
- "longestTaskMaxMs": 153,
+ "layoutSwitchMedianMs": 35.89999997615814,
+ "loadMedianMs": 95.10000002384186,
+ "longestTaskMaxMs": 134,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -334,13 +334,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 101,
- "scriptRawBytes": 3683643,
- "scriptRequestCount": 96,
- "totalRawBytes": 4020343
+ "otherRawBytes": 155792,
+ "requestCount": 100,
+ "scriptRawBytes": 3698663,
+ "scriptRequestCount": 95,
+ "totalRawBytes": 4036654
},
- "routeReadyMedianMs": 1343.6000000014901,
+ "routeReadyMedianMs": 1246,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -356,13 +356,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119.79999999701977,
+ "domContentLoadedMedianMs": 96,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 59.399999998509884,
- "loadMedianMs": 120,
- "longestTaskMaxMs": 152,
+ "layoutSwitchMedianMs": 49.5,
+ "loadMedianMs": 96.20000004768372,
+ "longestTaskMaxMs": 140,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -372,13 +372,13 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 778932,
- "otherRawBytes": 154501,
- "requestCount": 101,
- "scriptRawBytes": 3683643,
- "scriptRequestCount": 96,
- "totalRawBytes": 4020343
+ "otherRawBytes": 155792,
+ "requestCount": 100,
+ "scriptRawBytes": 3698663,
+ "scriptRequestCount": 95,
+ "totalRawBytes": 4036654
},
- "routeReadyMedianMs": 1362.3000000044703,
+ "routeReadyMedianMs": 1266.2999999523163,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -841,6 +841,7 @@
"source:src/app/BootWidgetHintController.tsx",
"source:src/app/FeatureHintsProvider.tsx",
"source:src/app/GalleryImageActionsBridge.tsx",
+ "source:src/app/GalleryRealtimeRuntime.tsx",
"source:src/app/GalleryUiAdapter.tsx",
"source:src/app/GenerateWidgetSyncRuntime.tsx",
"source:src/app/GenerationUiAdapter.tsx",
@@ -877,6 +878,7 @@
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
"source:src/features/gallery/data/queryCache.ts",
+ "source:src/features/gallery/data/realtimeRuntime.ts",
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/index.ts",
"source:src/features/gallery/mediaSlot.ts",
@@ -1869,6 +1871,7 @@
"source:src/app/BootWidgetHintController.tsx",
"source:src/app/FeatureHintsProvider.tsx",
"source:src/app/GalleryImageActionsBridge.tsx",
+ "source:src/app/GalleryRealtimeRuntime.tsx",
"source:src/app/GalleryUiAdapter.tsx",
"source:src/app/GenerateWidgetSyncRuntime.tsx",
"source:src/app/GenerationUiAdapter.tsx",
@@ -1905,6 +1908,7 @@
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
"source:src/features/gallery/data/queryCache.ts",
+ "source:src/features/gallery/data/realtimeRuntime.ts",
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/index.ts",
"source:src/features/gallery/mediaSlot.ts",
@@ -3067,6 +3071,7 @@
"source:src/app/BootWidgetHintController.tsx",
"source:src/app/FeatureHintsProvider.tsx",
"source:src/app/GalleryImageActionsBridge.tsx",
+ "source:src/app/GalleryRealtimeRuntime.tsx",
"source:src/app/GalleryUiAdapter.tsx",
"source:src/app/GenerateWidgetSyncRuntime.tsx",
"source:src/app/GenerationUiAdapter.tsx",
@@ -3103,6 +3108,7 @@
"source:src/features/gallery/data/imageUrls.ts",
"source:src/features/gallery/data/queries.ts",
"source:src/features/gallery/data/queryCache.ts",
+ "source:src/features/gallery/data/realtimeRuntime.ts",
"source:src/features/gallery/data/videoUrls.ts",
"source:src/features/gallery/index.ts",
"source:src/features/gallery/mediaSlot.ts",
diff --git a/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx b/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx
new file mode 100644
index 0000000000..1f76463cb6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/GalleryRealtimeRuntime.tsx
@@ -0,0 +1,22 @@
+import { createGalleryRealtimeRuntime, invalidateGallery } from '@features/gallery/queries';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { socketHub } from '@platform/transport/socketHub';
+import { useQueryClient } from '@tanstack/react-query';
+
+/** App-owned composition: uploads the backend announces over the socket refresh the Gallery read model. */
+export const GalleryRealtimeRuntime = () => {
+ const queryClient = useQueryClient();
+
+ useMountEffect(() => {
+ const runtime = createGalleryRealtimeRuntime({
+ backend: socketHub,
+ invalidate: () => invalidateGallery(queryClient),
+ });
+
+ runtime.start();
+
+ return runtime.dispose;
+ });
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index 7afae5ced5..22a6788cd6 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -16,6 +16,7 @@ import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegis
import { useMemo } from 'react';
import { BootWidgetHintController } from './BootWidgetHintController';
+import { GalleryRealtimeRuntime } from './GalleryRealtimeRuntime';
import { GenerateWidgetSyncRuntime } from './GenerateWidgetSyncRuntime';
import { QueueRuntimeAdapter } from './QueueRuntimeAdapter';
import { RecallParametersRuntime } from './RecallParametersRuntime';
@@ -54,6 +55,7 @@ export const WorkbenchApp = () => {
<WorkbenchHotkeyRuntime />
<WorkbenchCommandPalette />
<QueueRuntimeAdapter />
+ <GalleryRealtimeRuntime />
<WorkbenchRuntime />
<WorkbenchSessionController search={search} />
<WidgetHosts />
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts
new file mode 100644
index 0000000000..ab1557e2fc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.test.ts
@@ -0,0 +1,151 @@
+import type { BackendConnectionStatus } from '@platform/transport/types';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createGalleryRealtimeRuntime } from './realtimeRuntime';
+
+describe('gallery realtime runtime', () => {
+ const handlers = new Map<string, (payload: never) => void>();
+ const detachers: Array<ReturnType<typeof vi.fn>> = [];
+ let connectionHandler: ((status: BackendConnectionStatus) => void) | null = null;
+ let initialStatus: BackendConnectionStatus = 'connected';
+ const backend = {
+ on: vi.fn((event: string, handler: (payload: never) => void) => {
+ handlers.set(event, handler);
+ const detach = vi.fn(() => handlers.delete(event));
+ detachers.push(detach);
+ return detach;
+ }),
+ onConnectionChange: vi.fn((handler: (status: BackendConnectionStatus) => void) => {
+ connectionHandler = handler;
+ handler(initialStatus);
+ const detach = vi.fn(() => {
+ connectionHandler = null;
+ });
+ detachers.push(detach);
+ return detach;
+ }),
+ };
+ const invalidate = vi.fn();
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ handlers.clear();
+ detachers.length = 0;
+ connectionHandler = null;
+ initialStatus = 'connected';
+ backend.on.mockClear();
+ backend.onConnectionChange.mockClear();
+ invalidate.mockReset();
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it('coalesces a burst of upload events into one invalidation and detaches on dispose', () => {
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+ runtime.start();
+ handlers.get('image_uploaded')?.({ image_name: 'a.png' } as never);
+ handlers.get('image_uploaded')?.({ image_name: 'b.png' } as never);
+ handlers.get('video_uploaded')?.({ video_name: 'c.mp4' } as never);
+
+ expect(backend.on).toHaveBeenCalledTimes(2);
+ expect(backend.onConnectionChange).toHaveBeenCalledTimes(1);
+ expect(invalidate).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).toHaveBeenCalledTimes(1);
+
+ runtime.dispose();
+ handlers.get('image_uploaded')?.({ image_name: 'd.png' } as never);
+ vi.advanceTimersByTime(250);
+
+ expect(detachers.every((detach) => detach.mock.calls.length === 1)).toBe(true);
+ expect(invalidate).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds passes a minimum interval apart under a stream of uploads and still runs a trailing pass', () => {
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+
+ // A bulk drop completing one file every 300 ms for 3 s: each echo would
+ // otherwise become its own pass, cancelling the page fetches under the user.
+ for (let elapsed = 0; elapsed < 3000; elapsed += 300) {
+ handlers.get('image_uploaded')?.({ image_name: `${elapsed}.png` } as never);
+ vi.advanceTimersByTime(300);
+ }
+
+ const passesDuringStream = invalidate.mock.calls.length;
+
+ expect(passesDuringStream).toBeGreaterThanOrEqual(2);
+ expect(passesDuringStream).toBeLessThanOrEqual(4);
+
+ vi.advanceTimersByTime(1000);
+
+ // The last file's echo landed after the final pass and must not be lost.
+ expect(invalidate).toHaveBeenCalledTimes(passesDuringStream + 1);
+ runtime.dispose();
+ });
+
+ it('refetches after an outage but not on the boot-time connect', () => {
+ initialStatus = 'connecting';
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+ connectionHandler?.('connected');
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).not.toHaveBeenCalled();
+
+ connectionHandler?.('disconnected');
+ connectionHandler?.('connected');
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).toHaveBeenCalledTimes(1);
+ runtime.dispose();
+ });
+
+ it('treats a connect after mounting on a downed backend as a reconnect', () => {
+ initialStatus = 'disconnected';
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+ connectionHandler?.('connected');
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).toHaveBeenCalledTimes(1);
+ runtime.dispose();
+ });
+
+ it('drops a pending invalidation on dispose', () => {
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+ handlers.get('image_uploaded')?.({ image_name: 'a.png' } as never);
+ runtime.dispose();
+
+ // Asserting the timer is gone, not just inert: the account-scope guard alone would
+ // keep a disposed runtime's timer alive on every navigation away from the editor.
+ expect(vi.getTimerCount()).toBe(0);
+
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).not.toHaveBeenCalled();
+ });
+
+ it('ignores socket callbacks after its account scope expires', () => {
+ const runtime = createGalleryRealtimeRuntime({ backend, invalidate });
+
+ runtime.start();
+ accountLifecycle.invalidate();
+ handlers.get('image_uploaded')?.({ image_name: 'a.png' } as never);
+ vi.advanceTimersByTime(250);
+
+ expect(invalidate).not.toHaveBeenCalled();
+ runtime.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts
new file mode 100644
index 0000000000..5eee51f8e7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/data/realtimeRuntime.ts
@@ -0,0 +1,109 @@
+import type { BackendConnectionStatus } from '@platform/transport/types';
+
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+
+export interface GalleryRealtimeBackend {
+ on(event: string, handler: (payload: never) => void): () => void;
+ onConnectionChange(handler: (status: BackendConnectionStatus) => void): () => void;
+}
+
+export interface GalleryRealtimeRuntime {
+ dispose(): void;
+ start(): void;
+}
+
+/**
+ * Refreshes the Gallery read model for content that arrives without a queue
+ * event: uploads through the API from scripts, other clients, or other tabs,
+ * and anything that landed while the socket was down.
+ *
+ * Uploads are not paced by generation the way queue events are, and every
+ * invalidation pass cancels the page fetches under the user. So passes are held
+ * at least `minIntervalMs` apart: an event arriving while one is pending rides
+ * along, and one arriving after a pass waits out the rest of the interval, so a
+ * trailing pass is always guaranteed. Uploads spaced wider than that interval
+ * still get a pass each, which is the point -- each one is new media to show.
+ */
+export const createGalleryRealtimeRuntime = ({
+ backend,
+ coalesceMs = 250,
+ invalidate,
+ minIntervalMs = 1000,
+}: {
+ backend: GalleryRealtimeBackend;
+ coalesceMs?: number;
+ invalidate: () => void | Promise<void>;
+ minIntervalMs?: number;
+}): GalleryRealtimeRuntime => {
+ const owner = captureAccountScope();
+ const detachers: Array<() => void> = [];
+ let invalidationTimer: ReturnType<typeof setTimeout> | null = null;
+ let lastInvalidatedAt = Number.NEGATIVE_INFINITY;
+ let isStarted = false;
+ const isActive = (): boolean => isStarted && isAccountScopeCurrent(owner);
+
+ const scheduleInvalidation = (): void => {
+ if (!isActive() || invalidationTimer !== null) {
+ return;
+ }
+
+ // `performance.now()` rather than `Date.now()`: a wall clock that steps backwards (NTP
+ // correction after resume, VM resync) would otherwise push this delay out by the size of
+ // the step, and the guard above means that one pending timer absorbs every event until it
+ // fires.
+ const delay = Math.max(coalesceMs, lastInvalidatedAt + minIntervalMs - performance.now());
+
+ invalidationTimer = setTimeout(() => {
+ invalidationTimer = null;
+
+ if (isActive()) {
+ lastInvalidatedAt = performance.now();
+ void invalidate();
+ }
+ }, delay);
+ };
+
+ const start = (): void => {
+ if (isStarted || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ isStarted = true;
+
+ // The hub replays the current status synchronously on subscribe. A boot that
+ // reaches 'connected' from 'connecting' has missed nothing, so it must not
+ // cancel and refetch pages that are still loading. A hub that is already
+ // 'disconnected' when this mounts is the other case: events were missed, so
+ // its next 'connected' is a genuine reconnect.
+ let previousStatus: BackendConnectionStatus | null = null;
+
+ detachers.push(
+ backend.on('image_uploaded', scheduleInvalidation),
+ backend.on('video_uploaded', scheduleInvalidation),
+ backend.onConnectionChange((status) => {
+ const isReconnect = previousStatus === 'disconnected' && status === 'connected';
+
+ previousStatus = status;
+
+ if (isReconnect) {
+ scheduleInvalidation();
+ }
+ })
+ );
+ };
+
+ const dispose = (): void => {
+ isStarted = false;
+
+ for (const detach of detachers.splice(0)) {
+ detach();
+ }
+
+ if (invalidationTimer !== null) {
+ clearTimeout(invalidationTimer);
+ invalidationTimer = null;
+ }
+ };
+
+ return { dispose, start };
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index f9f43c1363..c61297dd28 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -25,3 +25,4 @@ export {
patchGalleryItemCaches,
} from './data/queryCache';
export type { GalleryItemCachePatch } from './data/queryCache';
+export { createGalleryRealtimeRuntime } from './data/realtimeRuntime';
diff --git a/tests/app/routers/test_upload_events.py b/tests/app/routers/test_upload_events.py
new file mode 100644
index 0000000000..a251fffe09
--- /dev/null
+++ b/tests/app/routers/test_upload_events.py
@@ -0,0 +1,331 @@
+"""The upload routes announce gallery-visible uploads so open galleries refresh without polling."""
+
+import io
+import os
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers import videos
+from invokeai.app.api_app import app
+from invokeai.app.services.board_records.board_records_common import BoardRecord, BoardVisibility
+from invokeai.app.services.events.events_common import ImageUploadedEvent, VideoUploadedEvent
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.images.images_common import ImageDTO
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.videos.videos_common import VideoDTO
+
+
[email protected](autouse=True, scope="module")
+def client(invokeai_root_dir: Path) -> TestClient:
+ os.environ["INVOKEAI_ROOT"] = invokeai_root_dir.as_posix()
+ return TestClient(app)
+
+
+class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker) -> None:
+ self.invoker = invoker
+
+
+def _board(board_visibility: BoardVisibility) -> BoardRecord:
+ return BoardRecord(
+ board_id="board-1",
+ board_name="Uploads",
+ user_id="owner-1",
+ created_at="None",
+ updated_at="None",
+ archived=False,
+ board_visibility=board_visibility,
+ )
+
+
+def _image_dto(is_intermediate: bool) -> ImageDTO:
+ return ImageDTO(
+ image_name="upload.png",
+ image_origin=ResourceOrigin.EXTERNAL,
+ image_category=ImageCategory.USER,
+ width=8,
+ height=8,
+ created_at="None",
+ updated_at="None",
+ is_intermediate=is_intermediate,
+ starred=False,
+ has_workflow=False,
+ image_url="/images/upload.png",
+ thumbnail_url="/thumbnails/upload.webp",
+ board_id="board-1",
+ )
+
+
+def _png_bytes() -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (8, 8), (255, 0, 0)).save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def _prepare_image_upload(monkeypatch: Any, mock_invoker: Invoker, is_intermediate: bool) -> None:
+ mock_deps = MockApiDependencies(mock_invoker)
+ mock_invoker.services.image_moves = MagicMock()
+ mock_invoker.services.image_moves.is_maintenance_active.return_value = False
+ monkeypatch.setattr(
+ mock_invoker.services.board_records, "get", MagicMock(return_value=_board(BoardVisibility.Public))
+ )
+ monkeypatch.setattr(mock_invoker.services.images, "create", MagicMock(return_value=_image_dto(is_intermediate)))
+ for target in (
+ "invokeai.app.api.routers.images.ApiDependencies",
+ "invokeai.app.api.routers._access.ApiDependencies",
+ "invokeai.app.api.routers.image_move_maintenance.ApiDependencies",
+ "invokeai.app.api.auth_dependencies.ApiDependencies",
+ ):
+ monkeypatch.setattr(target, mock_deps)
+
+
+def _upload_events(mock_invoker: Invoker) -> list[ImageUploadedEvent | VideoUploadedEvent]:
+ return [
+ event
+ for event in mock_invoker.services.events.events # type: ignore[attr-defined]
+ if isinstance(event, (ImageUploadedEvent, VideoUploadedEvent))
+ ]
+
+
+def test_image_upload_announces_the_upload_with_its_board_visibility(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ events = _upload_events(mock_invoker)
+ assert len(events) == 1
+ event = events[0]
+ assert isinstance(event, ImageUploadedEvent)
+ assert event.image_name == "upload.png"
+ assert event.image_category == ImageCategory.USER
+ assert event.board_id == "board-1"
+ assert event.board_owner_id == "owner-1"
+ assert event.board_visibility == BoardVisibility.Public
+ assert event.user_id == "system"
+
+
+def test_image_upload_without_a_board_is_announced_with_no_board(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+ mock_invoker.services.images.create.return_value = _image_dto(is_intermediate=False).model_copy(
+ update={"board_id": None}
+ )
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ mock_invoker.services.board_records.get.assert_not_called()
+ events = _upload_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].board_id is None
+ assert events[0].board_owner_id is None
+ assert events[0].board_visibility is None
+
+
+def test_failed_image_creation_is_a_mapped_500_with_no_announcement(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+ mock_invoker.services.images.create.side_effect = RuntimeError("disk full")
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 500
+ assert response.json()["detail"] == "Failed to create image"
+ assert _upload_events(mock_invoker) == []
+
+
+ ("is_intermediate", "image_category"), [(True, "user"), (False, "other")], ids=["intermediate", "canvas-owned"]
+)
+def test_hidden_image_upload_is_not_announced(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, is_intermediate: bool, image_category: str
+) -> None:
+ """Canvas persistence uploads durable OTHER images on every paint flush, plus intermediates.
+
+ Neither kind appears in a gallery view, so announcing them would refetch the gallery of the
+ painter and of every admin for content nobody can see.
+ """
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=is_intermediate)
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": image_category, "is_intermediate": is_intermediate, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ assert _upload_events(mock_invoker) == []
+
+
+def test_failed_board_attach_is_announced_without_the_board(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """`create()` logs and continues when the board attach fails, so the DTO is the authority."""
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+ mock_invoker.services.images.create.return_value = _image_dto(is_intermediate=False).model_copy(
+ update={"board_id": None}
+ )
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ events = _upload_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].board_id is None
+ assert events[0].board_owner_id is None
+ assert events[0].board_visibility is None
+ assert events[0].shared_user_ids == []
+
+
+def test_private_board_upload_carries_its_share_recipients(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """A private board's viewers are named on the event; the socket layer never queries storage."""
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+ monkeypatch.setattr(
+ mock_invoker.services.board_records, "get", MagicMock(return_value=_board(BoardVisibility.Private))
+ )
+ monkeypatch.setattr(
+ mock_invoker.services.board_records, "get_shared_user_ids", MagicMock(return_value=["viewer-1", "viewer-2"])
+ )
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ events = _upload_events(mock_invoker)
+ assert len(events) == 1
+ assert events[0].shared_user_ids == ["viewer-1", "viewer-2"]
+
+
+def test_upload_to_a_board_everyone_can_see_does_not_enumerate_shares(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """Shared/Public uploads are broadcast, so paying for the share lookup would be waste."""
+ _prepare_image_upload(monkeypatch, mock_invoker, is_intermediate=False)
+ get_shared_user_ids = MagicMock(return_value=["viewer-1"])
+ monkeypatch.setattr(mock_invoker.services.board_records, "get_shared_user_ids", get_shared_user_ids)
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "user", "is_intermediate": False, "board_id": "board-1"},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 201
+ get_shared_user_ids.assert_not_called()
+ assert _upload_events(mock_invoker)[0].shared_user_ids == []
+
+
+def _video_dto() -> VideoDTO:
+ return VideoDTO(
+ video_name="upload.mp4",
+ video_origin=ResourceOrigin.EXTERNAL,
+ video_category=ImageCategory.USER,
+ width=8,
+ height=8,
+ duration=1.0,
+ created_at="None",
+ updated_at="None",
+ is_intermediate=False,
+ starred=False,
+ has_workflow=False,
+ video_url="/videos/upload.mp4",
+ thumbnail_url="/thumbnails/upload.webp",
+ board_id="board-1",
+ )
+
+
+def _prepare_video_upload(monkeypatch: Any, mock_invoker: Invoker) -> None:
+ mock_deps = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr(mock_invoker.services, "videos", MagicMock(), raising=False)
+ mock_invoker.services.videos.create.return_value = _video_dto()
+ monkeypatch.setattr(
+ mock_invoker.services.board_records, "get", MagicMock(return_value=_board(BoardVisibility.Shared))
+ )
+ for target in (
+ "invokeai.app.api.routers.videos.ApiDependencies",
+ "invokeai.app.api.routers._access.ApiDependencies",
+ "invokeai.app.api.auth_dependencies.ApiDependencies",
+ "invokeai.app.api_app.ApiDependencies",
+ ):
+ monkeypatch.setattr(target, mock_deps)
+ # A bare `ftyp` box passes the container check; the codec and decode probes need ffmpeg.
+ monkeypatch.setattr(
+ videos, "probe_media_streams", lambda path: SimpleNamespace(video_codec="h264", audio_codec="aac")
+ )
+ monkeypatch.setattr(videos, "_probe_decodable_video", lambda path: ((8, 8, 1.0, 8.0), None))
+
+
+def _post_video(client: TestClient, is_intermediate: bool, video_category: str = "user") -> Any:
+ return client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": video_category, "is_intermediate": is_intermediate, "board_id": "board-1"},
+ files={"file": ("upload.mp4", b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12, "video/mp4")},
+ )
+
+
+def test_video_upload_announces_the_upload_with_its_board_visibility(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ _prepare_video_upload(monkeypatch, mock_invoker)
+
+ response = _post_video(client, is_intermediate=False)
+
+ assert response.status_code == 201
+ events = _upload_events(mock_invoker)
+ assert len(events) == 1
+ event = events[0]
+ assert isinstance(event, VideoUploadedEvent)
+ assert event.video_name == "upload.mp4"
+ assert event.board_id == "board-1"
+ assert event.board_owner_id == "owner-1"
+ assert event.board_visibility == BoardVisibility.Shared
+ assert event.user_id == "system"
+
+
+ ("is_intermediate", "video_category"), [(True, "user"), (False, "other")], ids=["intermediate", "canvas-owned"]
+)
+def test_hidden_video_upload_is_not_announced(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, is_intermediate: bool, video_category: str
+) -> None:
+ _prepare_video_upload(monkeypatch, mock_invoker)
+
+ response = _post_video(client, is_intermediate=is_intermediate, video_category=video_category)
+
+ assert response.status_code == 201
+ assert _upload_events(mock_invoker) == []
diff --git a/tests/app/test_media_upload_socketio.py b/tests/app/test_media_upload_socketio.py
new file mode 100644
index 0000000000..4498b41927
--- /dev/null
+++ b/tests/app/test_media_upload_socketio.py
@@ -0,0 +1,134 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import FastAPI
+
+from invokeai.app.api.sockets import SocketIO
+from invokeai.app.services.board_records.board_records_common import BoardVisibility
+from invokeai.app.services.events.events_common import ImageUploadedEvent, MediaUploadedEventBase, VideoUploadedEvent
+from invokeai.app.services.image_records.image_records_common import ImageCategory
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+def _patch_multiuser(monkeypatch: pytest.MonkeyPatch, enabled: bool) -> None:
+ invoker = SimpleNamespace(services=SimpleNamespace(configuration=SimpleNamespace(multiuser=enabled)))
+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies", SimpleNamespace(invoker=invoker))
+
+
+def _image_event(
+ board_visibility: BoardVisibility | None,
+ board_id: str | None = "board-1",
+ board_owner_id: str | None = "user-1",
+ shared_user_ids: list[str] | None = None,
+) -> ImageUploadedEvent:
+ return ImageUploadedEvent.build(
+ image_name="upload.png",
+ image_category=ImageCategory.USER,
+ user_id="user-1",
+ board_id=board_id,
+ board_owner_id=board_owner_id if board_id else None,
+ board_visibility=board_visibility,
+ shared_user_ids=shared_user_ids or [],
+ )
+
+
+async def _route(monkeypatch: pytest.MonkeyPatch, event: MediaUploadedEventBase, multiuser: bool) -> list:
+ socketio = SocketIO(FastAPI())
+ socketio._sio.emit = AsyncMock()
+ _patch_multiuser(monkeypatch, multiuser)
+
+ await socketio._handle_media_event((event.__event_name__, event))
+
+ return [call.kwargs for call in socketio._sio.emit.await_args_list]
+
+
+def test_upload_events_are_registered_with_the_socket_handler() -> None:
+ """Routing tests below call the handler directly; this pins the wiring they skip."""
+ SocketIO(FastAPI())
+
+ from fastapi_events.handlers.local import local_handler
+
+ for event_name in ("image_uploaded", "video_uploaded"):
+ assert any(
+ getattr(handler, "__func__", handler).__name__ == "_handle_media_event"
+ for handler in local_handler._registry.get(event_name, [])
+ ), event_name
+
+
+async def test_single_user_upload_goes_to_the_admin_room(monkeypatch: pytest.MonkeyPatch) -> None:
+ emits = await _route(monkeypatch, _image_event(BoardVisibility.Private), multiuser=False)
+
+ assert [emit["room"] for emit in emits] == ["admin"]
+ assert emits[0]["event"] == "image_uploaded"
+ assert emits[0]["data"]["image_name"] == "upload.png"
+
+
+ ("board_visibility", "board_id"),
+ [(BoardVisibility.Private, "board-1"), (None, None)],
+ ids=["private-board", "no-board"],
+)
+async def test_private_upload_reaches_only_the_uploader_and_admins(
+ monkeypatch: pytest.MonkeyPatch, board_visibility: BoardVisibility | None, board_id: str | None
+) -> None:
+ emits = await _route(monkeypatch, _image_event(board_visibility, board_id), multiuser=True)
+
+ assert len(emits) == 1
+ assert emits[0]["room"] == ["user:user-1", "admin"]
+
+
+async def test_admin_upload_into_another_users_private_board_reaches_that_owner(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ emits = await _route(monkeypatch, _image_event(BoardVisibility.Private, board_owner_id="owner-2"), multiuser=True)
+
+ assert len(emits) == 1
+ assert emits[0]["room"] == ["user:user-1", "admin", "user:owner-2"]
+
+
+async def test_private_board_upload_also_reaches_its_share_recipients(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A board shared with named users is readable by them, so their galleries must refresh too."""
+ event = _image_event(BoardVisibility.Private, shared_user_ids=["viewer-1", "viewer-2"])
+
+ emits = await _route(monkeypatch, event, multiuser=True)
+
+ assert len(emits) == 1
+ assert emits[0]["room"] == ["user:user-1", "admin", "user:viewer-1", "user:viewer-2"]
+
+
[email protected]("board_visibility", [BoardVisibility.Shared, BoardVisibility.Public])
+async def test_upload_to_a_board_everyone_can_view_is_broadcast(
+ monkeypatch: pytest.MonkeyPatch, board_visibility: BoardVisibility
+) -> None:
+ emits = await _route(monkeypatch, _image_event(board_visibility), multiuser=True)
+
+ assert len(emits) == 1
+ assert "room" not in emits[0]
+ assert emits[0]["data"]["board_visibility"] == board_visibility.value
+
+
+async def test_video_uploads_route_like_image_uploads(monkeypatch: pytest.MonkeyPatch) -> None:
+ event = VideoUploadedEvent.build(
+ video_name="upload.mp4",
+ video_category=ImageCategory.USER,
+ user_id="user-1",
+ board_id="board-1",
+ board_owner_id="user-1",
+ board_visibility=BoardVisibility.Private,
+ shared_user_ids=[],
+ )
+
+ emits = await _route(monkeypatch, event, multiuser=True)
+
+ assert [(emit["event"], emit["room"]) for emit in emits] == [("video_uploaded", ["user:user-1", "admin"])]