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.

feat(images,videos): copy media server-side

joshistoast9beaef1a757f
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.py
index bd0d984feb..2edf21fd36 100644
--- a/invokeai/app/api/routers/_access.py
+++ b/invokeai/app/api/routers/_access.py
@@ -72,6 +72,33 @@ 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:
+ """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
+ straight through. Otherwise access is granted when the user is an admin, owns the board, or
+ the board is Public (public boards accept contributions from any user).
+
+ Shared boards are deliberately read-only here: `Shared` grants visibility, not contribution.
+ """
+ if board_id is None:
+ return
+
+ try:
+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
+ except Exception:
+ raise HTTPException(status_code=404, detail="Board not found")
+
+ if current_user.is_admin:
+ return
+ if board.user_id == current_user.user_id:
+ return
+ if board.board_visibility == BoardVisibility.Public:
+ return
+
+ raise HTTPException(status_code=403, detail="Not authorized to modify this board")
+
+
def assert_board_read_access(board_id: str, current_user: CurrentUserOrDefault) -> None:
"""Raise 403 if the current user may not read images from this board.
diff --git a/invokeai/app/api/routers/board_images.py b/invokeai/app/api/routers/board_images.py
index ea0273f02d..2417a33809 100644
--- a/invokeai/app/api/routers/board_images.py
+++ b/invokeai/app/api/routers/board_images.py
@@ -3,35 +3,15 @@ from fastapi.routing import APIRouter
from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers._access import (
+ assert_board_write_access as _assert_board_write_access,
+)
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.services.images.images_common import AddImagesToBoardResult, RemoveImagesFromBoardResult
board_images_router = APIRouter(prefix="/v1/board_images", tags=["boards"])
-def _assert_board_write_access(board_id: str, current_user: CurrentUserOrDefault) -> None:
- """Raise 403 if the current user may not mutate the given board.
-
- Write access is granted when ANY of these hold:
- - The user is an admin.
- - The user owns the board.
- - The board visibility is Public (public boards accept contributions from any user).
- """
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if current_user.is_admin:
- return
- if board.user_id == current_user.user_id:
- return
- if board.board_visibility == BoardVisibility.Public:
- return
- raise HTTPException(status_code=403, detail="Not authorized to modify this board")
-
-
def _assert_image_direct_owner(image_name: str, current_user: CurrentUserOrDefault) -> None:
"""Raise 403 if the current user is not the direct owner of the image.
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 71c1292082..aa017dae9c 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -16,6 +16,9 @@ from invokeai.app.api.extract_metadata_from_image import extract_metadata_from_i
from invokeai.app.api.routers._access import (
assert_board_read_access as _assert_board_read_access,
)
+from invokeai.app.api.routers._access import (
+ assert_board_write_access as _assert_board_write_access,
+)
from invokeai.app.api.routers._access import (
assert_image_owner as _assert_image_owner,
)
@@ -102,19 +105,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.
- if board_id is not None:
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if (
- not current_user.is_admin
- and board.user_id != current_user.user_id
- and board.board_visibility != BoardVisibility.Public
- ):
- raise HTTPException(status_code=403, detail="Not authorized to upload to this board")
+ _assert_board_write_access(board_id, current_user)
assert_image_move_maintenance_inactive()
@@ -581,6 +572,73 @@ async def delete_uncategorized_images(
raise HTTPException(status_code=500, detail="Failed to delete images")
+class CopiedImage(BaseModel):
+ source_image_name: str = Field(description="The image that was copied")
+ image_name: str = Field(description="The name assigned to the copy")
+
+
+class CopyImagesResult(BaseModel):
+ copied: list[CopiedImage] = Field(description="The copies that were made, in request order")
+ failed: list[str] = Field(description="The source image names that could not be copied")
+
+
+@images_router.post("/copy", operation_id="copy_images_to_board", response_model=CopyImagesResult)
+async def copy_images_to_board(
+ current_user: CurrentUserOrDefault,
+ image_names: list[str] = Body(description="The names of the images to copy"),
+ 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.
+
+ Each copy is a genuinely new image with its own name, because `board_images` keys on
+ `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.
+
+ Per-image failures are reported rather than raised, so one unreadable source cannot cost the
+ caller the whole batch.
+ """
+ _assert_board_write_access(board_id, current_user)
+
+ copied: list[CopiedImage] = []
+ failed: list[str] = []
+
+ 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,
+ 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}")
+ failed.append(image_name)
+
+ return CopyImagesResult(copied=copied, failed=failed)
+
+
class ImagesUpdatedFromListResult(BaseModel):
updated_image_names: list[str] = Field(description="The image names that were updated")
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index c535aa3b93..fdbe10af53 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -16,6 +16,9 @@ from starlette.concurrency import run_in_threadpool
from invokeai.app.api.auth_dependencies import CurrentMediaUserOrDefault, CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers._access import (
+ assert_board_write_access as _assert_board_write_access,
+)
from invokeai.app.api.routers.images import WorkflowAndGraphResponse, _assert_board_read_access
from invokeai.app.invocations.fields import MetadataField, MetadataFieldValidator
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
@@ -120,27 +123,6 @@ def _assert_video_direct_owner(video_name: str, current_user: CurrentUserOrDefau
raise HTTPException(status_code=403, detail="Not authorized to move this video")
-def _assert_board_write_access(board_id: str, current_user: CurrentUserOrDefault) -> None:
- """Raise 403 if the current user may not mutate the given board.
-
- Mirrors _assert_board_write_access in board_images.py: admins and the board owner
- may write; public boards accept contributions from any user.
- """
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if current_user.is_admin:
- return
- if board.user_id == current_user.user_id:
- return
- if board.board_visibility == BoardVisibility.Public:
- return
- raise HTTPException(status_code=403, detail="Not authorized to modify this board")
-
-
def _assert_video_read_access(video_name: str, current_user: CurrentUserOrDefault) -> None:
"""Raise 403 if the current user may not view the video."""
from invokeai.app.services.board_records.board_records_common import BoardVisibility
@@ -254,19 +236,7 @@ async def upload_video(
raise HTTPException(status_code=422, detail="Metadata must be a JSON object") from e
# Check board access for uploads to a specific board.
- if board_id is not None:
- from invokeai.app.services.board_records.board_records_common import BoardVisibility
-
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- except Exception:
- raise HTTPException(status_code=404, detail="Board not found")
- if (
- not current_user.is_admin
- and board.user_id != current_user.user_id
- and board.board_visibility != BoardVisibility.Public
- ):
- raise HTTPException(status_code=403, detail="Not authorized to upload to this board")
+ _assert_board_write_access(board_id, current_user)
if not _is_accepted_video_upload(file):
raise HTTPException(status_code=415, detail="Not a supported video file")
@@ -780,6 +750,66 @@ async def get_video_names(
raise HTTPException(status_code=500, detail="Failed to get video names")
+class CopiedVideo(BaseModel):
+ source_video_name: str = Field(description="The video that was copied")
+ video_name: str = Field(description="The name assigned to the copy")
+
+
+class CopyVideosResult(BaseModel):
+ copied: list[CopiedVideo] = Field(description="The copies that were made, in request order")
+ failed: list[str] = Field(description="The source video names that could not be copied")
+
+
+@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"),
+ 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.
+
+ The image twin of this route explains why copies rather than shared references: `board_videos`
+ keys on `video_name`, so one video sits on exactly one board.
+
+ 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.
+ """
+ _assert_board_write_access(board_id, current_user)
+
+ copied: list[CopiedVideo] = []
+ failed: list[str] = []
+
+ for video_name in video_names:
+ try:
+ _assert_video_read_access(video_name, current_user)
+ record = ApiDependencies.invoker.services.video_records.get(video_name)
+ source_path = Path(ApiDependencies.invoker.services.videos.get_path(video_name))
+ # A video's provenance is not in the file the way a PNG's is, so it is read back
+ # through the services and handed to `create` as the same strings an upload would.
+ metadata = ApiDependencies.invoker.services.videos.get_metadata(video_name)
+ video_dto = ApiDependencies.invoker.services.videos.create(
+ source_path=source_path,
+ width=record.width,
+ height=record.height,
+ duration=record.duration,
+ fps=record.fps,
+ video_origin=record.video_origin,
+ video_category=record.video_category,
+ board_id=board_id,
+ is_intermediate=False,
+ metadata=metadata.model_dump_json() if metadata is not None else None,
+ workflow=ApiDependencies.invoker.services.videos.get_workflow(video_name),
+ graph=ApiDependencies.invoker.services.videos.get_graph(video_name),
+ user_id=current_user.user_id,
+ )
+ 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}")
+ failed.append(video_name)
+
+ return CopyVideosResult(copied=copied, failed=failed)
+
+
@videos_router.post("/star", operation_id="star_videos_in_list", response_model=StarredVideosResult)
def star_videos_in_list(
current_user: CurrentUserOrDefault,
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 2a7d722ae3..c955f51b76 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -5771,6 +5771,51 @@
]
}
},
+ "/api/v1/images/copy": {
+ "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.",
+ "operationId": "copy_images_to_board",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_copy_images_to_board"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CopyImagesResult"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/images/star": {
"post": {
"tags": ["images"],
@@ -7189,6 +7234,51 @@
}
}
},
+ "/api/v1/videos/copy": {
+ "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.",
+ "operationId": "copy_videos_to_board",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_copy_videos_to_board"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CopyVideosResult"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/videos/star": {
"post": {
"tags": ["videos"],
@@ -12631,7 +12721,7 @@
"post": {
"tags": ["projects"],
"summary": "Create Project",
- "description": "Creates a project for the current user.",
+ "description": "Creates a project, and the private board it owns, for the current user.",
"operationId": "create_project",
"requestBody": {
"content": {
@@ -12817,6 +12907,54 @@
}
}
},
+ "/api/v1/projects/{project_id}/board-snapshot": {
+ "get": {
+ "tags": ["projects"],
+ "summary": "Get Project Board Snapshot",
+ "description": "Lists everything on the project's board that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway, and enforces its own\narchive limits over it.",
+ "operationId": "get_project_board_snapshot",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "project_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "The id of the project whose board to enumerate",
+ "title": "Project Id"
+ },
+ "description": "The id of the project whose board to enumerate"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ProjectBoardSnapshotDTO"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/recall/{queue_id}": {
"post": {
"tags": ["recall"],
@@ -16191,6 +16329,18 @@
],
"title": "Owner Username",
"description": "The username of the board owner (for admin view)."
+ },
+ "project_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id",
+ "description": "The id of the project that owns this board, if any."
}
},
"type": "object",
@@ -16285,6 +16435,60 @@
"required": ["batch_ids"],
"title": "Body_cancel_by_batch_ids"
},
+ "Body_copy_images_to_board": {
+ "properties": {
+ "image_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Image Names",
+ "description": "The names of the images to copy"
+ },
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Board Id",
+ "description": "The board to put the copies on, if any"
+ }
+ },
+ "type": "object",
+ "required": ["image_names"],
+ "title": "Body_copy_images_to_board"
+ },
+ "Body_copy_videos_to_board": {
+ "properties": {
+ "video_names": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Video Names",
+ "description": "The names of the videos to copy"
+ },
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Board Id",
+ "description": "The board to put the copies on, if any"
+ }
+ },
+ "type": "object",
+ "required": ["video_names"],
+ "title": "Body_copy_videos_to_board"
+ },
"Body_create_image_upload_entry": {
"properties": {
"width": {
@@ -22660,6 +22864,86 @@
"title": "ControlOutput",
"type": "object"
},
+ "CopiedImage": {
+ "properties": {
+ "source_image_name": {
+ "type": "string",
+ "title": "Source Image Name",
+ "description": "The image that was copied"
+ },
+ "image_name": {
+ "type": "string",
+ "title": "Image Name",
+ "description": "The name assigned to the copy"
+ }
+ },
+ "type": "object",
+ "required": ["source_image_name", "image_name"],
+ "title": "CopiedImage"
+ },
+ "CopiedVideo": {
+ "properties": {
+ "source_video_name": {
+ "type": "string",
+ "title": "Source Video Name",
+ "description": "The video that was copied"
+ },
+ "video_name": {
+ "type": "string",
+ "title": "Video Name",
+ "description": "The name assigned to the copy"
+ }
+ },
+ "type": "object",
+ "required": ["source_video_name", "video_name"],
+ "title": "CopiedVideo"
+ },
+ "CopyImagesResult": {
+ "properties": {
+ "copied": {
+ "items": {
+ "$ref": "#/components/schemas/CopiedImage"
+ },
+ "type": "array",
+ "title": "Copied",
+ "description": "The copies that were made, in request order"
+ },
+ "failed": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Failed",
+ "description": "The source image names that could not be copied"
+ }
+ },
+ "type": "object",
+ "required": ["copied", "failed"],
+ "title": "CopyImagesResult"
+ },
+ "CopyVideosResult": {
+ "properties": {
+ "copied": {
+ "items": {
+ "$ref": "#/components/schemas/CopiedVideo"
+ },
+ "type": "array",
+ "title": "Copied",
+ "description": "The copies that were made, in request order"
+ },
+ "failed": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Failed",
+ "description": "The source video names that could not be copied"
+ }
+ },
+ "type": "object",
+ "required": ["copied", "failed"],
+ "title": "CopyVideosResult"
+ },
"CoreMetadataInvocation": {
"additionalProperties": true,
"category": "metadata",
@@ -70807,6 +71091,52 @@
"title": "ProgressImage",
"type": "object"
},
+ "ProjectBoardItemDTO": {
+ "properties": {
+ "category": {
+ "type": "string",
+ "enum": ["general", "control", "mask", "user"],
+ "title": "Category",
+ "description": "The item's gallery category"
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["image", "video"],
+ "title": "Kind",
+ "description": "Which namespace the name belongs to"
+ },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "The server-assigned image or video name"
+ },
+ "starred": {
+ "type": "boolean",
+ "title": "Starred",
+ "description": "Whether the item is starred"
+ }
+ },
+ "type": "object",
+ "required": ["category", "kind", "name", "starred"],
+ "title": "ProjectBoardItemDTO",
+ "description": "One visible item on a project's board."
+ },
+ "ProjectBoardSnapshotDTO": {
+ "properties": {
+ "items": {
+ "items": {
+ "$ref": "#/components/schemas/ProjectBoardItemDTO"
+ },
+ "type": "array",
+ "title": "Items",
+ "description": "The board's visible items, ordered by kind then name"
+ }
+ },
+ "type": "object",
+ "required": ["items"],
+ "title": "ProjectBoardSnapshotDTO",
+ "description": "Everything a project's board holds that the gallery would show.\n\nThis is the enumeration an export needs in order to carry a project's whole workspace rather\nthan only the media its document happens to reference. Intermediates and the canvas's private\n`other` category are excluded, because neither is something the gallery shows on the board.\n\nDeliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive format\nis free to change without the wire format following it, and vice versa."
+ },
"ProjectCreateRequest": {
"properties": {
"project_id": {
@@ -70821,6 +71151,18 @@
"title": "Project Id",
"description": "Client-generated project id (e.g. for imports); generated when omitted"
},
+ "board_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Board Id",
+ "description": "An existing unclaimed private board for the project to adopt, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import."
+ },
"name": {
"type": "string",
"title": "Name",
@@ -70845,6 +71187,11 @@
"title": "Project Id",
"description": "The project's client-generated identifier"
},
+ "board_id": {
+ "type": "string",
+ "title": "Board Id",
+ "description": "The project's private board; only project APIs may rename or delete it"
+ },
"name": {
"type": "string",
"title": "Name",
@@ -70873,7 +71220,7 @@
}
},
"type": "object",
- "required": ["project_id", "name", "revision", "created_at", "updated_at", "data"],
+ "required": ["project_id", "board_id", "name", "revision", "created_at", "updated_at", "data"],
"title": "ProjectRecordDTO",
"description": "Full project record including the client-owned document."
},
@@ -70884,6 +71231,11 @@
"title": "Project Id",
"description": "The project's client-generated identifier"
},
+ "board_id": {
+ "type": "string",
+ "title": "Board Id",
+ "description": "The project's private board; only project APIs may rename or delete it"
+ },
"name": {
"type": "string",
"title": "Name",
@@ -70906,7 +71258,7 @@
}
},
"type": "object",
- "required": ["project_id", "name", "revision", "created_at", "updated_at"],
+ "required": ["project_id", "board_id", "name", "revision", "created_at", "updated_at"],
"title": "ProjectSummaryDTO",
"description": "Lightweight project listing entry; the document payload is omitted."
},
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 8e14fae0a8..f7454c2fb2 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1362,6 +1362,37 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/images/copy": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Copy Images To Board
+ * @description Copies images, optionally onto a board, and returns the new names.
+ *
+ * Each copy is a genuinely new image with its own name, because `board_images` keys on
+ * `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.
+ *
+ * Per-image failures are reported rather than raised, so one unreadable source cannot cost the
+ * caller the whole batch.
+ */
+ post: operations["copy_images_to_board"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/images/star": {
parameters: {
query?: never;
@@ -1697,6 +1728,32 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/videos/copy": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Copy Videos To Board
+ * @description Copies videos, optionally onto a board, and returns the new names.
+ *
+ * The image twin of this route explains why copies rather than shared references: `board_videos`
+ * keys on `video_name`, so one video sits on exactly one board.
+ *
+ * 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.
+ */
+ post: operations["copy_videos_to_board"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/videos/star": {
parameters: {
query?: never;
@@ -3236,7 +3293,7 @@ export type paths = {
put?: never;
/**
* Create Project
- * @description Creates a project for the current user.
+ * @description Creates a project, and the private board it owns, for the current user.
*/
post: operations["create_project"];
delete?: never;
@@ -3273,6 +3330,30 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/projects/{project_id}/board-snapshot": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Project Board Snapshot
+ * @description Lists everything on the project's board that the gallery would show.
+ *
+ * Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller
+ * that needs this — exporting a project — has to hold the whole list anyway, and enforces its own
+ * archive limits over it.
+ */
+ get: operations["get_project_board_snapshot"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/recall/{queue_id}": {
parameters: {
query?: never;
@@ -4848,6 +4929,11 @@ export type components = {
* @description The username of the board owner (for admin view).
*/
owner_username?: string | null;
+ /**
+ * Project Id
+ * @description The id of the project that owns this board, if any.
+ */
+ project_id?: string | null;
};
/**
* BoardField
@@ -4906,6 +4992,32 @@ export type components = {
*/
batch_ids: string[];
};
+ /** Body_copy_images_to_board */
+ Body_copy_images_to_board: {
+ /**
+ * Image Names
+ * @description The names of the images to copy
+ */
+ image_names: string[];
+ /**
+ * Board Id
+ * @description The board to put the copies on, if any
+ */
+ board_id?: string | null;
+ };
+ /** Body_copy_videos_to_board */
+ Body_copy_videos_to_board: {
+ /**
+ * Video Names
+ * @description The names of the videos to copy
+ */
+ video_names: string[];
+ /**
+ * Board Id
+ * @description The board to put the copies on, if any
+ */
+ board_id?: string | null;
+ };
/** Body_create_image_upload_entry */
Body_create_image_upload_entry: {
/**
@@ -8477,6 +8589,58 @@ export type components = {
*/
type: "control_output";
};
+ /** CopiedImage */
+ CopiedImage: {
+ /**
+ * Source Image Name
+ * @description The image that was copied
+ */
+ source_image_name: string;
+ /**
+ * Image Name
+ * @description The name assigned to the copy
+ */
+ image_name: string;
+ };
+ /** CopiedVideo */
+ CopiedVideo: {
+ /**
+ * Source Video Name
+ * @description The video that was copied
+ */
+ source_video_name: string;
+ /**
+ * Video Name
+ * @description The name assigned to the copy
+ */
+ video_name: string;
+ };
+ /** CopyImagesResult */
+ CopyImagesResult: {
+ /**
+ * Copied
+ * @description The copies that were made, in request order
+ */
+ copied: components["schemas"]["CopiedImage"][];
+ /**
+ * Failed
+ * @description The source image names that could not be copied
+ */
+ failed: string[];
+ };
+ /** CopyVideosResult */
+ CopyVideosResult: {
+ /**
+ * Copied
+ * @description The copies that were made, in request order
+ */
+ copied: components["schemas"]["CopiedVideo"][];
+ /**
+ * Failed
+ * @description The source video names that could not be copied
+ */
+ failed: string[];
+ };
/**
* Core Metadata
* @description Used internally by Invoke to collect metadata for generations.
@@ -29542,6 +29706,52 @@ export type components = {
*/
dataURL: string;
};
+ /**
+ * ProjectBoardItemDTO
+ * @description One visible item on a project's board.
+ */
+ ProjectBoardItemDTO: {
+ /**
+ * Category
+ * @description The item's gallery category
+ * @enum {string}
+ */
+ category: "general" | "control" | "mask" | "user";
+ /**
+ * Kind
+ * @description Which namespace the name belongs to
+ * @enum {string}
+ */
+ kind: "image" | "video";
+ /**
+ * Name
+ * @description The server-assigned image or video name
+ */
+ name: string;
+ /**
+ * Starred
+ * @description Whether the item is starred
+ */
+ starred: boolean;
+ };
+ /**
+ * ProjectBoardSnapshotDTO
+ * @description Everything a project's board holds that the gallery would show.
+ *
+ * This is the enumeration an export needs in order to carry a project's whole workspace rather
+ * than only the media its document happens to reference. Intermediates and the canvas's private
+ * `other` category are excluded, because neither is something the gallery shows on the board.
+ *
+ * Deliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive format
+ * is free to change without the wire format following it, and vice versa.
+ */
+ ProjectBoardSnapshotDTO: {
+ /**
+ * Items
+ * @description The board's visible items, ordered by kind then name
+ */
+ items: components["schemas"]["ProjectBoardItemDTO"][];
+ };
/**
* ProjectCreateRequest
* @description Request body for creating a project.
@@ -29552,6 +29762,11 @@ export type components = {
* @description Client-generated project id (e.g. for imports); generated when omitted
*/
project_id?: string | null;
+ /**
+ * Board Id
+ * @description An existing unclaimed private board for the project to adopt, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import.
+ */
+ board_id?: string | null;
/**
* Name
* @description The project's display name
@@ -29575,6 +29790,11 @@ export type components = {
* @description The project's client-generated identifier
*/
project_id: string;
+ /**
+ * Board Id
+ * @description The project's private board; only project APIs may rename or delete it
+ */
+ board_id: string;
/**
* Name
* @description The project's display name
@@ -29613,6 +29833,11 @@ export type components = {
* @description The project's client-generated identifier
*/
project_id: string;
+ /**
+ * Board Id
+ * @description The project's private board; only project APIs may rename or delete it
+ */
+ board_id: string;
/**
* Name
* @description The project's display name
@@ -43704,6 +43929,39 @@ export interface operations {
};
};
};
+ copy_images_to_board: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["Body_copy_images_to_board"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["CopyImagesResult"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
star_images_in_list: {
parameters: {
query?: never;
@@ -44445,6 +44703,39 @@ export interface operations {
};
};
};
+ copy_videos_to_board: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["Body_copy_videos_to_board"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["CopyVideosResult"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
star_videos_in_list: {
parameters: {
query?: never;
@@ -47796,6 +48087,38 @@ export interface operations {
};
};
};
+ get_project_board_snapshot: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description The id of the project whose board to enumerate */
+ project_id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ProjectBoardSnapshotDTO"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
get_recall_parameters: {
parameters: {
query?: never;
diff --git a/tests/app/routers/test_media_copy.py b/tests/app/routers/test_media_copy.py
new file mode 100644
index 0000000000..f2ad556387
--- /dev/null
+++ b/tests/app/routers/test_media_copy.py
@@ -0,0 +1,225 @@
+"""Tests for the server-side media copy routes.
+
+Duplicating a project cannot share its media: `board_images` and `board_videos` key on the media
+name, so one item sits on exactly one board. These routes are what makes that copy cheap — the
+bytes never leave the server — so what matters here is that a copy is faithful (category, origin
+and provenance travel; intermediates and starring do not), lands where it was told to, and that
+one bad name cannot cost the caller the batch.
+"""
+
+import json
+from typing import Any
+from unittest.mock import MagicMock
+
+from fastapi import status
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.invoker import Invoker
+
+SOURCE_METADATA = {"positive_prompt": "a cat", "seed": 12345}
+
+
+def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+def _create_board(client: TestClient, token: str, name: str = "Target") -> str:
+ response = client.post(f"/api/v1/boards/?board_name={name}", headers=_auth(token))
+ assert response.status_code == status.HTTP_201_CREATED
+ return response.json()["board_id"]
+
+
+def _owner_id(client: TestClient, token: str) -> str:
+ board = client.post("/api/v1/boards/?board_name=Probe", headers=_auth(token))
+ return board.json()["user_id"]
+
+
+def _insert_image_record(mock_invoker: Invoker, name: str, user_id: str, category: str = "control") -> None:
+ """A real row, so the route's read-access check runs against real data."""
+ with mock_invoker.services.board_records._db.transaction() as cursor:
+ cursor.execute(
+ "INSERT INTO images (image_name, image_origin, image_category, width, height, user_id)"
+ " VALUES (?, 'internal', ?, 64, 64, ?);",
+ (name, category, user_id),
+ )
+
+
+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 _copy_images(client: TestClient, token: str, **body: Any):
+ return client.post("/api/v1/images/copy", json=body, headers=_auth(token))
+
+
+def test_copying_an_image_preserves_its_category_origin_and_metadata(
+ client: TestClient, mock_invoker: Invoker, user1_token: str
+):
+ 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)
+
+ response = _copy_images(client, user1_token, image_names=["src.png"], 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
+ # Neither the originating session nor node travels.
+ assert kwargs.get("session_id") is None
+ assert kwargs.get("node_id") is None
+
+
+def test_copying_without_a_board_leaves_the_copy_uncategorized(
+ client: TestClient, mock_invoker: Invoker, user1_token: str
+):
+ user_id = _owner_id(client, user1_token)
+ _insert_image_record(mock_invoker, "src.png", user_id)
+ images = _stub_images_service(mock_invoker)
+
+ response = _copy_images(client, user1_token, image_names=["src.png"])
+
+ assert response.status_code == status.HTTP_200_OK
+ assert images.create.call_args.kwargs["board_id"] is None
+
+
+def test_one_unreadable_source_does_not_cost_the_batch(
+ client: TestClient, mock_invoker: Invoker, user1_token: str
+):
+ user_id = _owner_id(client, user1_token)
+ _insert_image_record(mock_invoker, "good.png", user_id)
+ images = _stub_images_service(mock_invoker)
+
+ response = _copy_images(client, user1_token, image_names=["good.png", "missing.png"])
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert [entry["source_image_name"] for entry in body["copied"]] == ["good.png"]
+ assert body["failed"] == ["missing.png"]
+ assert images.create.call_count == 1
+
+
+def test_copying_into_a_board_you_cannot_write_is_refused(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str
+):
+ 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)
+
+ 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")
+
+ assert refused.status_code == status.HTTP_403_FORBIDDEN
+ assert missing.status_code == status.HTTP_404_NOT_FOUND
+ # The refusal lands before anything is copied.
+ images.create.assert_not_called()
+
+
+def test_copying_someone_elses_image_is_refused_per_name(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str
+):
+ mine = _owner_id(client, user1_token)
+ theirs = _owner_id(client, user2_token)
+ _insert_image_record(mock_invoker, "mine.png", 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"])
+
+ body = response.json()
+ assert [entry["source_image_name"] for entry in body["copied"]] == ["mine.png"]
+ assert body["failed"] == ["theirs.png"]
+
+
+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:
+ cursor.execute(
+ "INSERT INTO videos (video_name, video_origin, video_category, width, height, duration, fps, user_id)"
+ " VALUES (?, 'internal', 'general', 640, 480, 2.5, 24.0, ?);",
+ (name, user_id),
+ )
+
+
+def test_copying_a_video_preserves_its_shape_and_provenance(
+ client: TestClient, mock_invoker: Invoker, user1_token: str
+):
+ user_id = _owner_id(client, user1_token)
+ board_id = _create_board(client, user1_token, "Video+Target")
+ _insert_video_record(mock_invoker, "src.mp4", user_id)
+
+ videos = MagicMock()
+ videos.get_path.return_value = "/tmp/source.mp4"
+ metadata = MagicMock()
+ metadata.model_dump_json.return_value = json.dumps(SOURCE_METADATA)
+ videos.get_metadata.return_value = metadata
+ videos.get_workflow.return_value = "{}"
+ videos.get_graph.return_value = None
+ created = MagicMock()
+ created.video_name = "copy-001.mp4"
+ videos.create.return_value = created
+ mock_invoker.services.videos = videos
+
+ response = client.post(
+ "/api/v1/videos/copy",
+ json={"video_names": ["src.mp4"], "board_id": board_id},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"copied": [{"source_video_name": "src.mp4", "video_name": "copy-001.mp4"}], "failed": []}
+ kwargs = videos.create.call_args.kwargs
+ assert (kwargs["width"], kwargs["height"], kwargs["duration"], kwargs["fps"]) == (640, 480, 2.5, 24.0)
+ assert kwargs["video_category"] == ImageCategory.GENERAL
+ assert kwargs["board_id"] == board_id
+ assert kwargs["is_intermediate"] is False
+ assert json.loads(kwargs["metadata"]) == SOURCE_METADATA
+ assert kwargs["workflow"] == "{}"
+
+
+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()
+ mock_invoker.services.videos = videos
+
+ response = client.post(
+ "/api/v1/videos/copy",
+ json={"video_names": ["theirs.mp4"]},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"copied": [], "failed": ["theirs.mp4"]}
+ videos.create.assert_not_called()