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
feat(projects): add first-class project boards
joshistoast0490afaf7b77
diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.pyindex ac97f8180b..273dfffe5c 100644--- a/invokeai/app/api/routers/boards.py+++ b/invokeai/app/api/routers/boards.py@@ -102,6 +102,17 @@ async def update_board(if not current_user.is_admin and board.user_id != current_user.user_id:raise HTTPException(status_code=403, detail="Not authorized to update this board")+ # A project's board takes its name, archived state and visibility from the project, so the+ # generic route must not set them — for admins either. The cover is still fair game: it is a+ # display detail with no bearing on the project relationship.+ if board.project_id is not None and (+ changes.board_name is not None or changes.archived is not None or changes.board_visibility is not None+ ):+ raise HTTPException(+ status_code=409,+ detail="This board belongs to a project; rename or archive the project instead",+ )+try:result = ApiDependencies.invoker.services.boards.update(board_id=board_id, changes=changes)return result@@ -132,23 +143,58 @@ def delete_board(cascade_user_id: Optional[str] = None if current_user.is_admin else current_user.user_iddeleted_images: list[str] = []deleted_videos: list[str] = []+ board_deleted = Falsetry:if include_images is True:assert_image_move_maintenance_inactive()++ # Enumerate first, delete the board second, delete its media third. The order matters:+ # a project's board must be refused *before* anything is destroyed, and the conditional+ # delete is the only check that cannot lose a race against a project claiming the board.+ # Membership rows are gone by the time the media is deleted (the board FK cascades), which+ # is why the names have to be captured up front.+ #+ # Without `include_images` every membership is dropped regardless of who contributed it,+ # so that enumeration is deliberately unfiltered.+ enumerate_user_id = cascade_user_id if include_images is True else None+ board_image_names = ApiDependencies.invoker.services.board_images.get_all_board_image_names_for_board(+ board_id=board_id,+ categories=None,+ is_intermediate=None,+ user_id=enumerate_user_id,+ )+ board_video_names = ApiDependencies.invoker.services.board_video_records.get_all_board_video_names_for_board(+ board_id=board_id,+ categories=None,+ is_intermediate=None,+ user_id=enumerate_user_id,+ )++ if not ApiDependencies.invoker.services.boards.delete_if_unclaimed(board_id=board_id):+ # `get_dto` above proved the board existed, so it is either claimed now or it vanished+ # in between. Ask again rather than trusting the DTO, which predates any concurrent claim.+ claimed = ApiDependencies.invoker.services.board_records.get_project_ids_for_boards([board_id])+ if board_id in claimed:+ raise HTTPException(+ status_code=409,+ detail="This board belongs to a project; delete the project instead",+ )+ raise HTTPException(status_code=404, detail="Board not found")+ board_deleted = True++ if include_images is True:# The services report both outcomes: records whose file delete failed are- # preserved (they cascade to "uncategorized" via the board FKs when the- # board is deleted below) and returned as failures. This is the ground- # truth — reconstructing failures by diffing a router-side board listing- # against the deleted names would double the DB work and misreport items- # moved or deleted concurrently between the two queries.- deleted_images, failed_images = ApiDependencies.invoker.services.images.delete_images_on_board(- board_id=board_id, user_id=cascade_user_id+ # preserved (they are already uncategorized, the board having gone) and returned+ # as failures. This is the ground truth — reconstructing failures by diffing a+ # router-side board listing against the deleted names would double the DB work and+ # misreport items moved or deleted concurrently between the two queries.+ deleted_images, failed_images = ApiDependencies.invoker.services.images.delete_images_by_names(+ board_image_names)- deleted_videos, failed_videos = ApiDependencies.invoker.services.videos.delete_videos_on_board(- board_id=board_id, user_id=cascade_user_id+ deleted_videos, failed_videos = ApiDependencies.invoker.services.videos.delete_videos_by_names(+ board_video_names)- ApiDependencies.invoker.services.boards.delete(board_id=board_id)return DeleteBoardResult(board_id=board_id,deleted_board_images=[],@@ -158,27 +204,14 @@ def delete_board(failed_images=failed_images,failed_videos=failed_videos,)- else:- deleted_board_images = ApiDependencies.invoker.services.board_images.get_all_board_image_names_for_board(- board_id=board_id,- categories=None,- is_intermediate=None,- )- deleted_board_videos = (- ApiDependencies.invoker.services.board_video_records.get_all_board_video_names_for_board(- board_id=board_id,- categories=None,- is_intermediate=None,- )- )- ApiDependencies.invoker.services.boards.delete(board_id=board_id)- return DeleteBoardResult(- board_id=board_id,- deleted_board_images=deleted_board_images,- deleted_images=[],- deleted_board_videos=deleted_board_videos,- deleted_videos=[],- )++ return DeleteBoardResult(+ board_id=board_id,+ deleted_board_images=board_image_names,+ deleted_images=[],+ deleted_board_videos=board_video_names,+ deleted_videos=[],+ )except HTTPException:raiseexcept Exception:@@ -186,10 +219,10 @@ def delete_board(raise HTTPException(status_code=500,detail={- "message": "Failed to delete board after partially deleting media",+ "message": "Failed to delete board media","deleted_images": deleted_images,"deleted_videos": deleted_videos,- "board_deleted": False,+ "board_deleted": board_deleted,},)raise HTTPException(status_code=500, detail="Failed to delete board")diff --git a/invokeai/app/api/routers/projects.py b/invokeai/app/api/routers/projects.pyindex 6609c09123..284944fd03 100644--- a/invokeai/app/api/routers/projects.py+++ b/invokeai/app/api/routers/projects.py@@ -7,6 +7,9 @@ from pydantic import BaseModel, Fieldfrom invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.project_records.project_records_common import (+ ProjectBoardNotFoundError,+ ProjectBoardSnapshotDTO,+ ProjectBoardUnavailableError,ProjectRecordConflictError,ProjectRecordDTO,ProjectRecordExistsError,@@ -23,6 +26,14 @@ class ProjectCreateRequest(BaseModel):project_id: str | None = Field(default=None, description="Client-generated project id (e.g. for imports); generated when omitted")+ board_id: str | None = Field(+ default=None,+ 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: str = Field(description="The project's display name")data: dict[str, Any] = Field(description="The opaque client-owned project document")@@ -48,16 +59,19 @@ async def create_project(current_user: CurrentUserOrDefault,request: ProjectCreateRequest = Body(description="The project to create"),) -> ProjectRecordDTO:- """Creates a project for the current user."""+ """Creates a project, and the private board it owns, for the current user."""try:return ApiDependencies.invoker.services.project_records.create(user_id=current_user.user_id,name=request.name,data=request.data,project_id=request.project_id,+ board_id=request.board_id,)- except ProjectRecordExistsError as e:+ except (ProjectRecordExistsError, ProjectBoardUnavailableError) as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))+ except ProjectBoardNotFoundError as e:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))@projects_router.get("/{project_id}", operation_id="get_project", response_model=ProjectRecordDTO)@@ -96,6 +110,27 @@ async def update_project()+@projects_router.get(+ "/{project_id}/board-snapshot",+ operation_id="get_project_board_snapshot",+ response_model=ProjectBoardSnapshotDTO,+)+async def get_project_board_snapshot(+ current_user: CurrentUserOrDefault,+ project_id: str = Path(description="The id of the project whose board to enumerate"),+) -> ProjectBoardSnapshotDTO:+ """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.+ """+ try:+ return ApiDependencies.invoker.services.project_records.get_board_snapshot(current_user.user_id, project_id)+ except ProjectRecordNotFoundError as e:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))++@projects_router.delete("/{project_id}", operation_id="delete_project", status_code=status.HTTP_204_NO_CONTENT)async def delete_project(current_user: CurrentUserOrDefault,diff --git a/invokeai/app/services/board_records/board_records_base.py b/invokeai/app/services/board_records/board_records_base.pyindex 811084ebf7..3493a4b4e7 100644--- a/invokeai/app/services/board_records/board_records_base.py+++ b/invokeai/app/services/board_records/board_records_base.py@@ -13,6 +13,25 @@ class BoardRecordStorageBase(ABC):"""Deletes a board record."""pass+ @abstractmethod+ def delete_if_unclaimed(self, board_id: str) -> bool:+ """Delete a board only if no project owns it. Returns whether it was deleted.++ The check and the delete are one statement so that a project claiming the board concurrently+ either commits first and this returns False, or loses and finds the board already gone.+ Callers must not destroy the board's media until this has returned True.+ """+ pass++ @abstractmethod+ def get_project_ids_for_boards(self, board_ids: list[str]) -> dict[str, str]:+ """Map board id to owning project id, for the boards that a project owns.++ Boards with no project are absent from the result. Bulk because board listings would+ otherwise issue one lookup per row.+ """+ pass+@abstractmethoddef save(self,diff --git a/invokeai/app/services/board_records/board_records_sqlite.py b/invokeai/app/services/board_records/board_records_sqlite.pyindex 89f08cf76c..d545d18130 100644--- a/invokeai/app/services/board_records/board_records_sqlite.py+++ b/invokeai/app/services/board_records/board_records_sqlite.py@@ -35,6 +35,37 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):except Exception as e:raise BoardRecordDeleteException from e+ def delete_if_unclaimed(self, board_id: str) -> bool:+ with self._db.transaction() as cursor:+ try:+ cursor.execute(+ """--sql+ DELETE FROM boards+ WHERE board_id = ?+ AND NOT EXISTS (+ SELECT 1 FROM projects WHERE projects.board_id = boards.board_id+ );+ """,+ (board_id,),+ )+ return cursor.rowcount > 0+ except Exception as e:+ raise BoardRecordDeleteException from e++ def get_project_ids_for_boards(self, board_ids: list[str]) -> dict[str, str]:+ if not board_ids:+ return {}++ placeholders = ", ".join("?" for _ in board_ids)+ with self._db.transaction() as cursor:+ cursor.execute(+ f"""--sql+ SELECT board_id, project_id FROM projects WHERE board_id IN ({placeholders});+ """,+ tuple(board_ids),+ )+ return {row[0]: row[1] for row in cursor.fetchall()}+def save(self,board_name: str,diff --git a/invokeai/app/services/boards/boards_base.py b/invokeai/app/services/boards/boards_base.pyindex 914dfa3d0d..5d5ac344f2 100644--- a/invokeai/app/services/boards/boards_base.py+++ b/invokeai/app/services/boards/boards_base.py@@ -43,6 +43,14 @@ class BoardServiceABC(ABC):"""Deletes a board."""pass+ @abstractmethod+ def delete_if_unclaimed(+ self,+ board_id: str,+ ) -> bool:+ """Delete a board only if no project owns it. Returns whether it was deleted."""+ pass+@abstractmethoddef get_many(self,diff --git a/invokeai/app/services/boards/boards_common.py b/invokeai/app/services/boards/boards_common.pyindex c6310242bd..87d8f322a9 100644--- a/invokeai/app/services/boards/boards_common.py+++ b/invokeai/app/services/boards/boards_common.py@@ -22,6 +22,13 @@ class BoardDTO(BoardRecord):"""The number of assets in the board."""owner_username: Optional[str] = Field(default=None, description="The username of the board owner (for admin view).")"""The username of the board owner (for admin view)."""+ project_id: Optional[str] = Field(default=None, description="The id of the project that owns this board, if any.")+ """Set when a project owns this board. Such a board can only be renamed or deleted through the+ project APIs; the generic board routes refuse it. Ownership is derived by joining `projects`, so+ it never appears on `BoardRecord` and is never a column on `boards`.++ Note that `BoardRecord` extends `BaseModelExcludeNull`: this field is *omitted* from serialized+ output rather than sent as `null`, so clients must treat absent as "not a project board"."""def board_record_to_dto(@@ -32,6 +39,7 @@ def board_record_to_dto(owner_username: Optional[str] = None,cover_video_name: Optional[str] = None,video_count: int = 0,+ project_id: Optional[str] = None,) -> BoardDTO:"""Converts a board record to a board DTO."""return BoardDTO(@@ -42,4 +50,5 @@ def board_record_to_dto(video_count=video_count,asset_count=asset_count,owner_username=owner_username,+ project_id=project_id,)diff --git a/invokeai/app/services/boards/boards_default.py b/invokeai/app/services/boards/boards_default.pyindex 750a450492..d8b2eebff5 100644--- a/invokeai/app/services/boards/boards_default.py+++ b/invokeai/app/services/boards/boards_default.py@@ -54,6 +54,9 @@ class BoardService(BoardServiceABC):board_record = self.__invoker.services.board_records.save(board_name, user_id)return board_record_to_dto(board_record, None, 0, 0)+ def _get_project_id(self, board_id: str) -> Optional[str]:+ return self.__invoker.services.board_records.get_project_ids_for_boards([board_id]).get(board_id)+def get_dto(self, board_id: str) -> BoardDTO:board_record = self.__invoker.services.board_records.get(board_id)cover_image_name, cover_video_name = self._resolve_cover(board_record.board_id)@@ -65,6 +68,7 @@ class BoardService(BoardServiceABC):asset_count,cover_video_name=cover_video_name,video_count=video_count,+ project_id=self._get_project_id(board_id),)def update(@@ -82,11 +86,15 @@ class BoardService(BoardServiceABC):asset_count,cover_video_name=cover_video_name,video_count=video_count,+ project_id=self._get_project_id(board_id),)def delete(self, board_id: str) -> None:self.__invoker.services.board_records.delete(board_id)+ def delete_if_unclaimed(self, board_id: str) -> bool:+ return self.__invoker.services.board_records.delete_if_unclaimed(board_id)+def get_many(self,user_id: str,@@ -100,9 +108,10 @@ class BoardService(BoardServiceABC):board_records = self.__invoker.services.board_records.get_many(user_id, is_admin, order_by, direction, offset, limit, include_archived)- summaries = self.__invoker.services.gallery.get_board_media_summaries(- [record.board_id for record in board_records.items]- )+ board_ids = [record.board_id for record in board_records.items]+ summaries = self.__invoker.services.gallery.get_board_media_summaries(board_ids)+ # One lookup for the page, not one per row.+ project_ids = self.__invoker.services.board_records.get_project_ids_for_boards(board_ids)board_dtos = []for r in board_records.items:summary = summaries[r.board_id]@@ -123,6 +132,7 @@ class BoardService(BoardServiceABC):owner_username,cover_video_name=summary.cover_video_name,video_count=summary.video_count,+ project_id=project_ids.get(r.board_id),))@@ -139,9 +149,10 @@ class BoardService(BoardServiceABC):board_records = self.__invoker.services.board_records.get_all(user_id, is_admin, order_by, direction, include_archived)- summaries = self.__invoker.services.gallery.get_board_media_summaries(- [record.board_id for record in board_records]- )+ board_ids = [record.board_id for record in board_records]+ summaries = self.__invoker.services.gallery.get_board_media_summaries(board_ids)+ # One lookup for the whole listing, not one per row.+ project_ids = self.__invoker.services.board_records.get_project_ids_for_boards(board_ids)board_dtos = []for r in board_records:summary = summaries[r.board_id]@@ -162,6 +173,7 @@ class BoardService(BoardServiceABC):owner_username,cover_video_name=summary.cover_video_name,video_count=summary.video_count,+ project_id=project_ids.get(r.board_id),))diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.pyindex 8c825ca74b..f699c50a50 100644--- a/invokeai/app/services/images/images_base.py+++ b/invokeai/app/services/images/images_base.py@@ -152,6 +152,16 @@ class ImageServiceABC(ABC):"""Gets the number of intermediate images. If user_id is provided, only counts that user's intermediates."""pass+ @abstractmethod+ def delete_images_by_names(self, image_names: list[str]) -> tuple[list[str], list[str]]:+ """Deletes exactly these images; returns ``(deleted_names, failed_names)``.++ For callers that must decide whether the deletion may proceed *before* destroying+ anything, and so enumerate the names themselves. Same per-image failure semantics as+ ``delete_images_on_board``.+ """+ pass+@abstractmethoddef delete_images_on_board(self, board_id: str, user_id: Optional[str] = None) -> tuple[list[str], list[str]]:"""Deletes all images on a board; returns ``(deleted_names, failed_names)``.diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.pyindex 96073cb051..ef536ec07b 100644--- a/invokeai/app/services/images/images_default.py+++ b/invokeai/app/services/images/images_default.py@@ -308,15 +308,24 @@ class ImageService(ImageServiceABC):raise edef delete_images_on_board(self, board_id: str, user_id: Optional[str] = None) -> tuple[list[str], list[str]]:+ # When ``user_id`` is set the lookup filters to images owned by that user so the+ # cascade doesn't destroy other users' contributions to a public/shared board.+ image_names = self.__invoker.services.board_image_records.get_all_board_image_names_for_board(+ board_id,+ categories=None,+ is_intermediate=None,+ user_id=user_id,+ )+ return self.delete_images_by_names(image_names)++ def delete_images_by_names(self, image_names: list[str]) -> tuple[list[str], list[str]]:+ """Delete exactly these images, returning ``(deleted, failed)``.++ Split from ``delete_images_on_board`` so a caller that must decide whether the board may go+ *before* destroying anything can enumerate first and delete second. Records whose file+ delete fails keep their record on purpose and come back as failures.+ """try:- # When ``user_id`` is set the lookup filters to images owned by that user so the- # cascade doesn't destroy other users' contributions to a public/shared board.- image_names = self.__invoker.services.board_image_records.get_all_board_image_names_for_board(- board_id,- categories=None,- is_intermediate=None,- user_id=user_id,- )deleted_image_names: list[str] = []failed_image_names: list[str] = []staged_deletes: list[tuple[str, object]] = []diff --git a/invokeai/app/services/project_records/project_records_base.py b/invokeai/app/services/project_records/project_records_base.pyindex 0bc02b74d7..56af5d553c 100644--- a/invokeai/app/services/project_records/project_records_base.py+++ b/invokeai/app/services/project_records/project_records_base.py@@ -1,7 +1,11 @@from abc import ABC, abstractmethodfrom typing import Any-from invokeai.app.services.project_records.project_records_common import ProjectRecordDTO, ProjectSummaryDTO+from invokeai.app.services.project_records.project_records_common import (+ ProjectBoardSnapshotDTO,+ ProjectRecordDTO,+ ProjectSummaryDTO,+)class ProjectRecordsStorageBase(ABC):@@ -10,23 +14,39 @@ class ProjectRecordsStorageBase(ABC):All operations are scoped by user_id; a user can never read or writeanother user's projects. Saves use optimistic concurrency via theproject's monotonic revision.++ Every project owns exactly one private board, and this storage is the only+ thing allowed to create, rename or delete it. The board's name tracks the+ project's name; the two always commit together."""@abstractmethod- def create(self, user_id: str, name: str, data: dict[str, Any], project_id: str | None = None) -> ProjectRecordDTO:- """Create a project for the user.+ def create(+ self,+ user_id: str,+ name: str,+ data: dict[str, Any],+ project_id: str | None = None,+ board_id: str | None = None,+ ) -> ProjectRecordDTO:+ """Create a project for the user, with a board.Args:user_id: The owning user.name: The project's display name.data: The opaque client-owned project document.project_id: Client-generated id (e.g. for imports); generated when omitted.+ board_id: An existing unclaimed private board to adopt, renamed to `name`. Omit to+ create one. Restoration uses this to upload media before the project exists, so+ that creating the project is the single commit point for an import.Returns:The created project record.Raises:ProjectRecordExistsError: The user already has a project with this id.+ ProjectBoardNotFoundError: `board_id` is missing or belongs to another user.+ ProjectBoardUnavailableError: The board is public, shared, or already claimed."""pass@@ -48,7 +68,9 @@ class ProjectRecordsStorageBase(ABC):def update(self, user_id: str, project_id: str, expected_revision: int, name: str, data: dict[str, Any]) -> ProjectRecordDTO:- """Save a project if the caller's revision is current.+ """Save a project if the caller's revision is current, renaming its board to match.++ A save that loses the revision race renames nothing.Raises:ProjectRecordNotFoundError: No such project for this user.@@ -58,5 +80,31 @@ class ProjectRecordsStorageBase(ABC):@abstractmethoddef delete(self, user_id: str, project_id: str) -> None:- """Delete one of the user's projects. Idempotent: deleting a missing project is a no-op."""+ """Delete one of the user's projects and its board.++ Idempotent: deleting a missing project is a no-op. The board's media is not deleted — losing+ the board returns it to Uncategorized.+ """+ pass++ @abstractmethod+ def get_board_snapshot(self, user_id: str, project_id: str) -> ProjectBoardSnapshotDTO:+ """Enumerate everything on the project's board that the gallery would show.++ Excludes intermediates and the canvas's private `other` category, so the result is exactly+ the board as the user sees it. Exports use this to carry a project's whole workspace rather+ than only the media its document references.++ Raises:+ ProjectRecordNotFoundError: No such project for this user.+ """+ pass++ @abstractmethod+ def get_board_id(self, user_id: str, project_id: str) -> str:+ """Get the project's board id without loading its document.++ Raises:+ ProjectRecordNotFoundError: No such project for this user.+ """passdiff --git a/invokeai/app/services/project_records/project_records_common.py b/invokeai/app/services/project_records/project_records_common.pyindex dc25b17017..b3b0615e20 100644--- a/invokeai/app/services/project_records/project_records_common.py+++ b/invokeai/app/services/project_records/project_records_common.py@@ -1,6 +1,6 @@"""Common types and errors for the project records service."""-from typing import Any+from typing import Any, Literalfrom pydantic import BaseModel, Field@@ -29,10 +29,33 @@ class ProjectRecordConflictError(Exception):)+class ProjectBoardNotFoundError(Exception):+ """Raised when a project is created against a board the user does not have.++ A board owned by someone else lands here rather than in a "forbidden" error: the caller has no+ business learning that a board id it does not own exists.+ """++ def __init__(self, board_id: str) -> None:+ super().__init__(f"Board {board_id} not found")+++class ProjectBoardUnavailableError(Exception):+ """Raised when a board exists and is the user's, but cannot become a project's board.++ A project board is private, unshared, and owned by exactly one project; a board that is public,+ shared, explicitly shared with someone, or already claimed fails all three ways at once.+ """++ def __init__(self, board_id: str) -> None:+ super().__init__(f"Board {board_id} is not available to be claimed by a project")++class ProjectSummaryDTO(BaseModel):"""Lightweight project listing entry; the document payload is omitted."""project_id: str = Field(description="The project's client-generated identifier")+ board_id: str = Field(description="The project's private board; only project APIs may rename or delete it")name: str = Field(description="The project's display name")revision: int = Field(description="Monotonic revision, incremented on every save")created_at: str = Field(description="When the project was created")@@ -43,3 +66,26 @@ class ProjectRecordDTO(ProjectSummaryDTO):"""Full project record including the client-owned document."""data: dict[str, Any] = Field(description="The opaque client-owned project document")+++class ProjectBoardItemDTO(BaseModel):+ """One visible item on a project's board."""++ category: Literal["general", "control", "mask", "user"] = Field(description="The item's gallery category")+ kind: Literal["image", "video"] = Field(description="Which namespace the name belongs to")+ name: str = Field(description="The server-assigned image or video name")+ starred: bool = Field(description="Whether the item is starred")+++class ProjectBoardSnapshotDTO(BaseModel):+ """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.+ """++ items: list[ProjectBoardItemDTO] = Field(description="The board's visible items, ordered by kind then name")diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.pyindex 0369a626f4..698f84c722 100644--- a/invokeai/app/services/project_records/project_records_sqlite.py+++ b/invokeai/app/services/project_records/project_records_sqlite.py@@ -1,11 +1,16 @@import jsonimport sqlite3import uuid-from typing import Any+from typing import Any, Optional+from invokeai.app.services.board_records.board_records_common import BoardVisibilityfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.project_records.project_records_base import ProjectRecordsStorageBasefrom invokeai.app.services.project_records.project_records_common import (+ ProjectBoardItemDTO,+ ProjectBoardNotFoundError,+ ProjectBoardSnapshotDTO,+ ProjectBoardUnavailableError,ProjectRecordConflictError,ProjectRecordDTO,ProjectRecordExistsError,@@ -13,10 +18,26 @@ from invokeai.app.services.project_records.project_records_common import (ProjectSummaryDTO,)from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.util.misc import uuid_string++# `BoardChanges.board_name` caps names at 300 characters. Project names are unbounded, so the board+# carrying a project's name is truncated to stay inside what the generic board API would accept.+BOARD_NAME_MAX_LENGTH = 300class ProjectRecordsSqlite(ProjectRecordsStorageBase):- """SQLite implementation of per-user project document storage."""+ """SQLite implementation of per-user project document storage.++ A project and its board are one unit here. Every write that touches both — creating them,+ renaming them, deleting them — happens inside a single `self._db.transaction()` so the two can+ never disagree.++ That transaction is the reason this class talks to `boards` in raw SQL rather than through+ `BoardService`. `SqliteDatabase.transaction()` guards a re-entrant lock and commits on the way+ out of *every* level, so calling another service's method from inside an open transaction would+ commit this one's half-finished work. Nothing between the `with` and its close may call anything+ that opens a transaction of its own, including `self.get()`.+ """def __init__(self, db: SqliteDatabase) -> None:super().__init__()@@ -25,20 +46,35 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):def start(self, invoker: Invoker) -> None:self._invoker = invoker- def create(self, user_id: str, name: str, data: dict[str, Any], project_id: str | None = None) -> ProjectRecordDTO:+ def create(+ self,+ user_id: str,+ name: str,+ data: dict[str, Any],+ project_id: str | None = None,+ board_id: str | None = None,+ ) -> ProjectRecordDTO:project_id = project_id or uuid.uuid4().hextry:with self._db.transaction() as cursor:+ if board_id is None:+ resolved_board_id = self._insert_board(cursor, user_id=user_id, name=name)+ else:+ self._claim_board(cursor, user_id=user_id, board_id=board_id, name=name)+ resolved_board_id = board_id+cursor.execute("""--sql- INSERT INTO projects (project_id, user_id, name, data)- VALUES (?, ?, ?, ?);+ INSERT INTO projects (project_id, user_id, name, data, board_id)+ VALUES (?, ?, ?, ?, ?);""",- (project_id, user_id, name, json.dumps(data)),+ (project_id, user_id, name, json.dumps(data), resolved_board_id),)except sqlite3.IntegrityError as e:- raise ProjectRecordExistsError(project_id) from e+ # The board insert/rename rolls back with the project insert, so a rejected create never+ # leaves an orphan board behind.+ raise self._classify_integrity_error(e, project_id=project_id, board_id=board_id) from ereturn self.get(user_id, project_id)@@ -46,7 +82,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):with self._db.transaction() as cursor:cursor.execute("""--sql- SELECT project_id, name, data, revision, created_at, updated_at+ SELECT project_id, board_id, name, data, revision, created_at, updated_atFROM projectsWHERE user_id = ? AND project_id = ?;""",@@ -59,18 +95,19 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):return ProjectRecordDTO(project_id=row[0],- name=row[1],- data=json.loads(row[2]),- revision=row[3],- created_at=row[4],- updated_at=row[5],+ board_id=row[1],+ name=row[2],+ data=json.loads(row[3]),+ revision=row[4],+ created_at=row[5],+ updated_at=row[6],)def list(self, user_id: str) -> list[ProjectSummaryDTO]:with self._db.transaction() as cursor:cursor.execute("""--sql- SELECT project_id, name, revision, created_at, updated_at+ SELECT project_id, board_id, name, revision, created_at, updated_atFROM projectsWHERE user_id = ?-- rowid breaks ties between rows created in the same millisecond,@@ -84,10 +121,11 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):return [ProjectSummaryDTO(project_id=row[0],- name=row[1],- revision=row[2],- created_at=row[3],- updated_at=row[4],+ board_id=row[1],+ name=row[2],+ revision=row[3],+ created_at=row[4],+ updated_at=row[5],)for row in rows]@@ -119,12 +157,33 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):if row is None:raise ProjectRecordNotFoundError(project_id)+ # Raised before the rename, so a save that lost the race renames nothing.raise ProjectRecordConflictError(project_id, expected_revision, row[0])+ cursor.execute(+ """--sql+ UPDATE boards+ SET board_name = ?+ WHERE board_id = (SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?);+ """,+ (name[:BOARD_NAME_MAX_LENGTH], user_id, project_id),+ )+return self.get(user_id, project_id)def delete(self, user_id: str, project_id: str) -> None:with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;+ """,+ (user_id, project_id),+ )+ row = cursor.fetchone()++ if row is None:+ return+cursor.execute("""--sqlDELETE FROM projects@@ -132,3 +191,134 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):""",(user_id, project_id),)+ # Only after the project is gone: the board FK is RESTRICT, so a claimed board cannot be+ # deleted. Deleting the board cascades its memberships, returning the media to+ # Uncategorized; the image and video records and their files are untouched.+ cursor.execute(+ """--sql+ DELETE FROM boards WHERE board_id = ?;+ """,+ (row[0],),+ )++ def get_board_snapshot(self, user_id: str, project_id: str) -> ProjectBoardSnapshotDTO:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;+ """,+ (user_id, project_id),+ )+ row = cursor.fetchone()++ if row is None:+ raise ProjectRecordNotFoundError(project_id)++ # One union over both namespaces, shaped like `get_board_media_summaries`. The filters+ # are what make the result match what the gallery shows for this board: intermediates+ # are hidden, and `other` — the canvas's private category — is in neither+ # IMAGE_CATEGORIES nor ASSETS_CATEGORIES and so appears in no board view.+ #+ # `deleted_at` is deliberately *not* filtered. Soft delete is unused and no other+ # board query consults it, so filtering here would make the snapshot disagree with the+ # counts shown beside the board.+ cursor.execute(+ """--sql+ SELECT 'image' AS kind, images.image_name AS name,+ images.image_category AS category, images.starred AS starred+ FROM board_images+ INNER JOIN images ON board_images.image_name = images.image_name+ WHERE board_images.board_id = ?+ AND images.is_intermediate = FALSE+ AND images.image_category IN ('general', 'control', 'mask', 'user')+ UNION ALL+ SELECT 'video' AS kind, videos.video_name AS name,+ videos.video_category AS category, videos.starred AS starred+ FROM board_videos+ INNER JOIN videos ON board_videos.video_name = videos.video_name+ WHERE board_videos.board_id = ?+ AND videos.is_intermediate = FALSE+ AND videos.video_category IN ('general', 'control', 'mask', 'user')+ ORDER BY kind ASC, name ASC;+ """,+ (row[0], row[0]),+ )+ rows = cursor.fetchall()++ return ProjectBoardSnapshotDTO(+ items=[ProjectBoardItemDTO(kind=r[0], name=r[1], category=r[2], starred=bool(r[3])) for r in rows]+ )++ def get_board_id(self, user_id: str, project_id: str) -> str:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;+ """,+ (user_id, project_id),+ )+ row = cursor.fetchone()++ if row is None:+ raise ProjectRecordNotFoundError(project_id)++ return row[0]++ def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str) -> str:+ board_id = uuid_string()+ cursor.execute(+ """--sql+ INSERT INTO boards (board_id, board_name, user_id, board_visibility, archived)+ VALUES (?, ?, ?, ?, FALSE);+ """,+ (board_id, name[:BOARD_NAME_MAX_LENGTH], user_id, BoardVisibility.Private.value),+ )+ return board_id++ def _claim_board(self, cursor: sqlite3.Cursor, *, user_id: str, board_id: str, name: str) -> None:+ """Take ownership of an existing private board, or explain why it cannot be taken.++ One query answers every way a claim can fail. The `UNIQUE` constraint on `projects.board_id`+ settles the race this check cannot see: two imports claiming the same board both pass here,+ and exactly one of them survives the insert.+ """+ cursor.execute(+ """--sql+ SELECT+ b.user_id,+ b.board_visibility,+ EXISTS(SELECT 1 FROM shared_boards s WHERE s.board_id = b.board_id),+ EXISTS(SELECT 1 FROM projects p WHERE p.board_id = b.board_id)+ FROM boards b+ WHERE b.board_id = ?;+ """,+ (board_id,),+ )+ row = cursor.fetchone()++ if row is None or row[0] != user_id:+ raise ProjectBoardNotFoundError(board_id)++ if row[1] != BoardVisibility.Private.value or row[2] or row[3]:+ raise ProjectBoardUnavailableError(board_id)++ cursor.execute(+ """--sql+ UPDATE boards SET board_name = ? WHERE board_id = ?;+ """,+ (name[:BOARD_NAME_MAX_LENGTH], board_id),+ )++ @staticmethod+ def _classify_integrity_error(+ error: sqlite3.IntegrityError, *, project_id: str, board_id: Optional[str]+ ) -> Exception:+ """Name which uniqueness a rejected insert violated.++ Two constraints can reject the same statement: the composite primary key, meaning the user+ already has this project id, and `projects.board_id`, meaning another project claimed the+ board after `_claim_board` looked.+ """+ if board_id is not None and "projects.board_id" in str(error):+ return ProjectBoardUnavailableError(board_id)+ return ProjectRecordExistsError(project_id)diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.pynew file mode 100644index 0000000000..f13a434247--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py@@ -0,0 +1,256 @@+"""Give every project a first-class board that SQLite owns.++Until now a "project board" was a fiction the client maintained: the Workbench created an ordinary+board on demand and stashed its id in the opaque project document at+`widgetInstances.<id>.state.values.projectBoardId`. Nothing on the server knew the board belonged to+a project, so the board could be renamed, archived or deleted out from under it, two projects could+name the same board, and a project restored on another install pointed at a board id that did not+exist there.++This migration moves the relationship into the schema: `projects.board_id` becomes `NOT NULL UNIQUE`+with a foreign key to `boards`. The `UNIQUE` makes "a board belongs to at most one project" a+database fact, and the FK's default `RESTRICT` makes "a claimed board cannot be deleted" one too,+backing the application's 409 rather than merely agreeing with it.++Existing projects keep the board they were already using **only when that is unambiguously safe**.+The document is opaque and client-written, so its `projectBoardId` is treated as a hint to be+verified, never as an assertion: a candidate is adopted only when exactly one distinct value survives+every ownership test. Anything ambiguous — two candidates, a board owned by someone else, a shared or+public board, one another project already took — gets a fresh empty board instead. That is the+conservative direction: a project that adopts nothing merely starts with an empty board, whereas a+project that adopts the wrong board takes ownership of media it does not own.++Nothing is moved between boards. `board_images` and `board_videos` are read but never written, so no+image or video changes hands here; only the projects table gains a column, and boards may gain rows+and a new name.+"""++import json+import sqlite3+from typing import Any, Optional++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+from invokeai.app.util.misc import uuid_string++# `BoardChanges.board_name` caps names at 300 characters. Project names are unbounded, so a board+# adopting a project's name is truncated to stay inside what the generic board API would accept.+BOARD_NAME_MAX_LENGTH = 300+++class AddProjectBoardsMigrationCallback:+ def __call__(self, cursor: sqlite3.Cursor) -> None:+ assignments = self._assign_boards(cursor)+ self._rebuild_projects_table(cursor, assignments)++ def _assign_boards(self, cursor: sqlite3.Cursor) -> list[tuple[int, str]]:+ """Resolve one board per project, creating boards as needed.++ Returns (rowid, board_id) pairs. Projects are visited in `rowid` order so that when two of+ them name the same board the earlier one wins, deterministically and repeatably.+ """+ cursor.execute(+ """--sql+ SELECT rowid, user_id, name, data FROM projects ORDER BY rowid ASC;+ """+ )+ projects = cursor.fetchall()++ assignments: list[tuple[int, str]] = []+ # Boards claimed earlier in this run. The column does not exist yet, so this set is the only+ # record of what has already been spoken for.+ claimed: set[str] = set()++ for rowid, user_id, name, data in projects:+ board_id = self._adopt_board(cursor, user_id=user_id, data=data, claimed=claimed)++ if board_id is None:+ board_id = self._insert_board(cursor, user_id=user_id, name=name)+ else:+ cursor.execute(+ """--sql+ UPDATE boards SET board_name = ? WHERE board_id = ?;+ """,+ (name[:BOARD_NAME_MAX_LENGTH], board_id),+ )++ claimed.add(board_id)+ assignments.append((rowid, board_id))++ return assignments++ def _adopt_board(+ self, cursor: sqlite3.Cursor, *, user_id: str, data: str, claimed: set[str]+ ) -> Optional[str]:+ """Return the project's existing board if exactly one candidate is safe to adopt."""+ candidates = _collect_board_candidates(data)++ # Two gallery widgets disagreeing about which board is the project's leaves no way to pick+ # correctly, and guessing would hand a project someone else's media.+ if len(candidates) != 1:+ return None++ board_id = next(iter(candidates))++ if board_id in claimed:+ return None++ cursor.execute(+ """--sql+ SELECT+ b.user_id,+ b.board_visibility,+ EXISTS(SELECT 1 FROM shared_boards s WHERE s.board_id = b.board_id)+ FROM boards b+ WHERE b.board_id = ?;+ """,+ (board_id,),+ )+ row = cursor.fetchone()++ if row is None:+ return None++ board_user_id, board_visibility, is_shared = row++ if board_user_id != user_id:+ return None+ # A project board is private by definition; adopting a shared or public one would lock a+ # board other people can see into a single project's lifecycle.+ if board_visibility != "private":+ return None+ if is_shared:+ return None++ return board_id++ def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str) -> str:+ board_id = uuid_string()+ cursor.execute(+ """--sql+ INSERT INTO boards (board_id, board_name, user_id, board_visibility, archived)+ VALUES (?, ?, ?, 'private', FALSE);+ """,+ (board_id, name[:BOARD_NAME_MAX_LENGTH], user_id),+ )+ return board_id++ def _rebuild_projects_table(self, cursor: sqlite3.Cursor, assignments: list[tuple[int, str]]) -> None:+ """Rebuild `projects` with `board_id`.++ SQLite cannot `ALTER TABLE ... ADD COLUMN` a `UNIQUE`, `NOT NULL` column with a foreign key,+ so the table is rebuilt. `projects` has no inbound foreign keys, so this is safe with+ `PRAGMA foreign_keys = ON` — which matters because the pragma is a no-op inside the+ transaction the migrator wraps this callback in and so cannot be turned off here.+ """+ # Dropped first so that renaming the replacement into place cannot rewrite a live trigger's+ # body out from under us.+ cursor.execute("DROP TRIGGER IF EXISTS tg_projects_updated_at;")++ cursor.execute(+ """--sql+ CREATE TABLE projects_with_boards (+ -- Client-generated identifier; unique per user, not globally.+ project_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ name TEXT NOT NULL,+ -- Opaque client-owned project document (JSON).+ data TEXT NOT NULL,+ -- The project's private board. UNIQUE is what makes "at most one project per board"+ -- a schema fact; the FK's default RESTRICT is what stops a claimed board being+ -- deleted through the generic board API.+ board_id TEXT NOT NULL UNIQUE,+ -- Incremented on every update; used for optimistic concurrency.+ revision INTEGER NOT NULL DEFAULT 1,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (user_id, project_id),+ FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,+ FOREIGN KEY (board_id) REFERENCES boards(board_id)+ );+ """+ )++ # Inserted in rowid order so the rebuilt table keeps the original insertion order, which is+ # what `list()` falls back to when two projects share a created_at millisecond.+ for rowid, board_id in assignments:+ cursor.execute(+ """--sql+ INSERT INTO projects_with_boards+ (project_id, user_id, name, data, board_id, revision, created_at, updated_at)+ SELECT project_id, user_id, name, data, ?, revision, created_at, updated_at+ FROM projects+ WHERE rowid = ?;+ """,+ (board_id, rowid),+ )++ cursor.execute("DROP TABLE projects;")+ cursor.execute("ALTER TABLE projects_with_boards RENAME TO projects;")++ cursor.execute(+ """--sql+ CREATE TRIGGER IF NOT EXISTS tg_projects_updated_at+ AFTER UPDATE ON projects+ FOR EACH ROW+ BEGIN+ UPDATE projects+ SET updated_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')+ WHERE user_id = OLD.user_id AND project_id = OLD.project_id;+ END;+ """+ )+++def _collect_board_candidates(data: str) -> set[str]:+ """Every distinct non-empty `projectBoardId` a project document names.++ Two shapes are read: the current `widgetInstances` map, and the `widgetStates.gallery` shape+ earlier builds wrote. A document that is unparseable or shaped unexpectedly yields nothing,+ which lands the project on a fresh board.+ """+ try:+ document = json.loads(data)+ except (TypeError, ValueError):+ return set()++ if not isinstance(document, dict):+ return set()++ candidates: set[str] = set()++ widget_instances = document.get("widgetInstances")+ if isinstance(widget_instances, dict):+ for instance in widget_instances.values():+ if not isinstance(instance, dict) or instance.get("typeId") != "gallery":+ continue+ state = instance.get("state")+ if not isinstance(state, dict):+ continue+ _add_candidate(candidates, state.get("values"))++ widget_states = document.get("widgetStates")+ if isinstance(widget_states, dict):+ gallery = widget_states.get("gallery")+ if isinstance(gallery, dict):+ _add_candidate(candidates, gallery.get("values"))++ return candidates+++def _add_candidate(candidates: set[str], values: Any) -> None:+ if not isinstance(values, dict):+ return+ board_id = values.get("projectBoardId")+ if isinstance(board_id, str) and board_id != "":+ candidates.add(board_id)+++def build_migration() -> Migration:+ """Build the migration that gives every project its own board."""+ return Migration(+ id="2026_08_06_add_project_boards",+ # The repair migration is what guarantees `projects` exists at all on databases that were+ # ever opened by an upstream build; it transitively guarantees `boards` and `shared_boards`.+ depends_on="2026_07_30_repair_projects_table",+ callback=AddProjectBoardsMigrationCallback(),+ )diff --git a/invokeai/app/services/videos/videos_base.py b/invokeai/app/services/videos/videos_base.pyindex 542e2cdff5..595f88f62d 100644--- a/invokeai/app/services/videos/videos_base.py+++ b/invokeai/app/services/videos/videos_base.py@@ -133,6 +133,16 @@ class VideoServiceABC(ABC):"""Deletes a video."""pass+ @abstractmethod+ def delete_videos_by_names(self, video_names: list[str]) -> tuple[list[str], list[str]]:+ """Deletes exactly these videos; returns ``(deleted_names, failed_names)``.++ For callers that must decide whether the deletion may proceed *before* destroying+ anything, and so enumerate the names themselves. Same per-video failure semantics as+ ``delete_videos_on_board``.+ """+ pass+@abstractmethoddef delete_videos_on_board(self, board_id: str, user_id: Optional[str] = None) -> tuple[list[str], list[str]]:"""Deletes all videos on a board; returns ``(deleted_names, failed_names)``.diff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.pyindex 46e3711dbb..090fa6e993 100644--- a/invokeai/app/services/videos/videos_default.py+++ b/invokeai/app/services/videos/videos_default.py@@ -320,18 +320,25 @@ class VideoService(VideoServiceABC):raise edef delete_videos_on_board(self, board_id: str, user_id: Optional[str] = None) -> tuple[list[str], list[str]]:+ # When ``user_id`` is set the lookup filters to videos owned by that user so the+ # cascade doesn't destroy other users' contributions to a public/shared board.+ video_names = self.__invoker.services.board_video_records.get_all_board_video_names_for_board(+ board_id, categories=None, is_intermediate=None, user_id=user_id+ )+ return self.delete_videos_by_names(video_names)++ def delete_videos_by_names(self, video_names: list[str]) -> tuple[list[str], list[str]]:+ """Delete exactly these videos, returning ``(deleted, failed)``.++ Split from ``delete_videos_on_board`` so a caller that must decide whether the board may go+ *before* destroying anything can enumerate first and delete second.+ """try:- # When ``user_id`` is set the lookup filters to videos owned by that user so the- # cascade doesn't destroy other users' contributions to a public/shared board.- video_names = self.__invoker.services.board_video_records.get_all_board_video_names_for_board(- board_id, categories=None, is_intermediate=None, user_id=user_id- )# Only delete records for files we actually managed to remove. Otherwise a# transient FS error would leave the file orphaned on disk with no record# pointing at it — the API would report success and the user would have no- # way to clean up the leak. The board itself will still be deleted by the- # caller, so any preserved records cascade to "uncategorized" via the- # board_videos FK.+ # way to clean up the leak. A preserved record simply stays on the server;+ # when its board goes it becomes "uncategorized" via the board_videos FK.deleted_video_names: list[str] = []failed_video_names: list[str] = []staged_deletes: list[tuple[str, object]] = []diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pyindex fe41f17cf8..d91496bb3f 100644--- a/tests/app/routers/conftest.py+++ b/tests/app/routers/conftest.py@@ -61,6 +61,9 @@ _PATCHED_API_DEPENDENCIES_MODULES = ("invokeai.app.api.routers._access","invokeai.app.api.routers.model_manager","invokeai.app.api.routers.app_info",+ "invokeai.app.api.routers.projects",+ "invokeai.app.api.routers.boards",+ "invokeai.app.api.routers.videos",)diff --git a/tests/app/routers/test_boards_multiuser.py b/tests/app/routers/test_boards_multiuser.pyindex 17ab8b8449..af14e3a724 100644--- a/tests/app/routers/test_boards_multiuser.py+++ b/tests/app/routers/test_boards_multiuser.py@@ -89,14 +89,16 @@ def enable_multiuser_for_tests(monkeypatch: Any, mock_invoker: Invoker):mock_video_records.get_most_recent_video_for_board.return_value = Nonemock_invoker.services.video_records = mock_video_recordsmock_invoker.services.videos = MagicMock()- # delete_videos_on_board now returns the authoritative ``deleted_videos`` list (only the+ # ``delete_videos_by_names`` returns the authoritative ``deleted_videos`` list (only the# videos whose file deletion actually succeeded). Default to an empty list so pydantic# validation on ``DeleteBoardResult`` doesn't reject the MagicMock auto-return.+ mock_invoker.services.videos.delete_videos_by_names.return_value = ([], [])mock_invoker.services.videos.delete_videos_on_board.return_value = ([], [])# The images service is a real ImageService instance in mock_services; the delete-board- # cascade calls ``delete_images_on_board`` on it, which fails without an initialized+ # cascade calls ``delete_images_by_names`` on it, which fails without an initialized# invoker. Stub it so the multiuser router tests can assert the cascade args.mock_invoker.services.images = MagicMock()+ mock_invoker.services.images.delete_images_by_names.return_value = ([], [])mock_invoker.services.images.delete_images_on_board.return_value = ([], [])mock_deps = MockApiDependencies(mock_invoker)@@ -721,7 +723,7 @@ def test_admin_can_change_any_board_visibility(client: TestClient, admin_token:def test_delete_board_with_include_images_cascades_videos(client: TestClient, mock_invoker: Invoker, user1_token: str):- """include_images=true must also call delete_videos_on_board (not image-only)."""+ """include_images=true must also destroy the board's videos (not image-only)."""create = client.post("/api/v1/boards/?board_name=Cascade+Test+Board",headers={"Authorization": f"Bearer {user1_token}"},@@ -729,10 +731,16 @@ def test_delete_board_with_include_images_cascades_videos(client: TestClient, moassert create.status_code == status.HTTP_201_CREATEDboard_id = create.json()["board_id"]+ # Membership is enumerated before the board is deleted (the board FK cascades the rows+ # away), then those exact names are destroyed.+ mock_invoker.services.board_video_records.get_all_board_video_names_for_board.return_value = [+ "video_a.mp4",+ "video_b.mp4",+ ]# The cascade returns the names of videos it actually deleted; the router must surface# *that* list (not the pre-delete enumeration) so the response can't claim a video was# destroyed when its DB record was preserved due to a file-delete failure.- mock_invoker.services.videos.delete_videos_on_board.return_value = (["video_a.mp4", "video_b.mp4"], [])+ mock_invoker.services.videos.delete_videos_by_names.return_value = (["video_a.mp4", "video_b.mp4"], [])response = client.delete(f"/api/v1/boards/{board_id}?include_images=true",@@ -742,9 +750,7 @@ def test_delete_board_with_include_images_cascades_videos(client: TestClient, mobody = response.json()assert body["board_id"] == board_idassert set(body["deleted_videos"]) == {"video_a.mp4", "video_b.mp4"}- mock_invoker.services.videos.delete_videos_on_board.assert_called_once()- call = mock_invoker.services.videos.delete_videos_on_board.call_args- assert call.kwargs["board_id"] == board_id+ mock_invoker.services.videos.delete_videos_by_names.assert_called_once_with(["video_a.mp4", "video_b.mp4"])def test_delete_board_with_partial_video_file_delete_failure_reports_only_actual_deletes(@@ -767,8 +773,8 @@ def test_delete_board_with_partial_video_file_delete_failure_reports_only_actual# The service deleted "good.mp4" successfully but preserved "stuck.mp4" because its# file delete failed. The router must NOT claim "stuck.mp4" was deleted, and must# report the failure from the service's own accounting (not a racy listing diff).- mock_invoker.services.images.delete_images_on_board.return_value = (["good.png"], ["stuck.png"])- mock_invoker.services.videos.delete_videos_on_board.return_value = (["good.mp4"], ["stuck.mp4"])+ mock_invoker.services.images.delete_images_by_names.return_value = (["good.png"], ["stuck.png"])+ mock_invoker.services.videos.delete_videos_by_names.return_value = (["good.mp4"], ["stuck.mp4"])response = client.delete(f"/api/v1/boards/{board_id}?include_images=true",@@ -786,19 +792,26 @@ def test_delete_board_with_partial_video_file_delete_failure_reports_only_actualdef test_delete_board_reports_partial_cascade_completion(client: TestClient, mock_invoker: Invoker, user1_token: str, failure_phase: str):+ """The board is deleted before its media, so which phase failed decides what survives.++ A board that cannot be deleted must leave every image and video intact — that ordering is+ what stops a project's media being destroyed by a delete the board itself would refuse.+ """create = client.post("/api/v1/boards/?board_name=Partial+Cascade+Failure",headers={"Authorization": f"Bearer {user1_token}"},)assert create.status_code == status.HTTP_201_CREATEDboard_id = create.json()["board_id"]- mock_invoker.services.images.delete_images_on_board.return_value = (["deleted.png"], [])- mock_invoker.services.videos.delete_videos_on_board.return_value = (["deleted.mp4"], [])+ mock_invoker.services.images.delete_images_by_names.return_value = (["deleted.png"], [])+ mock_invoker.services.videos.delete_videos_by_names.return_value = (["deleted.mp4"], [])if failure_phase == "videos":- mock_invoker.services.videos.delete_videos_on_board.side_effect = RuntimeError("video delete failed")+ mock_invoker.services.videos.delete_videos_by_names.side_effect = RuntimeError("video delete failed")board_delete_patch = (- patch.object(mock_invoker.services.boards, "delete", side_effect=RuntimeError("board delete failed"))+ patch.object(+ mock_invoker.services.boards, "delete_if_unclaimed", side_effect=RuntimeError("board delete failed")+ )if failure_phase == "board"else nullcontext())@@ -810,9 +823,17 @@ def test_delete_board_reports_partial_cascade_completion(assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERRORdetail = response.json()["detail"]- assert detail["deleted_images"] == ["deleted.png"]- assert detail["deleted_videos"] == ([] if failure_phase == "videos" else ["deleted.mp4"])- assert detail["board_deleted"] is False+ if failure_phase == "board":+ assert detail["board_deleted"] is False+ # Nothing was touched: the media deletion never ran.+ assert detail["deleted_images"] == []+ assert detail["deleted_videos"] == []+ mock_invoker.services.images.delete_images_by_names.assert_not_called()+ mock_invoker.services.videos.delete_videos_by_names.assert_not_called()+ else:+ assert detail["board_deleted"] is True+ assert detail["deleted_images"] == ["deleted.png"]+ assert detail["deleted_videos"] == []def test_delete_board_with_include_images_filters_cascade_by_user(@@ -840,17 +861,15 @@ def test_delete_board_with_include_images_filters_cascade_by_user()assert response.status_code == status.HTTP_200_OK- # The router must pass the current user's id through to the cascade so the SQL filter- # narrows the lookup + delete to that user's rows only. Admins skip the filter (pass- # ``user_id=None``); this test exercises the non-admin path.- delete_images_call = mock_invoker.services.images.delete_images_on_board.call_args- delete_videos_call = mock_invoker.services.videos.delete_videos_on_board.call_args- assert delete_images_call.kwargs.get("user_id") is not None- assert delete_videos_call.kwargs.get("user_id") is not None- # Both cascade calls must share the same user_id (the requester).- requester_id = delete_images_call.kwargs["user_id"]- assert delete_images_call.kwargs["user_id"] == requester_id- assert delete_videos_call.kwargs["user_id"] == requester_id+ # The router must pass the current user's id through to the enumeration — which is now what+ # narrows the cascade, since the names it captures are exactly the ones later destroyed.+ # Admins skip the filter (pass ``user_id=None``); this test exercises the non-admin path.+ images_call = mock_invoker.services.board_images.get_all_board_image_names_for_board.call_args+ videos_call = mock_invoker.services.board_video_records.get_all_board_video_names_for_board.call_args+ requester_id = images_call.kwargs.get("user_id")+ assert requester_id is not None+ # Both enumerations must share the same user_id (the requester).+ assert videos_call.kwargs.get("user_id") == requester_iddef test_delete_board_with_include_images_admin_skips_user_filter(@@ -873,10 +892,10 @@ def test_delete_board_with_include_images_admin_skips_user_filter()assert response.status_code == status.HTTP_200_OK- delete_images_call = mock_invoker.services.images.delete_images_on_board.call_args- delete_videos_call = mock_invoker.services.videos.delete_videos_on_board.call_args- assert delete_images_call.kwargs.get("user_id") is None- assert delete_videos_call.kwargs.get("user_id") is None+ images_call = mock_invoker.services.board_images.get_all_board_image_names_for_board.call_args+ videos_call = mock_invoker.services.board_video_records.get_all_board_video_names_for_board.call_args+ assert images_call.kwargs.get("user_id") is None+ assert videos_call.kwargs.get("user_id") is Nonedef test_delete_board_without_include_images_lists_uncategorized_videos(@@ -909,3 +928,118 @@ def test_delete_board_without_include_images_lists_uncategorized_videos(def test_delete_board_is_offloaded_by_fastapi() -> None:assert not inspect.iscoroutinefunction(delete_board)+++# ---------------------------------------------------------------------------+# Project-owned boards: the generic routes must not touch them+# ---------------------------------------------------------------------------+++def _claim_board_for_a_project(client: TestClient, mock_invoker: Invoker, token: str, name: str) -> str:+ """Create a board and hand it to a new project, returning the board id."""+ create = client.post(+ f"/api/v1/boards/?board_name={name}",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert create.status_code == status.HTTP_201_CREATED+ board = create.json()+ mock_invoker.services.project_records.create(+ user_id=board["user_id"],+ name="Owning project",+ data={},+ board_id=board["board_id"],+ )+ return board["board_id"]+++def test_a_project_board_reports_the_project_that_owns_it(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ board_id = _claim_board_for_a_project(client, mock_invoker, user1_token, "Claimed+Board")++ response = client.get(f"/api/v1/boards/{board_id}", headers={"Authorization": f"Bearer {user1_token}"})++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["project_id"] is not None++ listed = client.get("/api/v1/boards/?all=true", headers={"Authorization": f"Bearer {user1_token}"})+ claimed = [b for b in listed.json() if b["board_id"] == board_id]+ assert len(claimed) == 1+ assert claimed[0]["project_id"] is not None+++def test_an_unclaimed_board_omits_the_project_id(client: TestClient, user1_token: str):+ """`BoardRecord` excludes nulls, so a plain board must simply not carry the field."""+ create = client.post(+ "/api/v1/boards/?board_name=Plain+Board",+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert create.json().get("project_id") is None++[email protected]("changes", [{"board_name": "Renamed"}, {"archived": True}, {"board_visibility": "public"}])+def test_generic_update_of_a_project_board_is_refused(+ client: TestClient, mock_invoker: Invoker, user1_token: str, admin_token: str, changes: dict[str, Any]+):+ board_id = _claim_board_for_a_project(client, mock_invoker, user1_token, "Protected+Board")++ for token in (user1_token, admin_token):+ response = client.patch(+ f"/api/v1/boards/{board_id}",+ json=changes,+ headers={"Authorization": f"Bearer {token}"},+ )+ assert response.status_code == status.HTTP_409_CONFLICT++ # The project's name is still the board's name.+ board = client.get(f"/api/v1/boards/{board_id}", headers={"Authorization": f"Bearer {user1_token}"}).json()+ assert board["board_name"] == "Owning project"+ assert board["archived"] is False+ assert board["board_visibility"] == "private"+++def test_setting_only_the_cover_of_a_project_board_is_still_allowed(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ """The cover is a display detail with no bearing on the project relationship."""+ board_id = _claim_board_for_a_project(client, mock_invoker, user1_token, "Cover+Board")+ # `boards.cover_image_name` is a foreign key, so the image has to actually exist.+ with mock_invoker.services.board_records._db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO images (image_name, image_origin, image_category, width, height)"+ " VALUES ('cover.png', 'internal', 'general', 64, 64);"+ )++ response = client.patch(+ f"/api/v1/boards/{board_id}",+ json={"cover_image_name": "cover.png"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )++ assert response.status_code == status.HTTP_201_CREATED++[email protected]("include_images", [False, True])+def test_generic_deletion_of_a_project_board_is_refused_without_touching_media(+ client: TestClient, mock_invoker: Invoker, user1_token: str, admin_token: str, include_images: bool+):+ """The refusal must land before any media is destroyed — that is the whole point of+ enumerating first and deleting the board second."""+ board_id = _claim_board_for_a_project(client, mock_invoker, user1_token, "Undeletable+Board")+ mock_invoker.services.board_images.get_all_board_image_names_for_board.return_value = ["keep.png"]+ mock_invoker.services.board_video_records.get_all_board_video_names_for_board.return_value = ["keep.mp4"]++ for token in (user1_token, admin_token):+ response = client.delete(+ f"/api/v1/boards/{board_id}?include_images={'true' if include_images else 'false'}",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert response.status_code == status.HTTP_409_CONFLICT++ mock_invoker.services.images.delete_images_by_names.assert_not_called()+ mock_invoker.services.videos.delete_videos_by_names.assert_not_called()+ # The board is still there.+ assert (+ client.get(f"/api/v1/boards/{board_id}", headers={"Authorization": f"Bearer {user1_token}"}).status_code+ == status.HTTP_200_OK+ )diff --git a/tests/app/routers/test_projects.py b/tests/app/routers/test_projects.pynew file mode 100644index 0000000000..5126886884--- /dev/null+++ b/tests/app/routers/test_projects.py@@ -0,0 +1,236 @@+"""Router-level tests for projects, focused on the board every project owns.++The storage-level rules live in `tests/app/services/project_records/test_project_records.py`; what+these pin is the HTTP contract on top of them — which failure is a 404 and which is a 409, and that+a board handed to a project really does leave the generic board routes' reach.+"""++from typing import Any++import pytest+from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.invoker import Invoker+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def _create_board(client: TestClient, token: str, name: str = "Loose+Board") -> 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 _create_project(client: TestClient, token: str, **body: Any):+ return client.post("/api/v1/projects/", json={"name": "Project", "data": {}, **body}, headers=_auth(token))+++def test_creating_a_project_creates_and_returns_its_board(client: TestClient, user1_token: str):+ response = _create_project(client, user1_token, name="Fresh")++ assert response.status_code == status.HTTP_201_CREATED+ board_id = response.json()["board_id"]+ assert board_id++ board = client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token))+ assert board.status_code == status.HTTP_200_OK+ assert board.json()["board_name"] == "Fresh"+ assert board.json()["board_visibility"] == "private"+++def test_listing_projects_carries_the_board(client: TestClient, user1_token: str):+ created = _create_project(client, user1_token).json()++ listed = client.get("/api/v1/projects/", headers=_auth(user1_token))++ assert listed.status_code == status.HTTP_200_OK+ (summary,) = [p for p in listed.json() if p["project_id"] == created["project_id"]]+ assert summary["board_id"] == created["board_id"]+++def test_creating_a_project_claims_the_board_it_is_given(client: TestClient, user1_token: str):+ board_id = _create_board(client, user1_token, "Staging")++ response = _create_project(client, user1_token, name="Imported", board_id=board_id)++ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["board_id"] == board_id+ # Claiming renames the board to the project.+ board = client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).json()+ assert board["board_name"] == "Imported"+ assert board["project_id"] == response.json()["project_id"]+++def test_claiming_a_board_that_is_missing_or_someone_elses_is_a_404(+ client: TestClient, user1_token: str, user2_token: str+):+ theirs = _create_board(client, user2_token, "Theirs")++ assert _create_project(client, user1_token, board_id="no-such-board").status_code == status.HTTP_404_NOT_FOUND+ # Someone else's board must be indistinguishable from one that does not exist.+ assert _create_project(client, user1_token, board_id=theirs).status_code == status.HTTP_404_NOT_FOUND++[email protected]("visibility", ["shared", "public"])+def test_claiming_a_non_private_board_is_a_409(client: TestClient, user1_token: str, visibility: str):+ board_id = _create_board(client, user1_token, "Visible")+ patched = client.patch(+ f"/api/v1/boards/{board_id}", json={"board_visibility": visibility}, headers=_auth(user1_token)+ )+ assert patched.status_code == status.HTTP_201_CREATED++ assert _create_project(client, user1_token, board_id=board_id).status_code == status.HTTP_409_CONFLICT+++def test_a_board_can_only_be_claimed_once(client: TestClient, user1_token: str):+ board_id = _create_board(client, user1_token, "Contested")+ assert _create_project(client, user1_token, name="First", board_id=board_id).status_code == (+ status.HTTP_201_CREATED+ )++ second = _create_project(client, user1_token, name="Second", board_id=board_id)++ assert second.status_code == status.HTTP_409_CONFLICT+ board = client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).json()+ assert board["board_name"] == "First"+++def test_a_duplicate_project_id_is_a_409_and_leaves_no_orphan_board(client: TestClient, user1_token: str):+ assert _create_project(client, user1_token, project_id="p1").status_code == status.HTTP_201_CREATED+ before = len(client.get("/api/v1/boards/?all=true", headers=_auth(user1_token)).json())++ response = _create_project(client, user1_token, project_id="p1")++ assert response.status_code == status.HTTP_409_CONFLICT+ after = len(client.get("/api/v1/boards/?all=true", headers=_auth(user1_token)).json())+ assert after == before+++def test_saving_a_project_renames_its_board_but_a_stale_save_does_not(client: TestClient, user1_token: str):+ created = _create_project(client, user1_token, name="Before").json()+ project_id, board_id = created["project_id"], created["board_id"]++ saved = client.put(+ f"/api/v1/projects/{project_id}",+ json={"name": "After", "data": {}, "expected_revision": 1},+ headers=_auth(user1_token),+ )+ assert saved.status_code == status.HTTP_200_OK+ assert client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).json()["board_name"] == "After"++ stale = client.put(+ f"/api/v1/projects/{project_id}",+ json={"name": "Loser", "data": {}, "expected_revision": 1},+ headers=_auth(user1_token),+ )+ assert stale.status_code == status.HTTP_409_CONFLICT+ assert client.get(f"/api/v1/boards/{board_id}", headers=_auth(user1_token)).json()["board_name"] == "After"+++def test_deleting_a_project_deletes_its_board(client: TestClient, user1_token: str):+ created = _create_project(client, user1_token).json()++ deleted = client.delete(f"/api/v1/projects/{created['project_id']}", headers=_auth(user1_token))++ assert deleted.status_code == status.HTTP_204_NO_CONTENT+ board = client.get(f"/api/v1/boards/{created['board_id']}", headers=_auth(user1_token))+ assert board.status_code == status.HTTP_404_NOT_FOUND+++def test_deleting_a_project_leaves_its_media_uncategorized(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ created = _create_project(client, user1_token).json()+ with mock_invoker.services.board_records._db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO images (image_name, image_origin, image_category, width, height)"+ " VALUES ('kept.png', 'internal', 'general', 64, 64);"+ )+ cursor.execute(+ "INSERT INTO board_images (board_id, image_name) VALUES (?, 'kept.png');", (created["board_id"],)+ )++ client.delete(f"/api/v1/projects/{created['project_id']}", headers=_auth(user1_token))++ with mock_invoker.services.board_records._db.transaction() as cursor:+ cursor.execute("SELECT COUNT(*) FROM images WHERE image_name = 'kept.png';")+ assert cursor.fetchone()[0] == 1+ cursor.execute("SELECT COUNT(*) FROM board_images WHERE image_name = 'kept.png';")+ assert cursor.fetchone()[0] == 0+++def test_the_board_snapshot_lists_the_projects_visible_media(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ created = _create_project(client, user1_token).json()+ with mock_invoker.services.board_records._db.transaction() as cursor:+ for name, category, intermediate in (+ ("shown.png", "general", False),+ ("asset.png", "control", False),+ ("canvas.png", "other", False),+ ("scratch.png", "general", True),+ ):+ cursor.execute(+ "INSERT INTO images (image_name, image_origin, image_category, width, height, is_intermediate)"+ " VALUES (?, 'internal', ?, 64, 64, ?);",+ (name, category, intermediate),+ )+ cursor.execute(+ "INSERT INTO board_images (board_id, image_name) VALUES (?, ?);", (created["board_id"], name)+ )++ response = client.get(f"/api/v1/projects/{created['project_id']}/board-snapshot", headers=_auth(user1_token))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {+ "items": [+ {"category": "control", "kind": "image", "name": "asset.png", "starred": False},+ {"category": "general", "kind": "image", "name": "shown.png", "starred": False},+ ]+ }+++def test_the_board_snapshot_of_an_empty_project_is_empty(client: TestClient, user1_token: str):+ created = _create_project(client, user1_token).json()++ response = client.get(f"/api/v1/projects/{created['project_id']}/board-snapshot", headers=_auth(user1_token))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"items": []}+++def test_the_board_snapshot_of_a_missing_or_foreign_project_is_a_404(+ client: TestClient, user1_token: str, user2_token: str+):+ created = _create_project(client, user1_token).json()++ assert client.get("/api/v1/projects/nope/board-snapshot", headers=_auth(user1_token)).status_code == (+ status.HTTP_404_NOT_FOUND+ )+ assert client.get(+ f"/api/v1/projects/{created['project_id']}/board-snapshot", headers=_auth(user2_token)+ ).status_code == status.HTTP_404_NOT_FOUND+++def test_projects_stay_private_to_their_owner(client: TestClient, user1_token: str, user2_token: str):+ created = _create_project(client, user1_token).json()+ project_id = created["project_id"]++ assert client.get(f"/api/v1/projects/{project_id}", headers=_auth(user2_token)).status_code == (+ status.HTTP_404_NOT_FOUND+ )+ assert client.put(+ f"/api/v1/projects/{project_id}",+ json={"name": "Stolen", "data": {}, "expected_revision": 1},+ headers=_auth(user2_token),+ ).status_code == status.HTTP_404_NOT_FOUND++ # Deleting someone else's project is a silent no-op, and must not take their board with it.+ client.delete(f"/api/v1/projects/{project_id}", headers=_auth(user2_token))+ assert client.get(f"/api/v1/projects/{project_id}", headers=_auth(user1_token)).status_code == status.HTTP_200_OK+ assert client.get(f"/api/v1/boards/{created['board_id']}", headers=_auth(user1_token)).status_code == (+ status.HTTP_200_OK+ )diff --git a/tests/app/services/project_records/test_project_records.py b/tests/app/services/project_records/test_project_records.pyindex 55c2ae8f87..31e7ee3b95 100644--- a/tests/app/services/project_records/test_project_records.py+++ b/tests/app/services/project_records/test_project_records.py@@ -1,9 +1,11 @@-"""Tests for the project records service: CRUD, optimistic concurrency, and user isolation."""+"""Tests for the project records service: CRUD, optimistic concurrency, boards, and user isolation."""import pytestfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.project_records.project_records_common import (+ ProjectBoardNotFoundError,+ ProjectBoardUnavailableError,ProjectRecordConflictError,ProjectRecordExistsError,ProjectRecordNotFoundError,@@ -137,3 +139,315 @@ def test_users_cannot_touch_each_others_projects(project_records: ProjectRecordsproject_records.delete(other_user_id, created.project_id)# ...and the owner's project is untouched.assert project_records.get(SYSTEM_USER_ID, created.project_id).data == {"secret": True}+++# --- boards -----------------------------------------------------------------------------------+++def _insert_board(+ db: SqliteDatabase,+ board_id: str,+ *,+ user_id: str = SYSTEM_USER_ID,+ name: str = "Loose board",+ visibility: str = "private",+) -> str:+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO boards (board_id, board_name, user_id, board_visibility) VALUES (?, ?, ?, ?);",+ (board_id, name, user_id, visibility),+ )+ return board_id+++def _board_name(db: SqliteDatabase, board_id: str) -> str | None:+ with db.transaction() as cursor:+ cursor.execute("SELECT board_name FROM boards WHERE board_id = ?;", (board_id,))+ row = cursor.fetchone()+ return None if row is None else row[0]+++def _board_count(db: SqliteDatabase) -> int:+ with db.transaction() as cursor:+ cursor.execute("SELECT COUNT(*) FROM boards;")+ return cursor.fetchone()[0]+++def _add_image_to_board(db: SqliteDatabase, image_name: str, board_id: str) -> None:+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO images (image_name, image_origin, image_category, width, height)"+ " VALUES (?, 'internal', 'general', 64, 64);",+ (image_name,),+ )+ cursor.execute("INSERT INTO board_images (board_id, image_name) VALUES (?, ?);", (board_id, image_name))+++def test_create_makes_one_board_named_after_the_project(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ before = _board_count(db)++ created = project_records.create(SYSTEM_USER_ID, "My Project", {})++ assert _board_count(db) == before + 1+ assert created.board_id+ assert _board_name(db, created.board_id) == "My Project"+ assert project_records.get_board_id(SYSTEM_USER_ID, created.project_id) == created.board_id+++def test_create_claims_a_supplied_board_and_renames_it(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ _insert_board(db, "staging-board", name="Untitled")+ before = _board_count(db)++ created = project_records.create(SYSTEM_USER_ID, "Imported", {}, board_id="staging-board")++ assert created.board_id == "staging-board"+ assert _board_name(db, "staging-board") == "Imported"+ # Claiming reuses the board rather than making another.+ assert _board_count(db) == before+++def test_claiming_a_missing_or_foreign_board_reports_it_as_missing(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, other_user_id: str+) -> None:+ _insert_board(db, "theirs", user_id=other_user_id)++ with pytest.raises(ProjectBoardNotFoundError):+ project_records.create(SYSTEM_USER_ID, "P", {}, board_id="no-such-board")++ # Someone else's board must not be distinguishable from one that does not exist.+ with pytest.raises(ProjectBoardNotFoundError):+ project_records.create(SYSTEM_USER_ID, "P", {}, board_id="theirs")++[email protected]("visibility", ["shared", "public"])+def test_claiming_a_non_private_board_is_rejected(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, visibility: str+) -> None:+ _insert_board(db, "visible", visibility=visibility)++ with pytest.raises(ProjectBoardUnavailableError):+ project_records.create(SYSTEM_USER_ID, "P", {}, board_id="visible")+++def test_claiming_an_explicitly_shared_board_is_rejected(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, other_user_id: str+) -> None:+ _insert_board(db, "lent-out")+ with db.transaction() as cursor:+ cursor.execute("INSERT INTO shared_boards (board_id, user_id) VALUES ('lent-out', ?);", (other_user_id,))++ with pytest.raises(ProjectBoardUnavailableError):+ project_records.create(SYSTEM_USER_ID, "P", {}, board_id="lent-out")+++def test_a_board_can_only_ever_be_claimed_once(project_records: ProjectRecordsSqlite, db: SqliteDatabase) -> None:+ _insert_board(db, "contested")+ project_records.create(SYSTEM_USER_ID, "First", {}, board_id="contested")++ with pytest.raises(ProjectBoardUnavailableError):+ project_records.create(SYSTEM_USER_ID, "Second", {}, board_id="contested")++ assert _board_name(db, "contested") == "First"+++def test_a_rejected_create_leaves_no_orphan_board(project_records: ProjectRecordsSqlite, db: SqliteDatabase) -> None:+ project_records.create(SYSTEM_USER_ID, "Taken", {}, project_id="project-taken")+ before = _board_count(db)++ with pytest.raises(ProjectRecordExistsError):+ project_records.create(SYSTEM_USER_ID, "Again", {}, project_id="project-taken")++ # The board insert shares the failed insert's transaction, so it rolled back with it.+ assert _board_count(db) == before+++def test_a_rejected_claim_leaves_the_board_name_alone(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ _insert_board(db, "staging", name="Untitled")+ project_records.create(SYSTEM_USER_ID, "Taken", {}, project_id="project-taken")++ with pytest.raises(ProjectRecordExistsError):+ project_records.create(SYSTEM_USER_ID, "Renamer", {}, project_id="project-taken", board_id="staging")++ assert _board_name(db, "staging") == "Untitled"+++def test_rename_renames_the_board_but_only_on_a_winning_save(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Before", {})++ project_records.update(SYSTEM_USER_ID, created.project_id, expected_revision=1, name="After", data={})+ assert _board_name(db, created.board_id) == "After"++ with pytest.raises(ProjectRecordConflictError):+ project_records.update(SYSTEM_USER_ID, created.project_id, expected_revision=1, name="Loser", data={})++ assert _board_name(db, created.board_id) == "After"+++def test_delete_removes_the_board_and_its_membership_but_keeps_the_media(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Doomed", {})+ _add_image_to_board(db, "kept.png", created.board_id)++ project_records.delete(SYSTEM_USER_ID, created.project_id)++ assert _board_name(db, created.board_id) is None+ with db.transaction() as cursor:+ cursor.execute("SELECT COUNT(*) FROM board_images WHERE image_name = 'kept.png';")+ assert cursor.fetchone()[0] == 0+ # The image itself survives, uncategorized.+ cursor.execute("SELECT COUNT(*) FROM images WHERE image_name = 'kept.png';")+ assert cursor.fetchone()[0] == 1+++def test_summaries_and_records_both_carry_the_board(project_records: ProjectRecordsSqlite) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Listed", {})++ (summary,) = [s for s in project_records.list(SYSTEM_USER_ID) if s.project_id == created.project_id]+ assert summary.board_id == created.board_id+++def test_get_board_id_is_user_scoped(project_records: ProjectRecordsSqlite, other_user_id: str) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Private", {})++ with pytest.raises(ProjectRecordNotFoundError):+ project_records.get_board_id(other_user_id, created.project_id)+++# --- board snapshot ---------------------------------------------------------------------------+++def _put_image(+ db: SqliteDatabase,+ name: str,+ board_id: str,+ *,+ category: str = "general",+ starred: bool = False,+ is_intermediate: bool = False,+) -> None:+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO images (image_name, image_origin, image_category, width, height, starred, is_intermediate)"+ " VALUES (?, 'internal', ?, 64, 64, ?, ?);",+ (name, category, starred, is_intermediate),+ )+ cursor.execute("INSERT INTO board_images (board_id, image_name) VALUES (?, ?);", (board_id, name))+++def _put_video(+ db: SqliteDatabase,+ name: str,+ board_id: str,+ *,+ category: str = "general",+ starred: bool = False,+ is_intermediate: bool = False,+) -> None:+ with db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO videos (video_name, video_origin, video_category, width, height, starred, is_intermediate)"+ " VALUES (?, 'internal', ?, 64, 64, ?, ?);",+ (name, category, starred, is_intermediate),+ )+ cursor.execute("INSERT INTO board_videos (board_id, video_name) VALUES (?, ?);", (board_id, name))+++def test_the_snapshot_lists_every_visible_category_of_both_kinds(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Full", {})+ for category in ("general", "control", "mask", "user"):+ _put_image(db, f"{category}.png", created.board_id, category=category)+ _put_video(db, f"{category}.mp4", created.board_id, category=category)++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++ assert {(item.kind, item.name, item.category) for item in snapshot.items} == {+ (kind, f"{category}.{ext}", category)+ for category in ("general", "control", "mask", "user")+ for kind, ext in (("image", "png"), ("video", "mp4"))+ }+++def test_the_snapshot_excludes_what_the_gallery_does_not_show(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Filtered", {})+ _put_image(db, "shown.png", created.board_id)+ # `other` is the canvas's private category — in neither gallery view, so not board membership.+ _put_image(db, "canvas.png", created.board_id, category="other")+ _put_image(db, "scratch.png", created.board_id, is_intermediate=True)+ _put_video(db, "shown.mp4", created.board_id)+ _put_video(db, "canvas.mp4", created.board_id, category="other")+ _put_video(db, "scratch.mp4", created.board_id, is_intermediate=True)++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++ assert [item.name for item in snapshot.items] == ["shown.png", "shown.mp4"]+++def test_the_snapshot_excludes_media_on_other_boards(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ mine = project_records.create(SYSTEM_USER_ID, "Mine", {})+ theirs = project_records.create(SYSTEM_USER_ID, "Other", {})+ _put_image(db, "mine.png", mine.board_id)+ _put_image(db, "theirs.png", theirs.board_id)++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, mine.project_id)++ assert [item.name for item in snapshot.items] == ["mine.png"]+++def test_the_snapshot_carries_starring_and_is_ordered_by_kind_then_name(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Ordered", {})+ _put_image(db, "b.png", created.board_id, starred=True)+ _put_image(db, "a.png", created.board_id)+ _put_video(db, "a.mp4", created.board_id)++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++ assert [(item.kind, item.name, item.starred) for item in snapshot.items] == [+ ("image", "a.png", False),+ ("image", "b.png", True),+ ("video", "a.mp4", False),+ ]+++def test_a_same_name_image_and_video_are_separate_entries(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase+) -> None:+ """Images and videos are separate namespaces, so one name can legitimately be both."""+ created = project_records.create(SYSTEM_USER_ID, "Twins", {})+ _put_image(db, "twin", created.board_id)+ _put_video(db, "twin", created.board_id)++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++ assert [(item.kind, item.name) for item in snapshot.items] == [("image", "twin"), ("video", "twin")]+++def test_an_empty_board_snapshots_to_an_empty_list(project_records: ProjectRecordsSqlite) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Empty", {})++ assert project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id).items == []+++def test_snapshotting_someone_elses_project_is_not_found(+ project_records: ProjectRecordsSqlite, other_user_id: str+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Private", {})++ with pytest.raises(ProjectRecordNotFoundError):+ project_records.get_board_snapshot(other_user_id, created.project_id)diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.pynew file mode 100644index 0000000000..924bca8675--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py@@ -0,0 +1,477 @@+import json+import sqlite3+from logging import Logger+from pathlib import Path+from typing import Any, Optional+from unittest.mock import MagicMock++from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase+from invokeai.app.services.shared.sqlite_migrator.migration_loader import MigrationBuildContext, build_migrations+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_08_06_add_project_boards import (+ AddProjectBoardsMigrationCallback,+ build_migration,+)+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import SqliteMigrator++MIGRATION_ID = "2026_08_06_add_project_boards"+++def _make_db() -> sqlite3.Connection:+ """A database holding just the tables this migration reads and writes."""+ db = sqlite3.connect(":memory:")+ db.execute("PRAGMA foreign_keys = ON;")+ db.executescript(+ """+ CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);++ CREATE TABLE boards (+ board_id TEXT NOT NULL PRIMARY KEY,+ board_name TEXT NOT NULL,+ cover_image_name TEXT,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ deleted_at DATETIME,+ archived BOOLEAN DEFAULT FALSE,+ user_id TEXT DEFAULT 'system',+ is_public BOOLEAN NOT NULL DEFAULT FALSE,+ board_visibility TEXT NOT NULL DEFAULT 'private'+ );++ CREATE TABLE shared_boards (+ board_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ can_edit BOOLEAN NOT NULL DEFAULT FALSE,+ PRIMARY KEY (board_id, user_id),+ FOREIGN KEY (board_id) REFERENCES boards(board_id) ON DELETE CASCADE,+ FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE+ );++ CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY);+ CREATE TABLE videos (video_name TEXT NOT NULL PRIMARY KEY);++ CREATE TABLE board_images (+ board_id TEXT NOT NULL,+ image_name TEXT NOT NULL,+ PRIMARY KEY (image_name),+ FOREIGN KEY (board_id) REFERENCES boards (board_id) ON DELETE CASCADE,+ FOREIGN KEY (image_name) REFERENCES images (image_name) ON DELETE CASCADE+ );++ CREATE TABLE board_videos (+ board_id TEXT NOT NULL,+ video_name TEXT NOT NULL,+ PRIMARY KEY (video_name),+ FOREIGN KEY (board_id) REFERENCES boards (board_id) ON DELETE CASCADE,+ FOREIGN KEY (video_name) REFERENCES videos (video_name) ON DELETE CASCADE+ );++ CREATE TABLE projects (+ project_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ name TEXT NOT NULL,+ data TEXT NOT NULL,+ revision INTEGER NOT NULL DEFAULT 1,+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (user_id, project_id),+ FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE+ );++ CREATE TRIGGER tg_projects_updated_at+ AFTER UPDATE ON projects+ FOR EACH ROW+ BEGIN+ UPDATE projects+ SET updated_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')+ WHERE user_id = OLD.user_id AND project_id = OLD.project_id;+ END;+ """+ )+ return db+++def _add_user(db: sqlite3.Connection, user_id: str) -> None:+ db.execute("INSERT INTO users VALUES (?);", (user_id,))+++def _add_board(+ db: sqlite3.Connection,+ board_id: str,+ *,+ user_id: str = "u1",+ name: str = "Board",+ visibility: str = "private",+) -> None:+ db.execute(+ "INSERT INTO boards (board_id, board_name, user_id, board_visibility) VALUES (?, ?, ?, ?);",+ (board_id, name, user_id, visibility),+ )+++def _gallery_document(*board_ids: Optional[str], legacy: bool = False) -> str:+ """A project document naming one gallery widget per supplied board id."""+ if legacy:+ (board_id,) = board_ids+ return json.dumps({"widgetStates": {"gallery": {"values": {"projectBoardId": board_id}}}})++ instances: dict[str, Any] = {}+ for index, board_id in enumerate(board_ids):+ values: dict[str, Any] = {} if board_id is None else {"projectBoardId": board_id}+ instances[f"gallery-{index}"] = {"typeId": "gallery", "state": {"values": values}}+ # A non-gallery widget that happens to carry the key must never be read.+ instances["canvas-0"] = {"typeId": "canvas", "state": {"values": {"projectBoardId": "board-decoy"}}}+ return json.dumps({"widgetInstances": instances})+++def _add_project(+ db: sqlite3.Connection,+ project_id: str,+ *,+ user_id: str = "u1",+ name: str = "Project",+ data: str = "{}",+) -> None:+ db.execute(+ "INSERT INTO projects (project_id, user_id, name, data) VALUES (?, ?, ?, ?);",+ (project_id, user_id, name, data),+ )+++def _board_of(db: sqlite3.Connection, project_id: str, user_id: str = "u1") -> str:+ cursor = db.execute(+ "SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;", (user_id, project_id)+ )+ row = cursor.fetchone()+ assert row is not None+ return row[0]+++def _run(db: sqlite3.Connection) -> None:+ AddProjectBoardsMigrationCallback()(db.cursor())+++# --- adoption -------------------------------------------------------------------------------+++def test_adopts_the_single_valid_candidate_and_renames_it_to_the_project() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1", name="Old board name")+ _add_project(db, "p1", name="My project", data=_gallery_document("board-1"))++ _run(db)++ assert _board_of(db, "p1") == "board-1"+ assert db.execute("SELECT board_name FROM boards WHERE board_id = 'board-1';").fetchone()[0] == "My project"+++def test_adopts_a_candidate_written_in_the_legacy_widget_states_shape() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_project(db, "p1", data=_gallery_document("board-1", legacy=True))++ _run(db)++ assert _board_of(db, "p1") == "board-1"+++def test_adopts_when_several_gallery_instances_name_the_same_board() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_project(db, "p1", data=_gallery_document("board-1", "board-1"))++ _run(db)++ assert _board_of(db, "p1") == "board-1"+++def test_creates_a_fresh_board_when_two_candidates_disagree() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_board(db, "board-2")+ _add_project(db, "p1", data=_gallery_document("board-1", "board-2"))++ _run(db)++ assert _board_of(db, "p1") not in {"board-1", "board-2"}+++def test_creates_a_fresh_board_for_each_disqualified_candidate() -> None:+ """Every ownership test, one project each, so a regression names the rule it broke."""+ db = _make_db()+ _add_user(db, "u1")+ _add_user(db, "u2")++ _add_board(db, "board-foreign", user_id="u2")+ _add_project(db, "p-foreign", data=_gallery_document("board-foreign"))++ _add_board(db, "board-shared-visibility", visibility="shared")+ _add_project(db, "p-shared-visibility", data=_gallery_document("board-shared-visibility"))++ _add_board(db, "board-public", visibility="public")+ _add_project(db, "p-public", data=_gallery_document("board-public"))++ _add_board(db, "board-share-row")+ db.execute("INSERT INTO shared_boards (board_id, user_id) VALUES ('board-share-row', 'u2');")+ _add_project(db, "p-share-row", data=_gallery_document("board-share-row"))++ _add_project(db, "p-missing", data=_gallery_document("board-does-not-exist"))+ _add_project(db, "p-none", data="{}")+ _add_project(db, "p-malformed", data="not json at all")+ _add_project(db, "p-empty-id", data=_gallery_document(""))+ _add_project(db, "p-no-values", data=_gallery_document(None))++ _run(db)++ disqualified = {+ "board-foreign",+ "board-shared-visibility",+ "board-public",+ "board-share-row",+ "board-does-not-exist",+ "board-decoy",+ }+ for project_id in (+ "p-foreign",+ "p-shared-visibility",+ "p-public",+ "p-share-row",+ "p-missing",+ "p-none",+ "p-malformed",+ "p-empty-id",+ "p-no-values",+ ):+ assert _board_of(db, project_id) not in disqualified+++def test_the_earlier_project_wins_a_board_two_projects_both_name() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_project(db, "p-first", data=_gallery_document("board-1"))+ _add_project(db, "p-second", data=_gallery_document("board-1"))++ _run(db)++ assert _board_of(db, "p-first") == "board-1"+ assert _board_of(db, "p-second") != "board-1"+++def test_two_users_may_share_a_project_id_and_still_get_distinct_boards() -> None:+ """`projects` is keyed (user_id, project_id), so the same id on two users is legal."""+ db = _make_db()+ _add_user(db, "u1")+ _add_user(db, "u2")+ _add_project(db, "shared-id", user_id="u1", name="Mine")+ _add_project(db, "shared-id", user_id="u2", name="Theirs")++ _run(db)++ assert _board_of(db, "shared-id", "u1") != _board_of(db, "shared-id", "u2")+++def test_a_created_board_is_private_unarchived_and_owned_by_the_project_owner() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_project(db, "p1", name="Fresh project")++ _run(db)++ row = db.execute(+ "SELECT board_name, user_id, board_visibility, archived FROM boards WHERE board_id = ?;",+ (_board_of(db, "p1"),),+ ).fetchone()+ assert row == ("Fresh project", "u1", "private", 0)+++def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_project(db, "p1", name="x" * 400)++ _run(db)++ name = db.execute("SELECT board_name FROM boards WHERE board_id = ?;", (_board_of(db, "p1"),)).fetchone()[0]+ assert len(name) == 300+++# --- structure ------------------------------------------------------------------------------+++def test_every_project_gets_a_unique_board_and_the_column_rejects_reuse() -> None:+ db = _make_db()+ _add_user(db, "u1")+ for index in range(5):+ _add_project(db, f"p{index}")++ _run(db)++ board_ids = [row[0] for row in db.execute("SELECT board_id FROM projects;").fetchall()]+ assert len(board_ids) == 5+ assert all(board_id is not None for board_id in board_ids)+ assert len(set(board_ids)) == 5++ try:+ db.execute(+ "INSERT INTO projects (project_id, user_id, name, data, board_id) VALUES ('px','u1','n','{}',?);",+ (board_ids[0],),+ )+ raise AssertionError("a second project claimed the same board")+ except sqlite3.IntegrityError:+ pass+++def test_a_claimed_board_cannot_be_deleted_out_from_under_its_project() -> None:+ """The FK is the database-level backstop behind the API's 409."""+ db = _make_db()+ _add_user(db, "u1")+ _add_project(db, "p1")+ _run(db)++ try:+ db.execute("DELETE FROM boards WHERE board_id = ?;", (_board_of(db, "p1"),))+ raise AssertionError("a claimed board was deleted")+ except sqlite3.IntegrityError:+ pass+++def test_board_membership_is_never_touched() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_board(db, "board-2")+ db.execute("INSERT INTO images VALUES ('i1.png');")+ db.execute("INSERT INTO videos VALUES ('v1.mp4');")+ db.execute("INSERT INTO board_images VALUES ('board-1', 'i1.png');")+ db.execute("INSERT INTO board_videos VALUES ('board-2', 'v1.mp4');")+ _add_project(db, "p1", data=_gallery_document("board-1"))++ _run(db)++ assert db.execute("SELECT board_id, image_name FROM board_images;").fetchall() == [("board-1", "i1.png")]+ assert db.execute("SELECT board_id, video_name FROM board_videos;").fetchall() == [("board-2", "v1.mp4")]+++def test_the_rebuilt_table_keeps_its_key_columns_ordering_and_trigger() -> None:+ db = _make_db()+ _add_user(db, "u1")+ db.execute(+ "INSERT INTO projects (project_id, user_id, name, data, revision, created_at, updated_at)"+ " VALUES ('p1','u1','first','{}', 7, '2020-01-01 00:00:00.000', '2020-01-02 00:00:00.000');"+ )+ # Same created_at as p1, so only insertion order can separate them.+ db.execute(+ "INSERT INTO projects (project_id, user_id, name, data, revision, created_at, updated_at)"+ " VALUES ('p2','u1','second','{}', 1, '2020-01-01 00:00:00.000', '2020-01-02 00:00:00.000');"+ )++ _run(db)++ assert db.execute(+ "SELECT project_id, name, revision, created_at, updated_at FROM projects ORDER BY created_at, rowid;"+ ).fetchall() == [+ ("p1", "first", 7, "2020-01-01 00:00:00.000", "2020-01-02 00:00:00.000"),+ ("p2", "second", 1, "2020-01-01 00:00:00.000", "2020-01-02 00:00:00.000"),+ ]++ # The composite primary key survives the rebuild.+ try:+ _add_project(db, "p1")+ raise AssertionError("duplicate (user_id, project_id) was accepted")+ except sqlite3.IntegrityError:+ pass++ db.execute("UPDATE projects SET name = 'renamed' WHERE project_id = 'p1';")+ assert db.execute("SELECT updated_at FROM projects WHERE project_id = 'p1';").fetchone()[0] != (+ "2020-01-02 00:00:00.000"+ )+++def test_deleting_a_user_still_cascades_their_projects() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_project(db, "p1")+ _run(db)++ db.execute("DELETE FROM users WHERE user_id = 'u1';")++ assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 0+++def test_foreign_keys_are_consistent_afterwards() -> None:+ db = _make_db()+ _add_user(db, "u1")+ _add_board(db, "board-1")+ _add_project(db, "p1", data=_gallery_document("board-1"))+ _add_project(db, "p2")++ _run(db)++ assert db.execute("PRAGMA foreign_key_check;").fetchall() == []+++def test_an_empty_projects_table_migrates_cleanly() -> None:+ db = _make_db()++ _run(db)++ assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 0+ assert db.execute("PRAGMA foreign_key_check;").fetchall() == []+++# --- registration ---------------------------------------------------------------------------+++def test_migration_has_a_dated_id_and_depends_on_the_projects_repair() -> None:+ migration = build_migration()+ assert migration.id == MIGRATION_ID+ assert migration.depends_on == "2026_07_30_repair_projects_table"+ assert migration.from_version is None+ assert migration.to_version is None+++def test_it_runs_once_through_the_real_migrator_and_is_not_reapplied(tmp_path: Path) -> None:+ """End-to-end against the real schema: migrate to just before this migration, seed a project+ with a live board reference, then let the full migrator carry it the rest of the way."""+ logger = Logger("test")+ context = MigrationBuildContext(app_config=MagicMock(), logger=logger, image_files=MagicMock())+ all_migrations = build_migrations(context)++ db = SqliteDatabase(db_path=tmp_path / "projects.db", logger=logger, verbose=False)++ before = SqliteMigrator(db=db)+ for migration in all_migrations:+ if migration.id != MIGRATION_ID:+ before.register_migration(migration)+ before.run_migrations()++ cursor = db._conn.cursor()+ cursor.execute("INSERT INTO boards (board_id, board_name, user_id) VALUES ('b1', 'Old name', 'system');")+ cursor.execute(+ "INSERT INTO projects (project_id, user_id, name, data) VALUES ('p1', 'system', 'Kept', ?);",+ (_gallery_document("b1"),),+ )+ db._conn.commit()++ full = SqliteMigrator(db=db)+ for migration in all_migrations:+ full.register_migration(migration)+ assert full.run_migrations() is True++ # SqliteDatabase sets row_factory = sqlite3.Row, which does not compare equal to a tuple.+ cursor.execute("SELECT name, board_id FROM projects WHERE project_id = 'p1';")+ assert tuple(cursor.fetchone()) == ("Kept", "b1")+ cursor.execute("SELECT board_name FROM boards WHERE board_id = 'b1';")+ assert tuple(cursor.fetchone()) == ("Kept",)+ cursor.execute("PRAGMA foreign_key_check;")+ assert cursor.fetchall() == []++ # Migration tracking, not idempotent DDL, is what stops a second run rebuilding the table again.+ again = SqliteMigrator(db=db)+ for migration in all_migrations:+ again.register_migration(migration)+ assert again.run_migrations() is False