Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(images,videos): make the media copy routes safe and non-blocking
Josh Corbett2e76c2b39461
diff --git a/invokeai/app/api/routers/_limits.py b/invokeai/app/api/routers/_limits.pynew file mode 100644index 0000000000..ffd23e4e14--- /dev/null+++ b/invokeai/app/api/routers/_limits.py@@ -0,0 +1,10 @@+"""Request-size limits shared by more than one router.++These are ceilings on what a single request may ask the server to do, as opposed to what a caller+is allowed to do (`_access.py`) or how a listing is paged (`shared/pagination.py`).+"""++# Copying media is per-item work the server performs synchronously — a record insert and a file+# copy each — so one request's cost is unbounded without a cap. The frontend's largest batch is a+# project board being duplicated, which its own archive limits already keep well under this.+MAX_COPY_BATCH_SIZE = 1000diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.pyindex aa017dae9c..a600b6a849 100644--- a/invokeai/app/api/routers/images.py+++ b/invokeai/app/api/routers/images.py@@ -25,6 +25,7 @@ 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._limits import MAX_COPY_BATCH_SIZEfrom invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactivefrom invokeai.app.invocations.fields import MetadataFieldfrom invokeai.app.services.image_records.image_records_common import (@@ -583,9 +584,9 @@ class CopyImagesResult(BaseModel):@images_router.post("/copy", operation_id="copy_images_to_board", response_model=CopyImagesResult)-async def copy_images_to_board(+def copy_images_to_board(current_user: CurrentUserOrDefault,- image_names: list[str] = Body(description="The names of the images to copy"),+ image_names: list[str] = Body(description="The names of the images to copy", max_length=MAX_COPY_BATCH_SIZE),board_id: Optional[str] = Body(default=None, description="The board to put the copies on, if any"),) -> CopyImagesResult:"""Copies images, optionally onto a board, and returns the new names.@@ -594,14 +595,20 @@ async def copy_images_to_board(`image_name` — one image can sit on exactly one board, so sharing a name between two boards isnot representable. Duplicating a project needs that: its copy must own its media outright.- The pixels never leave the server. Category, origin and the metadata/workflow/graph embedded in- the PNG all travel; the originating session and node do not. Starring is not copied — callers- that want it use `POST /images/star`, the same path an import uses.+ The pixels never leave the server, and never leave the disk either: `images.copy` clones the+ record and copies the file byte for byte, so the embedded metadata, workflow and graph travel+ without being parsed and rewritten. Category and origin travel; the originating session and+ node do not. Starring is not copied — callers that want it use `POST /images/star`, the same+ path an import uses.Per-image failures are reported rather than raised, so one unreadable source cannot cost thecaller the whole batch.++ A sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a+ board's worth of them on the event loop would stall every other request for the duration."""_assert_board_write_access(board_id, current_user)+ assert_image_move_maintenance_inactive()copied: list[CopiedImage] = []failed: list[str] = []@@ -609,31 +616,14 @@ async def copy_images_to_board(for image_name in image_names:try:_assert_image_read_access(image_name, current_user)- record = ApiDependencies.invoker.services.images.get_record(image_name)- pil_image = ApiDependencies.invoker.services.images.get_pil_image(image_name)- # The same extraction the upload route performs: provenance lives in the PNG's text- # chunks, so reading it back here keeps a copy's metadata without any extra plumbing.- extracted = extract_metadata_from_image(- pil_image=pil_image,- invokeai_metadata_override=None,- invokeai_workflow_override=None,- invokeai_graph_override=None,- logger=ApiDependencies.invoker.services.logger,- )- image_dto = ApiDependencies.invoker.services.images.create(- image=pil_image,- image_origin=record.image_origin,- image_category=record.image_category,+ image_dto = ApiDependencies.invoker.services.images.copy(+ source_image_name=image_name,board_id=board_id,- is_intermediate=False,- metadata=extracted.invokeai_metadata,- workflow=extracted.invokeai_workflow,- graph=extracted.invokeai_graph,user_id=current_user.user_id,)copied.append(CopiedImage(source_image_name=image_name, image_name=image_dto.image_name))except Exception:- ApiDependencies.invoker.services.logger.error(f"Failed to copy image {image_name}")+ ApiDependencies.invoker.services.logger.error(f"Failed to copy image {image_name}", exc_info=True)failed.append(image_name)return CopyImagesResult(copied=copied, failed=failed)diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.pyindex fdbe10af53..57d627f4f1 100644--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@ -19,6 +19,7 @@ from invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers._access import (assert_board_write_access as _assert_board_write_access,)+from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZEfrom invokeai.app.api.routers.images import WorkflowAndGraphResponse, _assert_board_read_accessfrom invokeai.app.invocations.fields import MetadataField, MetadataFieldValidatorfrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin@@ -145,6 +146,22 @@ def _assert_video_read_access(video_name: str, current_user: CurrentUserOrDefaulraise HTTPException(status_code=403, detail="Not authorized to access this video")+def _read_video_thumbnail(video_name: str) -> Optional[PILImage.Image]:+ """The video's stored first-frame thumbnail, or None if it has none.++ Best-effort by design: the only caller uses it to skip a decode, and a missing or unreadable+ thumbnail is not a reason to fail a copy — the save path extracts one itself when handed None.+ """+ try:+ thumbnail_path = Path(ApiDependencies.invoker.services.videos.get_path(video_name, thumbnail=True))+ if not thumbnail_path.exists():+ return None+ with PILImage.open(thumbnail_path) as thumbnail:+ return thumbnail.copy()+ except Exception:+ return None++def _is_accepted_video_upload(file: UploadFile) -> bool:if file.content_type and file.content_type.startswith(ACCEPTED_VIDEO_MIME_PREFIXES):return True@@ -763,7 +780,7 @@ class CopyVideosResult(BaseModel):@videos_router.post("/copy", operation_id="copy_videos_to_board", response_model=CopyVideosResult)def copy_videos_to_board(current_user: CurrentUserOrDefault,- video_names: list[str] = Body(description="The names of the videos to copy"),+ video_names: list[str] = Body(description="The names of the videos to copy", max_length=MAX_COPY_BATCH_SIZE),board_id: Optional[str] = Body(default=None, description="The board to put the copies on, if any"),) -> CopyVideosResult:"""Copies videos, optionally onto a board, and returns the new names.@@ -773,6 +790,9 @@ def copy_videos_to_board(Blocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue ofthis being a sync `def`, so a large batch cannot stall the event loop.++ `move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,+ because every other caller hands it a temp file. Here the path is the *source's own* file."""_assert_board_write_access(board_id, current_user)@@ -801,10 +821,15 @@ def copy_videos_to_board(workflow=ApiDependencies.invoker.services.videos.get_workflow(video_name),graph=ApiDependencies.invoker.services.videos.get_graph(video_name),user_id=current_user.user_id,+ # The source's thumbnail is already the first frame at the size the copy wants, so+ # reusing it spares a decode-worker subprocess per copied video. A source without+ # one falls back to extraction, exactly as an upload would.+ first_frame=_read_video_thumbnail(video_name),+ move_source=False,)copied.append(CopiedVideo(source_video_name=video_name, video_name=video_dto.video_name))except Exception:- ApiDependencies.invoker.services.logger.error(f"Failed to copy video {video_name}")+ ApiDependencies.invoker.services.logger.error(f"Failed to copy video {video_name}", exc_info=True)failed.append(video_name)return CopyVideosResult(copied=copied, failed=failed)diff --git a/invokeai/app/services/image_files/image_files_base.py b/invokeai/app/services/image_files/image_files_base.pyindex 782e661c4b..484c0f287e 100644--- a/invokeai/app/services/image_files/image_files_base.py+++ b/invokeai/app/services/image_files/image_files_base.py@@ -56,6 +56,22 @@ class ImageFileStorageBase(ABC):"""Saves an image and a 256x256 WEBP thumbnail. Returns a tuple of the image name, thumbnail name, and created timestamp."""pass+ @abstractmethod+ def copy(+ self,+ source_image_name: str,+ image_name: str,+ source_subfolder: str = "",+ image_subfolder: str = "",+ thumbnail_size: int = 256,+ ) -> None:+ """Duplicates an existing image's file and thumbnail under a new name.++ A byte-level copy, not a re-encode: every PNG chunk travels, including ones this+ application does not parse, and no pixels are decoded.+ """+ pass+@abstractmethoddef delete(self, image_name: str, image_subfolder: str = "") -> None:"""Deletes an image and its thumbnail (if one exists)."""diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.pyindex dcac3f56b0..3183f5da53 100644--- a/invokeai/app/services/image_files/image_files_disk.py+++ b/invokeai/app/services/image_files/image_files_disk.py@@ -180,6 +180,46 @@ class DiskImageFileStorage(ImageFileStorageBase):except Exception as e:raise ImageFileSaveException from e+ def copy(+ self,+ source_image_name: str,+ image_name: str,+ source_subfolder: str = "",+ image_subfolder: str = "",+ thumbnail_size: int = 256,+ ) -> None:+ """Duplicate an image's files under a new name, without decoding them.++ A copy is byte-identical, so `shutil.copy2` is both the cheapest way to make one and the+ most faithful: every PNG chunk travels, including ones this application does not parse and+ would silently drop on a re-encode. Going through `save()` instead would decode and+ re-encode the pixels — hundreds of milliseconds and a fresh compression pass per image, to+ arrive at the same picture.++ Nothing is cached here. The source's cache entry belongs to the source, and a copy nobody+ has read yet has no business occupying a slot.+ """+ try:+ self.__validate_storage_folders()+ source_path = self.get_path(source_image_name, image_subfolder=source_subfolder)+ image_path = self.get_path(image_name, image_subfolder=image_subfolder)+ image_path.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source_path, image_path)++ source_thumbnail_path = self.get_path(source_image_name, thumbnail=True, image_subfolder=source_subfolder)+ thumbnail_path = self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder)+ thumbnail_path.parent.mkdir(parents=True, exist_ok=True)++ if source_thumbnail_path.exists():+ shutil.copy2(source_thumbnail_path, thumbnail_path)+ else:+ # A source predating thumbnails, or one whose thumbnail was lost. Rare enough to be+ # worth a decode rather than leaving the copy with a broken gallery tile.+ with Image.open(image_path) as copied:+ make_thumbnail(copied, thumbnail_size).save(thumbnail_path)+ except Exception as e:+ raise ImageFileSaveException from e+def delete(self, image_name: str, image_subfolder: str = "") -> None:token = self.stage_delete(image_name, image_subfolder)self.commit_delete(token)diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.pyindex f699c50a50..62b25e6691 100644--- a/invokeai/app/services/images/images_base.py+++ b/invokeai/app/services/images/images_base.py@@ -60,6 +60,21 @@ class ImageServiceABC(ABC):"""Creates an image, storing the file and its metadata."""pass+ @abstractmethod+ def copy(+ self,+ source_image_name: str,+ board_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> ImageDTO:+ """Duplicates an existing image under a new identity, optionally onto a board.++ The record is cloned and the file copied byte for byte — no decode, no re-encode — so+ embedded metadata, workflow and graph travel with it. The copy is never intermediate and+ is never starred.+ """+ pass+@abstractmethoddef update(self,diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.pyindex ef536ec07b..a7fb8d015e 100644--- a/invokeai/app/services/images/images_default.py+++ b/invokeai/app/services/images/images_default.py@@ -111,6 +111,83 @@ class ImageService(ImageServiceABC):self.__invoker.services.logger.error(f"Problem saving image record and file: {str(e)}")raise e+ def copy(+ self,+ source_image_name: str,+ board_id: Optional[str] = None,+ user_id: Optional[str] = None,+ ) -> ImageDTO:+ """Duplicate an existing image under a new identity, optionally onto a board.++ Duplicating a project needs genuinely new identities — `board_images` keys on+ `image_name`, so one image sits on exactly one board — but the *picture* is the same+ picture. So the record is cloned from the source's record and the file is copied byte for+ byte. Nothing is decoded, nothing is re-encoded, and the embedded metadata, workflow and+ graph travel because they are chunks in the file rather than something re-derived here.++ The copy is never intermediate: an intermediate is a step in someone else's run, and a+ copy is a thing a person asked for. Starring is not copied either — callers that want it+ use the same star route the gallery uses.+ """+ try:+ record = self.__invoker.services.image_records.get(source_image_name)+ metadata = self.__invoker.services.image_records.get_metadata(source_image_name)++ image_name = self.__invoker.services.names.create_image_name()+ strategy_name = self.__invoker.services.configuration.image_subfolder_strategy+ strategy = create_subfolder_strategy(strategy_name)+ image_subfolder = strategy.get_subfolder(image_name, record.image_category, False)++ record_saved = False+ try:+ self.__invoker.services.image_records.save(+ image_name=image_name,+ image_origin=record.image_origin,+ image_category=record.image_category,+ width=record.width,+ height=record.height,+ has_workflow=record.has_workflow,+ is_intermediate=False,+ metadata=metadata.model_dump_json() if metadata is not None else None,+ user_id=user_id,+ image_subfolder=image_subfolder,+ )+ record_saved = True++ if board_id is not None:+ # Deliberately fatal, unlike `create`. There the alternative to a board is+ # losing a freshly generated image; here the caller asked for a copy *on a+ # board*, and a copy that silently landed uncategorized would be reported as a+ # success that the caller then remaps its document onto.+ self.__invoker.services.board_image_records.add_image_to_board(+ board_id=board_id, image_name=image_name+ )++ self.__invoker.services.image_files.copy(+ source_image_name=source_image_name,+ image_name=image_name,+ source_subfolder=record.image_subfolder or "",+ image_subfolder=image_subfolder,+ )+ except Exception:+ # Unwind the record so a failed copy cannot leave the gallery holding a row whose+ # file endpoints 404 — the board membership goes with it via the FK.+ if record_saved:+ try:+ self.__invoker.services.image_records.delete(image_name)+ except Exception as cleanup_error:+ self.__invoker.services.logger.error(+ f"Failed to roll back the record for copy {image_name}: {cleanup_error}"+ )+ raise++ image_dto = self.get_dto(image_name)+ self._on_changed(image_dto)+ return image_dto+ except Exception:+ self.__invoker.services.logger.error(f"Failed to copy image {source_image_name}", exc_info=True)+ raise+def update(self,image_name: str,diff --git a/invokeai/app/services/video_files/video_files_base.py b/invokeai/app/services/video_files/video_files_base.pyindex 8249b56b13..09f6b79050 100644--- a/invokeai/app/services/video_files/video_files_base.py+++ b/invokeai/app/services/video_files/video_files_base.py@@ -24,10 +24,16 @@ class VideoFileStorageBase(ABC):workflow: Optional[str] = None,graph: Optional[str] = None,first_frame: Optional[Image.Image] = None,+ move_source: bool = True,) -> None:- """Saves a video by moving/copying the file at `source_path` into storage, then writes a sibling+ """Saves a video by moving the file at `source_path` into storage, then writes a siblingWEBP thumbnail extracted from the first frame, plus an optional sidecar JSON of metadata/workflow/graph.A caller that already decoded frame 0 can pass it as `first_frame` to skip the extraction.++ `source_path` is **consumed** by default: almost every caller hands over a temp file it just+ wrote, and moving it is both cheaper and the correct lifetime. A caller whose source is a+ file the server still owns — copying an existing video — must pass ``move_source=False``,+ or the copy will take the original's bytes with it."""passdiff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.pyindex 0835f2dda6..120de6d04a 100644--- a/invokeai/app/services/video_files/video_files_disk.py+++ b/invokeai/app/services/video_files/video_files_disk.py@@ -51,6 +51,7 @@ class DiskVideoFileStorage(VideoFileStorageBase):workflow: Optional[str] = None,graph: Optional[str] = None,first_frame: Optional[Image.Image] = None,+ move_source: bool = True,) -> None:logger = InvokeAILogger.get_logger()try:@@ -58,15 +59,18 @@ class DiskVideoFileStorage(VideoFileStorageBase):video_path = self.get_path(video_name, video_subfolder=video_subfolder)video_path.parent.mkdir(parents=True, exist_ok=True)- # Move if the source is on the same filesystem; otherwise copy then unlink.- try:- shutil.move(str(source_path), str(video_path))- except Exception:- shutil.copy2(str(source_path), str(video_path))+ if move_source:+ # Move if the source is on the same filesystem; otherwise copy then unlink.try:- Path(source_path).unlink(missing_ok=True)+ shutil.move(str(source_path), str(video_path))except Exception:- pass+ shutil.copy2(str(source_path), str(video_path))+ try:+ Path(source_path).unlink(missing_ok=True)+ except Exception:+ pass+ else:+ shutil.copy2(str(source_path), str(video_path))logger.info(f"Video file written: {video_path}")thumbnail_name = get_video_thumbnail_name(video_name)diff --git a/invokeai/app/services/videos/videos_base.py b/invokeai/app/services/videos/videos_base.pyindex 595f88f62d..abba2557f5 100644--- a/invokeai/app/services/videos/videos_base.py+++ b/invokeai/app/services/videos/videos_base.py@@ -61,12 +61,16 @@ class VideoServiceABC(ABC):graph: Optional[str] = None,user_id: Optional[str] = None,first_frame: Optional[Image.Image] = None,+ move_source: bool = True,) -> VideoDTO:- """Creates a video by moving/copying the file at `source_path` into storage and recording it.+ """Creates a video by moving the file at `source_path` into storage and recording it.``first_frame``, when provided (e.g. the upload path already decoded frame 0 toprove decodability), is used as the thumbnail source instead of spawning anotherdecode worker.++ ``source_path`` is consumed unless ``move_source=False``. Every caller that hands over a+ temp file wants the default; a caller copying a video the server already owns must not."""passdiff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.pyindex 090fa6e993..3768745a65 100644--- a/invokeai/app/services/videos/videos_default.py+++ b/invokeai/app/services/videos/videos_default.py@@ -54,6 +54,7 @@ class VideoService(VideoServiceABC):graph: Optional[str] = None,user_id: Optional[str] = None,first_frame: Optional[Image.Image] = None,+ move_source: bool = True,) -> VideoDTO:if video_origin not in ResourceOrigin:raise InvalidOriginException@@ -112,6 +113,7 @@ class VideoService(VideoServiceABC):workflow=workflow,graph=graph,first_frame=first_frame,+ move_source=move_source,)video_dto = self.get_dto(video_name)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex c955f51b76..a445e0fc16 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -5775,7 +5775,7 @@"post": {"tags": ["images"],"summary": "Copy Images To Board",- "description": "Copies images, optionally onto a board, and returns the new names.\n\nEach copy is a genuinely new image with its own name, because `board_images` keys on\n`image_name` \u2014 one image can sit on exactly one board, so sharing a name between two boards is\nnot representable. Duplicating a project needs that: its copy must own its media outright.\n\nThe pixels never leave the server. Category, origin and the metadata/workflow/graph embedded in\nthe PNG all travel; the originating session and node do not. Starring is not copied \u2014 callers\nthat want it use `POST /images/star`, the same path an import uses.\n\nPer-image failures are reported rather than raised, so one unreadable source cannot cost the\ncaller the whole batch.",+ "description": "Copies images, optionally onto a board, and returns the new names.\n\nEach copy is a genuinely new image with its own name, because `board_images` keys on\n`image_name` \u2014 one image can sit on exactly one board, so sharing a name between two boards is\nnot representable. Duplicating a project needs that: its copy must own its media outright.\n\nThe pixels never leave the server, and never leave the disk either: `images.copy` clones the\nrecord and copies the file byte for byte, so the embedded metadata, workflow and graph travel\nwithout being parsed and rewritten. Category and origin travel; the originating session and\nnode do not. Starring is not copied \u2014 callers that want it use `POST /images/star`, the same\npath an import uses.\n\nPer-image failures are reported rather than raised, so one unreadable source cannot cost the\ncaller the whole batch.\n\nA sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a\nboard's worth of them on the event loop would stall every other request for the duration.","operationId": "copy_images_to_board","requestBody": {"content": {@@ -7238,7 +7238,7 @@"post": {"tags": ["videos"],"summary": "Copy Videos To Board",- "description": "Copies videos, optionally onto a board, and returns the new names.\n\nThe image twin of this route explains why copies rather than shared references: `board_videos`\nkeys on `video_name`, so one video sits on exactly one board.\n\nBlocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue of\nthis being a sync `def`, so a large batch cannot stall the event loop.",+ "description": "Copies videos, optionally onto a board, and returns the new names.\n\nThe image twin of this route explains why copies rather than shared references: `board_videos`\nkeys on `video_name`, so one video sits on exactly one board.\n\nBlocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue of\nthis being a sync `def`, so a large batch cannot stall the event loop.\n\n`move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,\nbecause every other caller hands it a temp file. Here the path is the *source's own* file.","operationId": "copy_videos_to_board","requestBody": {"content": {@@ -16442,6 +16442,7 @@"type": "string"},"type": "array",+ "maxItems": 1000,"title": "Image Names","description": "The names of the images to copy"},@@ -16469,6 +16470,7 @@"type": "string"},"type": "array",+ "maxItems": 1000,"title": "Video Names","description": "The names of the videos to copy"},diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex f7454c2fb2..f40ea1e6b3 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1379,12 +1379,17 @@ export type paths = {* `image_name` — one image can sit on exactly one board, so sharing a name between two boards is* not representable. Duplicating a project needs that: its copy must own its media outright.*- * The pixels never leave the server. Category, origin and the metadata/workflow/graph embedded in- * the PNG all travel; the originating session and node do not. Starring is not copied — callers- * that want it use `POST /images/star`, the same path an import uses.+ * The pixels never leave the server, and never leave the disk either: `images.copy` clones the+ * record and copies the file byte for byte, so the embedded metadata, workflow and graph travel+ * without being parsed and rewritten. Category and origin travel; the originating session and+ * node do not. Starring is not copied — callers that want it use `POST /images/star`, the same+ * path an import uses.** Per-image failures are reported rather than raised, so one unreadable source cannot cost the* caller the whole batch.+ *+ * A sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a+ * board's worth of them on the event loop would stall every other request for the duration.*/post: operations["copy_images_to_board"];delete?: never;@@ -1746,6 +1751,9 @@ export type paths = {** Blocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue of* this being a sync `def`, so a large batch cannot stall the event loop.+ *+ * `move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,+ * because every other caller hands it a temp file. Here the path is the *source's own* file.*/post: operations["copy_videos_to_board"];delete?: never;diff --git a/tests/app/routers/test_media_copy.py b/tests/app/routers/test_media_copy.pyindex f2ad556387..5b64da9ca4 100644--- a/tests/app/routers/test_media_copy.py+++ b/tests/app/routers/test_media_copy.py@@ -8,17 +8,24 @@ one bad name cannot cost the caller the batch."""import json+from pathlib import Pathfrom typing import Anyfrom unittest.mock import MagicMock+import pytestfrom fastapi import statusfrom fastapi.testclient import TestClientfrom PIL import Image+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStoragefrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin+from invokeai.app.services.images.images_common import ImageDTOfrom invokeai.app.services.invoker import Invoker+from invokeai.app.services.names.names_default import SimpleNameService+from invokeai.app.services.urls.urls_default import LocalUrlServiceSOURCE_METADATA = {"positive_prompt": "a cat", "seed": 12345}+SOURCE_WORKFLOW = '{"name": "a workflow"}'def _auth(token: str) -> dict[str, str]:@@ -46,26 +53,38 @@ def _insert_image_record(mock_invoker: Invoker, name: str, user_id: str, categor)-def _pil_with_metadata() -> Image.Image:- """A PIL image carrying the text chunks `image_files_disk.save` writes."""- image = Image.new("RGB", (8, 8))- image.info = {"invokeai_metadata": json.dumps(SOURCE_METADATA)}- return image---def _stub_images_service(mock_invoker: Invoker, record_category: ImageCategory = ImageCategory.CONTROL) -> MagicMock:- """Replace the images service, keeping `image_records` real for the access check."""- images = MagicMock()- record = MagicMock()- record.image_origin = ResourceOrigin.INTERNAL- record.image_category = record_category- images.get_record.return_value = record- images.get_pil_image.return_value = _pil_with_metadata()- created = MagicMock()- created.image_name = "copy-001.png"- images.create.return_value = created- mock_invoker.services.images = images- return images+def real_images(mock_invoker: Invoker, tmp_path: Path) -> DiskImageFileStorage:+ """Wire the real image file storage and name service behind the real `ImageService`.++ Deliberately not a MagicMock. What this route has to get right is what happens *to the files*:+ that the copy is a new file, that the source keeps its own, and that provenance survives. A+ stubbed service asserts only that the route called something, which is how a copy that+ consumed its source would pass a full suite.+ """+ image_files = DiskImageFileStorage(tmp_path / "images")+ mock_invoker.services.image_files = image_files+ mock_invoker.services.names = SimpleNameService()+ mock_invoker.services.urls = LocalUrlService()+ image_files.start(mock_invoker)+ mock_invoker.services.images.start(mock_invoker)+ return image_files+++def _create_source_image(+ mock_invoker: Invoker,+ user_id: str,+ category: ImageCategory = ImageCategory.CONTROL,+) -> ImageDTO:+ """A genuinely stored image: record, file, thumbnail and embedded provenance."""+ return mock_invoker.services.images.create(+ image=Image.new("RGB", (8, 8), "red"),+ image_origin=ResourceOrigin.INTERNAL,+ image_category=category,+ metadata=json.dumps(SOURCE_METADATA),+ workflow=SOURCE_WORKFLOW,+ user_id=user_id,+ )def _copy_images(client: TestClient, token: str, **body: Any):@@ -73,93 +92,151 @@ def _copy_images(client: TestClient, token: str, **body: Any):def test_copying_an_image_preserves_its_category_origin_and_metadata(- client: TestClient, mock_invoker: Invoker, user1_token: str+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage):user_id = _owner_id(client, user1_token)board_id = _create_board(client, user1_token)- _insert_image_record(mock_invoker, "src.png", user_id)- images = _stub_images_service(mock_invoker)+ source = _create_source_image(mock_invoker, user_id)- response = _copy_images(client, user1_token, image_names=["src.png"], board_id=board_id)+ response = _copy_images(client, user1_token, image_names=[source.image_name], board_id=board_id)assert response.status_code == status.HTTP_200_OK- assert response.json() == {"copied": [{"source_image_name": "src.png", "image_name": "copy-001.png"}], "failed": []}-- kwargs = images.create.call_args.kwargs- assert kwargs["image_category"] == ImageCategory.CONTROL- assert kwargs["image_origin"] == ResourceOrigin.INTERNAL- assert kwargs["board_id"] == board_id- assert kwargs["is_intermediate"] is False- assert kwargs["user_id"] == user_id- # Provenance rides in the PNG's text chunks; the copy must read it back the way upload does.- assert json.loads(kwargs["metadata"]) == SOURCE_METADATA+ copy_name = response.json()["copied"][0]["image_name"]+ assert response.json()["failed"] == []+ assert copy_name != source.image_name++ copy_dto = mock_invoker.services.images.get_dto(copy_name)+ assert copy_dto.image_category == ImageCategory.CONTROL+ assert copy_dto.image_origin == ResourceOrigin.INTERNAL+ assert copy_dto.board_id == board_id+ assert copy_dto.is_intermediate is False+ assert copy_dto.starred is False+ assert mock_invoker.services.image_records.get_user_id(copy_name) == user_id+ # Provenance rides in the PNG's chunks and the record; both must arrive.+ metadata = mock_invoker.services.images.get_metadata(copy_name)+ assert metadata is not None and json.loads(metadata.model_dump_json()) == SOURCE_METADATA+ assert mock_invoker.services.images.get_workflow(copy_name) == SOURCE_WORKFLOW# Neither the originating session nor node travels.- assert kwargs.get("session_id") is None- assert kwargs.get("node_id") is None+ record = mock_invoker.services.images.get_record(copy_name)+ assert record.session_id is None+ assert record.node_id is None+++def test_copying_an_image_leaves_the_source_untouched(+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage+):+ """The copy must be additive. A copy that consumes or rewrites its source destroys the+ original project when its duplicate is made."""+ user_id = _owner_id(client, user1_token)+ source = _create_source_image(mock_invoker, user_id)+ source_path = real_images.get_path(source.image_name, image_subfolder=source.image_subfolder)+ source_bytes = source_path.read_bytes()++ response = _copy_images(client, user1_token, image_names=[source.image_name])+ copy_name = response.json()["copied"][0]["image_name"]++ assert source_path.exists()+ assert source_path.read_bytes() == source_bytes+ # The copy is its own file, byte-identical rather than re-encoded.+ copy_record = mock_invoker.services.images.get_record(copy_name)+ copy_path = real_images.get_path(copy_name, image_subfolder=copy_record.image_subfolder)+ assert copy_path != source_path+ assert copy_path.read_bytes() == source_bytes+ # And the source's own provenance still reads back the way it did before the copy.+ assert mock_invoker.services.images.get_workflow(source.image_name) == SOURCE_WORKFLOW+ source_metadata = mock_invoker.services.images.get_metadata(source.image_name)+ assert source_metadata is not None and json.loads(source_metadata.model_dump_json()) == SOURCE_METADATAdef test_copying_without_a_board_leaves_the_copy_uncategorized(- client: TestClient, mock_invoker: Invoker, user1_token: str+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage):user_id = _owner_id(client, user1_token)- _insert_image_record(mock_invoker, "src.png", user_id)- images = _stub_images_service(mock_invoker)+ source = _create_source_image(mock_invoker, user_id)- response = _copy_images(client, user1_token, image_names=["src.png"])+ response = _copy_images(client, user1_token, image_names=[source.image_name])assert response.status_code == status.HTTP_200_OK- assert images.create.call_args.kwargs["board_id"] is None+ copy_name = response.json()["copied"][0]["image_name"]+ assert mock_invoker.services.images.get_dto(copy_name).board_id is Nonedef test_one_unreadable_source_does_not_cost_the_batch(- client: TestClient, mock_invoker: Invoker, user1_token: str+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage):user_id = _owner_id(client, user1_token)- _insert_image_record(mock_invoker, "good.png", user_id)- images = _stub_images_service(mock_invoker)+ source = _create_source_image(mock_invoker, user_id)- response = _copy_images(client, user1_token, image_names=["good.png", "missing.png"])+ response = _copy_images(client, user1_token, image_names=[source.image_name, "missing.png"])assert response.status_code == status.HTTP_200_OKbody = response.json()- assert [entry["source_image_name"] for entry in body["copied"]] == ["good.png"]+ assert [entry["source_image_name"] for entry in body["copied"]] == [source.image_name]assert body["failed"] == ["missing.png"]- assert images.create.call_count == 1+++def test_a_failed_copy_leaves_no_ghost_record(+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage+):+ """A record whose file never arrived is worse than no copy: the gallery shows a tile whose+ every endpoint 404s, and nothing points at it to clean it up."""+ user_id = _owner_id(client, user1_token)+ source = _create_source_image(mock_invoker, user_id)+ before = set(mock_invoker.services.image_records.get_image_names().image_names)++ # The file is gone but the record remains — a source the copy cannot materialize.+ real_images.get_path(source.image_name, image_subfolder=source.image_subfolder).unlink()++ response = _copy_images(client, user1_token, image_names=[source.image_name])++ assert response.json() == {"copied": [], "failed": [source.image_name]}+ assert set(mock_invoker.services.image_records.get_image_names().image_names) == beforedef test_copying_into_a_board_you_cannot_write_is_refused(- client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str, real_images: DiskImageFileStorage):theirs = _create_board(client, user2_token, "Theirs")user_id = _owner_id(client, user1_token)- _insert_image_record(mock_invoker, "src.png", user_id)- images = _stub_images_service(mock_invoker)+ source = _create_source_image(mock_invoker, user_id)+ before = set(mock_invoker.services.image_records.get_image_names().image_names)- refused = _copy_images(client, user1_token, image_names=["src.png"], board_id=theirs)- missing = _copy_images(client, user1_token, image_names=["src.png"], board_id="no-such-board")+ refused = _copy_images(client, user1_token, image_names=[source.image_name], board_id=theirs)+ missing = _copy_images(client, user1_token, image_names=[source.image_name], board_id="no-such-board")assert refused.status_code == status.HTTP_403_FORBIDDENassert missing.status_code == status.HTTP_404_NOT_FOUND# The refusal lands before anything is copied.- images.create.assert_not_called()+ assert set(mock_invoker.services.image_records.get_image_names().image_names) == beforedef test_copying_someone_elses_image_is_refused_per_name(- client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str, real_images: DiskImageFileStorage):mine = _owner_id(client, user1_token)theirs = _owner_id(client, user2_token)- _insert_image_record(mock_invoker, "mine.png", mine)+ source = _create_source_image(mock_invoker, mine)_insert_image_record(mock_invoker, "theirs.png", theirs)- _stub_images_service(mock_invoker)- response = _copy_images(client, user1_token, image_names=["mine.png", "theirs.png"])+ response = _copy_images(client, user1_token, image_names=[source.image_name, "theirs.png"])body = response.json()- assert [entry["source_image_name"] for entry in body["copied"]] == ["mine.png"]+ assert [entry["source_image_name"] for entry in body["copied"]] == [source.image_name]assert body["failed"] == ["theirs.png"]+def test_a_batch_larger_than_the_cap_is_refused(+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage+):+ """Each name is a record insert and a file copy the server performs synchronously, so an+ uncapped batch is an unbounded amount of work one request can ask for."""+ _owner_id(client, user1_token)++ response = _copy_images(client, user1_token, image_names=[f"img-{index}.png" for index in range(1001)])++ assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT++def _insert_video_record(mock_invoker: Invoker, name: str, user_id: str) -> None:"""A real row, so the board service's cover resolution keeps working around it."""with mock_invoker.services.board_records._db.transaction() as cursor:@@ -204,11 +281,12 @@ def test_copying_a_video_preserves_its_shape_and_provenance(assert kwargs["is_intermediate"] is Falseassert json.loads(kwargs["metadata"]) == SOURCE_METADATAassert kwargs["workflow"] == "{}"+ # The path handed over is the source's own managed file, and `create` consumes what it is+ # given. Without this the copy moves the original's bytes away from it.+ assert kwargs["move_source"] is False-def test_copying_someone_elses_video_is_refused_per_name(- client: TestClient, mock_invoker: Invoker, user1_token: str-):+def test_copying_someone_elses_video_is_refused_per_name(client: TestClient, mock_invoker: Invoker, user1_token: str):_owner_id(client, user1_token)_insert_video_record(mock_invoker, "theirs.mp4", "somebody-else")videos = MagicMock()diff --git a/tests/app/services/video_files/test_video_files_disk.py b/tests/app/services/video_files/test_video_files_disk.pyindex f793746b45..3adca26dd7 100644--- a/tests/app/services/video_files/test_video_files_disk.py+++ b/tests/app/services/video_files/test_video_files_disk.py@@ -45,6 +45,23 @@ def test_save_writes_video_and_sidecar(storage: DiskVideoFileStorage, tmp_path:assert storage.get_workflow(VIDEO_NAME) is None # sidecar readable, workflow not set+def test_save_with_move_source_false_leaves_the_source_intact(storage: DiskVideoFileStorage, tmp_path: Path):+ """Copying a video the server already owns must not consume it.++ ``save()`` moves by default because every generation and upload hands it a temp file. But+ ``POST /videos/copy`` passes the *source's own* managed path, so a move there deletes the+ original project's video and leaves its record pointing at nothing.+ """+ source = _make_source(tmp_path)+ original_bytes = source.read_bytes()++ storage.save(source_path=source, video_name=VIDEO_NAME, move_source=False)++ assert source.exists()+ assert source.read_bytes() == original_bytes+ assert storage.get_path(VIDEO_NAME).read_bytes() == original_bytes++def test_save_failure_after_move_removes_all_destination_files(storage: DiskVideoFileStorage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):