Skip to content

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

feat(boards): let boards belong to projects, with an inbox per project

Josh Corbett9a709776deb3
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index 85c4828d23..e37a8b489b 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -8,13 +8,16 @@ Import also accepts the `.invokeproject.json` envelope shipped by earlier webv2
`.invk` is shared with the previous frontend's [canvas projects](/development/front-end/canvas-projects/), which write version 1 of the same container. Workbench projects write version 2. The two are deliberately not interchangeable — see [Versions](#versions).
-## Every project owns one board
+## Boards belong to projects
-The backend gives each project exactly one private board (`projects.board_id` is `NOT NULL UNIQUE` with a foreign key to `boards`). The board is the project's workspace: everything it generates lands there, and only the project APIs may touch it.
+A board lives in exactly one of its owner's projects, or in the **Library** — the tier every project can see. `boards.project_id` is the stored membership (`NULL` is the Library); it is a plain indexed column rather than a foreign key, because `projects` is keyed by `(user_id, project_id)` and adding a composite constraint would mean rebuilding `boards` under enforced cascades. The services keep it consistent: `POST /boards/?project_id=` inserts from the project row itself, `PATCH /boards/{id}` with `project_id` (a project, or `null` for the Library) moves a board and guards the destination's existence in the same `UPDATE`, and both answer `404` for a project the owner does not have. Boards in a project are private and unshared; a move or visibility change that would make a member otherwise is refused with `409`.
-- **Renaming** a project renames its board in the same transaction. The generic `PATCH /boards/{id}` refuses a claimed board with `409`, so the two names cannot commit independently.
-- **Deleting** a project deletes its board with it, in one transaction. `DELETE /boards/{id}` refuses a claimed board *before* touching any media, and the foreign key is the backstop for a board claimed concurrently.
-- **The media survives.** Deleting a project removes the board and its memberships; the images and videos themselves return to Uncategorized, exactly as they would if the board were deleted without `include_images`.
+Every project also has an **inbox**: the one board `projects.board_id` names (`NOT NULL UNIQUE`, foreign key `ON DELETE RESTRICT`). It is created with the project, is always a member of it, and is the only board the project APIs manage.
+
+- **Renaming** a project renames its inbox in the same transaction. The generic `PATCH /boards/{id}` refuses to rename, archive, publish or move an inbox with `409`, so the two names cannot commit independently; its cover may still change. `BoardDTO.is_inbox` is how clients tell it apart from an ordinary member.
+- **Deleting** a project deletes its inbox with it, in one transaction, and either releases its other boards to the Library (`?boards=release`, the default) or deletes them too (`?boards=delete`). `DELETE /boards/{id}` refuses an inbox *before* touching any media, and the foreign key is the backstop for a board claimed concurrently.
+- **The media survives.** No path through the project APIs deletes media: a deleted board drops its memberships, and the images and videos return to Uncategorized, exactly as they would if the board were deleted without `include_images`.
+- **Imports adopt a Library board as the inbox.** `POST /projects` with `board_id` claims an unclaimed private board, renames it and makes it a member; a board already in another project is refused as unavailable.
- **The document's `projectBoardId` is a cache, never the truth.** Hydration overwrites it from the project record, and export strips it — along with `selectedBoardId` — because a board id means nothing on the install a project arrives at. Board ids elsewhere in a document, such as a workflow node's board input, are deliberately left alone.
## Synced canvas schema compatibility
@@ -218,6 +221,6 @@ Earlier webv2 builds exported `*.invokeproject.json` files containing a version
The archive stores references to models, LoRAs and other generation resources, not the model files themselves. Loading a project on another install restores its canvas and images, but missing models still need to be installed or replaced.
-**Not exported:** models and LoRAs, library templates themselves, queue history, intermediates, the canvas's private `other` media except where the document references it, gallery boards other than the project's own, and account preferences. A project file carries one project's workspace, not the install around it.
+**Not exported:** models and LoRAs, library templates themselves, queue history, intermediates, the canvas's private `other` media except where the document references it, gallery boards other than the project's inbox, and account preferences. A project file carries one project's workspace, not the install around it.
**Workflows travel with the project.** A schema-3 document carries the project's whole workflow collection (`workflows.entries`, each with its document and optional source and last-run metadata) and its active selection, so an archive holds every workflow the project owns, active or not, and every media reference they name is bundled like any other document reference. Source metadata names the library template a copy came from; import clears it, because a template id on one install names nothing on another and a portable file must never inherit a library write target. Same-server duplication keeps it. Older archives that carry a schema-2 `projectGraph` load through the same migration as older server documents: that graph becomes the project's first and only workflow.
diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.py
index 6b0683b5a4..026b741e79 100644
--- a/invokeai/app/api/routers/boards.py
+++ b/invokeai/app/api/routers/boards.py
@@ -10,8 +10,10 @@ from invokeai.app.api.routers._access import assert_board_read_access as _assert
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.services.board_records.board_records_common import (
BoardChanges,
+ BoardRecordInboxException,
BoardRecordOrderBy,
- BoardRecordProjectOwnedException,
+ BoardRecordProjectNotFoundException,
+ BoardRecordProjectUnavailableException,
)
from invokeai.app.services.boards.boards_common import BoardDTO
from invokeai.app.services.image_records.image_records_common import ImageCategory
@@ -57,11 +59,18 @@ class DeleteBoardResult(BaseModel):
def create_board(
current_user: CurrentUserOrDefault,
board_name: str = Query(description="The name of the board to create", max_length=300),
+ project_id: Optional[str] = Query(
+ default=None,
+ description="One of the current user's projects to create the board in; omit for the Library",
+ ),
) -> BoardDTO:
- """Creates a board for the current user"""
+ """Creates a board for the current user, in one of their projects or in the Library"""
try:
- result = ApiDependencies.invoker.services.boards.create(board_name=board_name, user_id=current_user.user_id)
- return result
+ return ApiDependencies.invoker.services.boards.create(
+ board_name=board_name, user_id=current_user.user_id, project_id=project_id
+ )
+ except BoardRecordProjectNotFoundException:
+ raise HTTPException(status_code=404, detail="Project not found")
except Exception:
raise HTTPException(status_code=500, detail="Failed to create board")
@@ -97,7 +106,14 @@ def update_board(
board_id: str = Path(description="The id of board to update"),
changes: BoardChanges = Body(description="The changes to apply to the board"),
) -> BoardDTO:
- """Updates a board (user must have access to it)"""
+ """Updates a board (user must have access to it).
+
+ A project's inbox takes its name, archived state and visibility from the project and cannot be
+ moved, so those changes are refused for it — for admins too; its cover is still fair game. A
+ board in a project is private and unshared, so a move into a project, or a visibility change on
+ a member, is refused when the result would be otherwise. The storage decides all of this in one
+ transaction; the DTO read here is only for the ownership check.
+ """
try:
board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
except Exception:
@@ -106,25 +122,17 @@ 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
- except BoardRecordProjectOwnedException:
+ return ApiDependencies.invoker.services.boards.update(board_id=board_id, changes=changes)
+ except BoardRecordInboxException:
raise HTTPException(
status_code=409,
- detail="This board belongs to a project; rename or archive the project instead",
+ detail="This board is the project's inbox; rename or archive the project instead",
)
+ except BoardRecordProjectNotFoundException:
+ raise HTTPException(status_code=404, detail="Project not found")
+ except BoardRecordProjectUnavailableException:
+ raise HTTPException(status_code=409, detail="Boards in a project must be private and unshared")
except Exception:
raise HTTPException(status_code=500, detail="Failed to update board")
@@ -159,7 +167,7 @@ def delete_board(
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
+ # a project's inbox 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.
@@ -181,13 +189,12 @@ def delete_board(
)
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
+ # `get_dto` above proved the board existed, so it is either an inbox 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:
+ if board_id in ApiDependencies.invoker.services.board_records.get_inbox_board_ids([board_id]):
raise HTTPException(
status_code=409,
- detail="This board belongs to a project; delete the project instead",
+ detail="This board is the project's inbox; delete the project instead",
)
raise HTTPException(status_code=404, detail="Board not found")
board_deleted = True
diff --git a/invokeai/app/api/routers/projects.py b/invokeai/app/api/routers/projects.py
index a76bbcd873..9331e9b977 100644
--- a/invokeai/app/api/routers/projects.py
+++ b/invokeai/app/api/routers/projects.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal
from fastapi import Body, HTTPException, Path, Query, status
from fastapi.routing import APIRouter
@@ -42,9 +42,9 @@ class ProjectCreateRequest(BaseModel):
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."
+ "An existing unclaimed private Library board for the project to adopt as its inbox, 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")
@@ -123,7 +123,7 @@ def create_project(
current_user: CurrentUserOrDefault,
request: ProjectCreateRequest = Body(description="The project to create"),
) -> ProjectRecordDTO:
- """Creates a project, and the private board it owns, for the current user."""
+ """Creates a project, and the private inbox board it owns, for the current user."""
try:
return ApiDependencies.invoker.services.project_records.create(
user_id=current_user.user_id,
@@ -218,7 +218,7 @@ 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.
+ """Lists everything on the project's inbox 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. It is still bounded,
@@ -238,13 +238,20 @@ def get_project_board_snapshot(
def delete_project(
current_user: CurrentUserOrDefault,
project_id: str = Path(description="The id of the project to delete"),
+ boards: Literal["release", "delete"] = Query(
+ default="release",
+ description=(
+ "What becomes of the project's boards other than its inbox: released to the Library with their"
+ " media, or deleted so their media returns to Uncategorized"
+ ),
+ ),
) -> None:
- """Deletes one of the current user's projects, and the board it owns, in one transaction.
+ """Deletes one of the current user's projects and its inbox, in one transaction.
- Idempotent. The media survives: deleting the board drops its memberships, so the images and
- videos on it return to Uncategorized, exactly as they would if the board were deleted without
+ Idempotent. The media survives either way: deleting a board drops its memberships, so the images
+ and videos on it return to Uncategorized, exactly as they would if the board were deleted without
`include_images`. There is deliberately no option to take them with it — a project is a
workspace, and emptying someone's gallery is not what deleting one should be able to mean.
Nothing is reported back for the same reason: nothing was destroyed to report.
"""
- ApiDependencies.invoker.services.project_records.delete(current_user.user_id, project_id)
+ ApiDependencies.invoker.services.project_records.delete(current_user.user_id, project_id, boards=boards)
diff --git a/invokeai/app/services/board_records/board_records_base.py b/invokeai/app/services/board_records/board_records_base.py
index 7eb98ccd09..851694fca9 100644
--- a/invokeai/app/services/board_records/board_records_base.py
+++ b/invokeai/app/services/board_records/board_records_base.py
@@ -11,7 +11,7 @@ class BoardRecordStorageBase(ABC):
@abstractmethod
def delete_if_unclaimed(self, board_id: str) -> bool:
- """Delete a board only if no project owns it. Returns whether it was deleted.
+ """Delete a board unless it is a project's inbox. 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.
@@ -20,18 +20,17 @@ class BoardRecordStorageBase(ABC):
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.
+ def get_inbox_board_ids(self, board_ids: list[str]) -> set[str]:
+ """Which of these boards are some project's inbox.
- Boards with no project are absent from the result. Bulk because board listings would
- otherwise issue one lookup per row; chunked internally, because a listing can name every
- board on the install and the query is parameterized per id.
+ Bulk because board listings would otherwise issue one lookup per row; chunked internally,
+ because a listing can name every board on the install and the query is parameterized per id.
"""
pass
@abstractmethod
- def get_with_project_id(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:
- """The board record and the id of the project that claims it, if any, in one query."""
+ def get_with_inbox_project(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:
+ """The board record and the id of the project whose inbox it is, if any, in one query."""
pass
@abstractmethod
@@ -39,8 +38,13 @@ class BoardRecordStorageBase(ABC):
self,
board_name: str,
user_id: str,
+ project_id: Optional[str] = None,
) -> BoardRecord:
- """Saves a board record for a specific user."""
+ """Saves a board record for a specific user, in one of their projects or in the Library.
+
+ Raises:
+ BoardRecordProjectNotFoundException: `project_id` is not one of the user's projects.
+ """
pass
@abstractmethod
@@ -57,7 +61,15 @@ class BoardRecordStorageBase(ABC):
board_id: str,
changes: BoardChanges,
) -> BoardRecord:
- """Updates a board record."""
+ """Updates a board record, deciding every rule in one transaction.
+
+ Raises:
+ BoardRecordInboxException: The board is a project's inbox and the changes rename,
+ archive, publish or move it. Only the cover may change through here.
+ BoardRecordProjectNotFoundException: The destination is not one of the owner's projects.
+ BoardRecordProjectUnavailableException: The board would be a non-private or explicitly
+ shared member of a project.
+ """
pass
@abstractmethod
diff --git a/invokeai/app/services/board_records/board_records_common.py b/invokeai/app/services/board_records/board_records_common.py
index 6a3ff50844..cbaf6680d1 100644
--- a/invokeai/app/services/board_records/board_records_common.py
+++ b/invokeai/app/services/board_records/board_records_common.py
@@ -43,6 +43,12 @@ class BoardRecord(BaseModelExcludeNull):
default=BoardVisibility.Private, description="The visibility of the board."
)
"""The visibility of the board (private, shared, or public)."""
+ project_id: Optional[str] = Field(
+ default=None, description="The id of the owner's project this board belongs to; absent for a Library board."
+ )
+ """A board lives in exactly one of its owner's projects, or in the Library when this is `None`.
+ Project boards are private and unshared. Clients must treat the field as absent-or-null: the
+ record's own `model_dump` drops `None` values, but a route's response serialization need not."""
def deserialize_board_record(board_dict: dict) -> BoardRecord:
@@ -59,6 +65,7 @@ def deserialize_board_record(board_dict: dict) -> BoardRecord:
updated_at = board_dict.get("updated_at", get_iso_timestamp())
deleted_at = board_dict.get("deleted_at", get_iso_timestamp())
archived = board_dict.get("archived", False)
+ project_id = board_dict.get("project_id")
board_visibility_raw = board_dict.get("board_visibility", BoardVisibility.Private.value)
try:
board_visibility = BoardVisibility(board_visibility_raw)
@@ -75,13 +82,14 @@ def deserialize_board_record(board_dict: dict) -> BoardRecord:
deleted_at=deleted_at,
archived=archived,
board_visibility=board_visibility,
+ project_id=project_id,
)
BOARD_NAME_MAX_LENGTH = 300
"""The longest board name the API accepts.
-Lives here because `BoardChanges` is what enforces it. A project's board takes the project's name,
+Lives here because `BoardChanges` is what enforces it. A project's inbox takes the project's name,
and project names are unbounded, so both the claim path and the migration truncate to this — they
must agree with the generic route or they would write names it then refuses to touch.
"""
@@ -94,6 +102,18 @@ class BoardChanges(BaseModel, extra="forbid"):
cover_image_name: Optional[str] = Field(default=None, description="The name of the board's new cover image.")
archived: Optional[bool] = Field(default=None, description="Whether or not the board is archived")
board_visibility: Optional[BoardVisibility] = Field(default=None, description="The visibility of the board.")
+ project_id: Optional[str] = Field(
+ default=None,
+ description=(
+ "Move the board into one of the owner's projects, or to the Library with an explicit null."
+ " Omit the field to leave the board where it is."
+ ),
+ )
+
+ @property
+ def moves_board(self) -> bool:
+ """Whether the request names a destination at all; `None` is the Library, absent is "stay"."""
+ return "project_id" in self.model_fields_set
class BoardRecordOrderBy(str, Enum, metaclass=MetaEnum):
@@ -117,10 +137,32 @@ class BoardRecordSaveException(Exception):
super().__init__(message)
-class BoardRecordProjectOwnedException(BoardRecordSaveException):
- """Raised when a generic board update would change project-owned state."""
+class BoardRecordInboxException(BoardRecordSaveException):
+ """Raised when a generic board write would rename, archive, publish, move or delete a project's inbox."""
+
+ def __init__(self, message="Board is a project's inbox"):
+ super().__init__(message)
+
+
+class BoardRecordProjectNotFoundException(BoardRecordSaveException):
+ """Raised when a board is created in or moved to a project its owner does not have.
+
+ Someone else's project reads as missing rather than forbidden: the caller has no business
+ learning that a project id it does not own exists.
+ """
+
+ def __init__(self, message="Project not found"):
+ super().__init__(message)
+
+
+class BoardRecordProjectUnavailableException(BoardRecordSaveException):
+ """Raised when a board cannot be in a project: it is shared or public, or would become so.
+
+ Boards in a project are private and unshared, so a visibility change and a move are refused
+ together whenever the result would be a non-private project board.
+ """
- def __init__(self, message="Board belongs to a project"):
+ def __init__(self, message="Boards in a project must be private"):
super().__init__(message)
diff --git a/invokeai/app/services/board_records/board_records_sqlite.py b/invokeai/app/services/board_records/board_records_sqlite.py
index 79c3fbb2e4..56953f3c87 100644
--- a/invokeai/app/services/board_records/board_records_sqlite.py
+++ b/invokeai/app/services/board_records/board_records_sqlite.py
@@ -6,10 +6,13 @@ from invokeai.app.services.board_records.board_records_common import (
BoardChanges,
BoardRecord,
BoardRecordDeleteException,
+ BoardRecordInboxException,
BoardRecordNotFoundException,
BoardRecordOrderBy,
- BoardRecordProjectOwnedException,
+ BoardRecordProjectNotFoundException,
+ BoardRecordProjectUnavailableException,
BoardRecordSaveException,
+ BoardVisibility,
deserialize_board_record,
)
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
@@ -44,29 +47,29 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
except Exception as e:
raise BoardRecordDeleteException from e
- def get_project_ids_for_boards(self, board_ids: list[str]) -> dict[str, str]:
+ def get_inbox_board_ids(self, board_ids: list[str]) -> set[str]:
if not board_ids:
- return {}
+ return set()
# Chunked because the caller is a board *listing*: an admin's `GET /boards/?all=true`
# passes every board on the install at once, and one bind parameter per board runs into
# SQLITE_MAX_VARIABLE_NUMBER — which fails the whole listing rather than degrading.
- claimed: dict[str, str] = {}
+ inboxes: set[str] = set()
with self._db.transaction() as cursor:
for start in range(0, len(board_ids), _BOARD_ID_QUERY_CHUNK):
chunk = board_ids[start : start + _BOARD_ID_QUERY_CHUNK]
placeholders = ", ".join("?" for _ in chunk)
cursor.execute(
f"""--sql
- SELECT board_id, project_id FROM projects WHERE board_id IN ({placeholders});
+ SELECT board_id FROM projects WHERE board_id IN ({placeholders});
""",
tuple(chunk),
)
- claimed.update({row[0]: row[1] for row in cursor.fetchall()})
- return claimed
+ inboxes.update(row[0] for row in cursor.fetchall())
+ return inboxes
- def get_with_project_id(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:
- """The board and the project that claims it, in one query.
+ def get_with_inbox_project(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:
+ """The board and the project whose inbox it is, in one query.
`get_dto` needs both and is called on every authorization check, so asking for them
separately doubled the round trips — and the transactions, which take a re-entrant lock —
@@ -76,7 +79,7 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
try:
cursor.execute(
"""--sql
- SELECT boards.*, projects.project_id AS claimed_by_project_id
+ SELECT boards.*, projects.project_id AS inbox_of_project_id
FROM boards
LEFT JOIN projects ON projects.board_id = boards.board_id
WHERE boards.board_id = ?;
@@ -89,24 +92,41 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
if result is None:
raise BoardRecordNotFoundException
row = dict(result)
- project_id = row.pop("claimed_by_project_id", None)
- return BoardRecord(**row), project_id
+ inbox_of_project_id = row.pop("inbox_of_project_id", None)
+ return BoardRecord(**row), inbox_of_project_id
def save(
self,
board_name: str,
user_id: str,
+ project_id: Optional[str] = None,
) -> BoardRecord:
with self._db.transaction() as cursor:
try:
board_id = uuid_string()
- cursor.execute(
- """--sql
- INSERT OR IGNORE INTO boards (board_id, board_name, user_id)
- VALUES (?, ?, ?);
- """,
- (board_id, board_name, user_id),
- )
+ if project_id is None:
+ cursor.execute(
+ """--sql
+ INSERT OR IGNORE INTO boards (board_id, board_name, user_id)
+ VALUES (?, ?, ?);
+ """,
+ (board_id, board_name, user_id),
+ )
+ else:
+ # The project lookup is the insert's own source row, so a project deleted
+ # between a caller's check and this statement yields no board rather than a
+ # member of nothing. Project ids are unique per user only, hence both keys.
+ cursor.execute(
+ """--sql
+ INSERT INTO boards (board_id, board_name, user_id, project_id)
+ SELECT ?, ?, projects.user_id, projects.project_id
+ FROM projects
+ WHERE projects.user_id = ? AND projects.project_id = ?;
+ """,
+ (board_id, board_name, user_id, project_id),
+ )
+ if cursor.rowcount == 0:
+ raise BoardRecordProjectNotFoundException
except sqlite3.Error as e:
raise BoardRecordSaveException from e
return self.get(board_id)
@@ -167,28 +187,65 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
board_id: str,
changes: BoardChanges,
) -> BoardRecord:
+ # The rules are decided and applied inside one transaction. The connection is shared and
+ # `transaction()` holds its lock for the whole block, so a project claiming the board, or
+ # a share landing on it, commits either before this read or after this write — there is no
+ # window in which a stale router-side DTO can let an inbox be renamed or a shared board
+ # moved into a project. The one check that is not a read is the destination project's
+ # existence, which the UPDATE guards itself, so a project deleted mid-request leaves the
+ # board where it was rather than a member of nothing.
with self._db.transaction() as cursor:
try:
- changes_project_owned_state = (
+ cursor.execute(
+ """--sql
+ SELECT boards.board_visibility,
+ boards.project_id,
+ EXISTS (SELECT 1 FROM projects WHERE projects.board_id = boards.board_id) AS is_inbox,
+ EXISTS (SELECT 1 FROM shared_boards WHERE shared_boards.board_id = boards.board_id)
+ AS is_shared
+ FROM boards
+ WHERE board_id = ?;
+ """,
+ (board_id,),
+ )
+ row = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ if row is None:
+ raise BoardRecordNotFoundException
+
+ changes_inbox_state = (
changes.board_name is not None
or changes.archived is not None
or changes.board_visibility is not None
+ or changes.moves_board
)
- # One conditional write, not a read followed by a write. A project claim racing
- # this statement either commits first and makes rowcount zero, or waits until this
- # update has committed; there is no stale DTO window in which project-owned state
- # can be renamed, archived or published.
+ if row["is_inbox"] and changes_inbox_state:
+ raise BoardRecordInboxException
+
+ next_project_id = changes.project_id if changes.moves_board else row["project_id"]
+ next_visibility = (
+ changes.board_visibility.value if changes.board_visibility is not None else row["board_visibility"]
+ )
+ if next_project_id is not None and (
+ next_visibility != BoardVisibility.Private.value or row["is_shared"]
+ ):
+ raise BoardRecordProjectUnavailableException
+
+ destination_project_id = changes.project_id if changes.moves_board else None
cursor.execute(
"""--sql
UPDATE boards
SET board_name = COALESCE(?, board_name),
cover_image_name = COALESCE(?, cover_image_name),
archived = COALESCE(?, archived),
- board_visibility = COALESCE(?, board_visibility)
+ board_visibility = COALESCE(?, board_visibility),
+ project_id = CASE WHEN ? THEN ? ELSE project_id END
WHERE board_id = ?
AND (
- ? = FALSE
- OR NOT EXISTS (SELECT 1 FROM projects WHERE projects.board_id = boards.board_id)
+ ? IS NULL
+ OR EXISTS (
+ SELECT 1 FROM projects
+ WHERE projects.user_id = boards.user_id AND projects.project_id = ?
+ )
);
""",
(
@@ -196,16 +253,15 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):
changes.cover_image_name,
changes.archived,
changes.board_visibility.value if changes.board_visibility is not None else None,
+ changes.moves_board,
+ changes.project_id,
board_id,
- changes_project_owned_state,
+ destination_project_id,
+ destination_project_id,
),
)
-
if cursor.rowcount == 0:
- cursor.execute("SELECT 1 FROM boards WHERE board_id = ?;", (board_id,))
- if cursor.fetchone() is None:
- raise BoardRecordNotFoundException
- raise BoardRecordProjectOwnedException
+ raise BoardRecordProjectNotFoundException
except sqlite3.Error as e:
raise BoardRecordSaveException from e
diff --git a/invokeai/app/services/boards/boards_base.py b/invokeai/app/services/boards/boards_base.py
index 4f1d36fb8f..cf25bafc1e 100644
--- a/invokeai/app/services/boards/boards_base.py
+++ b/invokeai/app/services/boards/boards_base.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from typing import Optional
from invokeai.app.services.board_records.board_records_common import BoardChanges, BoardRecordOrderBy
from invokeai.app.services.boards.boards_common import BoardDTO
@@ -14,8 +15,9 @@ class BoardServiceABC(ABC):
self,
board_name: str,
user_id: str,
+ project_id: Optional[str] = None,
) -> BoardDTO:
- """Creates a board for a specific user."""
+ """Creates a board for a specific user, in one of their projects or in the Library."""
pass
@abstractmethod
@@ -40,7 +42,7 @@ class BoardServiceABC(ABC):
self,
board_id: str,
) -> bool:
- """Delete a board only if no project owns it. Returns whether it was deleted.
+ """Delete a board unless it is a project's inbox. Returns whether it was deleted.
The only deletion there is. An unconditional `delete` used to sit beside this one with no
callers, which made "a project's board cannot be deleted out from under it" true by
diff --git a/invokeai/app/services/boards/boards_common.py b/invokeai/app/services/boards/boards_common.py
index 2e1babc6a2..7a1ceda82e 100644
--- a/invokeai/app/services/boards/boards_common.py
+++ b/invokeai/app/services/boards/boards_common.py
@@ -28,13 +28,14 @@ class BoardDTO(BoardRecord):
field lets clients split the total across the Media/Assets views."""
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"."""
+ is_inbox: bool = Field(
+ default=False, description="Whether this board is its project's inbox, which only the project APIs may change."
+ )
+ """The inbox is the one board every project has: it takes the project's name, cannot be moved,
+ renamed, archived or deleted through the generic board routes, and goes with the project when
+ the project is deleted. Derived by joining `projects.board_id`, never stored on `boards`; the
+ board's membership (`project_id`) is the stored fact, and an inbox is always a member of its
+ own project."""
def board_record_to_dto(
@@ -46,7 +47,7 @@ def board_record_to_dto(
cover_video_name: Optional[str] = None,
video_count: int = 0,
asset_video_count: int = 0,
- project_id: Optional[str] = None,
+ is_inbox: bool = False,
) -> BoardDTO:
"""Converts a board record to a board DTO."""
return BoardDTO(
@@ -58,5 +59,5 @@ def board_record_to_dto(
asset_count=asset_count,
asset_video_count=asset_video_count,
owner_username=owner_username,
- project_id=project_id,
+ is_inbox=is_inbox,
)
diff --git a/invokeai/app/services/boards/boards_default.py b/invokeai/app/services/boards/boards_default.py
index d8b6a18b69..9b0b680494 100644
--- a/invokeai/app/services/boards/boards_default.py
+++ b/invokeai/app/services/boards/boards_default.py
@@ -51,15 +51,16 @@ class BoardService(BoardServiceABC):
self,
board_name: str,
user_id: str,
+ project_id: Optional[str] = None,
) -> BoardDTO:
- board_record = self.__invoker.services.board_records.save(board_name, user_id)
+ board_record = self.__invoker.services.board_records.save(board_name, user_id, project_id)
return board_record_to_dto(board_record, None, 0, 0)
def get_dto(self, board_id: str) -> BoardDTO:
- # One query for the record and its claiming project. `get_dto` is what every authorization
- # check resolves through, so a second lookup here is a second transaction — and the lock it
- # takes — on the most-travelled read in the API.
- board_record, project_id = self.__invoker.services.board_records.get_with_project_id(board_id)
+ # One query for the record and the project it is the inbox of. `get_dto` is what every
+ # authorization check resolves through, so a second lookup here is a second transaction —
+ # and the lock it takes — on the most-travelled read in the API.
+ board_record, inbox_of_project_id = self.__invoker.services.board_records.get_with_inbox_project(board_id)
cover_image_name, cover_video_name = self._resolve_cover(board_record.board_id)
image_count, video_count, asset_count, asset_video_count = self._get_counts(board_id)
return board_record_to_dto(
@@ -70,7 +71,7 @@ class BoardService(BoardServiceABC):
cover_video_name=cover_video_name,
video_count=video_count,
asset_video_count=asset_video_count,
- project_id=project_id,
+ is_inbox=inbox_of_project_id is not None,
)
def update(
@@ -80,8 +81,8 @@ class BoardService(BoardServiceABC):
) -> BoardDTO:
self.__invoker.services.board_records.update(board_id, changes)
# Re-read through `get_dto` rather than shaping the update's own return: it is the one
- # place that resolves cover, counts and claiming project together, and an update that
- # dropped `project_id` would tell the gallery a project's board is an ordinary one.
+ # place that resolves cover, counts and the inbox flag together, and an update that
+ # dropped the flag would tell the gallery a project's inbox is an ordinary board.
return self.get_dto(board_id)
def delete_if_unclaimed(self, board_id: str) -> bool:
@@ -128,7 +129,7 @@ class BoardService(BoardServiceABC):
summaries = self.__invoker.services.gallery.get_board_media_summaries(
[record.board_id for record in board_records]
)
- project_ids = self.__invoker.services.board_records.get_project_ids_for_boards(
+ inbox_board_ids = self.__invoker.services.board_records.get_inbox_board_ids(
[record.board_id for record in board_records]
)
owners = (
@@ -153,7 +154,7 @@ class BoardService(BoardServiceABC):
cover_video_name=summary.cover_video_name,
video_count=summary.video_count,
asset_video_count=summary.asset_video_count,
- project_id=project_ids.get(r.board_id),
+ is_inbox=r.board_id in inbox_board_ids,
)
)
diff --git a/invokeai/app/services/project_records/project_records_base.py b/invokeai/app/services/project_records/project_records_base.py
index eb2db222cd..1f4a7db10a 100644
--- a/invokeai/app/services/project_records/project_records_base.py
+++ b/invokeai/app/services/project_records/project_records_base.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from typing import Any
+from typing import Any, Literal
from invokeai.app.services.project_records.project_records_common import (
DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,
@@ -16,9 +16,11 @@ class ProjectRecordsStorageBase(ABC):
another user's projects. Saves use optimistic concurrency via the
project'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.
+ Every project has exactly one inbox: a private board that this storage alone
+ creates, renames and deletes. Its name tracks the project's name; the two
+ always commit together. The project's other boards are ordinary boards whose
+ `project_id` names it; they are created and moved through the board service
+ and only leave with the project, released to the Library or deleted.
"""
@abstractmethod
@@ -32,16 +34,17 @@ class ProjectRecordsStorageBase(ABC):
minimum_canvas_schema_version: int = DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,
max_canvas_schema_version: int = DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,
) -> ProjectRecordDTO:
- """Create a project for the user, with a board.
+ """Create a project for the user, with its inbox.
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.
+ board_id: An existing unclaimed private Library board to adopt as the inbox, 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.
minimum_canvas_schema_version: Compatibility floor stored with the project.
max_canvas_schema_version: Newest canvas schema understood by the caller.
@@ -89,7 +92,7 @@ class ProjectRecordsStorageBase(ABC):
minimum_canvas_schema_version: int | None = None,
max_canvas_schema_version: int = DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,
) -> ProjectRecordDTO:
- """Save a project if the caller's revision is current, renaming its board to match.
+ """Save a project if the caller's revision is current, renaming its inbox to match.
A save that loses the revision race renames nothing.
@@ -104,17 +107,18 @@ class ProjectRecordsStorageBase(ABC):
pass
@abstractmethod
- def delete(self, user_id: str, project_id: str) -> None:
- """Delete one of the user's projects and its board.
+ def delete(self, user_id: str, project_id: str, boards: Literal["release", "delete"] = "release") -> None:
+ """Delete one of the user's projects and its inbox, in one transaction.
- Idempotent: deleting a missing project is a no-op. The board's media is not deleted — losing
- the board returns it to Uncategorized.
+ Idempotent: deleting a missing project is a no-op. The project's other boards are either
+ released to the Library, where they keep their media, or deleted with the project. No media
+ is ever deleted here — losing a board returns its items 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.
+ """Enumerate everything on the project's inbox 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
@@ -127,7 +131,7 @@ class ProjectRecordsStorageBase(ABC):
@abstractmethod
def get_board_id(self, user_id: str, project_id: str) -> str:
- """Get the project's board id without loading its document.
+ """Get the project's inbox board id without loading its document.
Raises:
ProjectRecordNotFoundError: No such project for this user.
diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.py
index 4f8ea95f8d..a8c81c34b2 100644
--- a/invokeai/app/services/project_records/project_records_sqlite.py
+++ b/invokeai/app/services/project_records/project_records_sqlite.py
@@ -1,7 +1,7 @@
import json
import sqlite3
import uuid
-from typing import Any, Optional
+from typing import Any, Literal, Optional
from invokeai.app.services.board_records.board_records_common import BOARD_NAME_MAX_LENGTH, BoardVisibility
from invokeai.app.services.image_records.image_records_common import ASSETS_CATEGORIES, IMAGE_CATEGORIES
@@ -58,7 +58,7 @@ def _require_project_document_size(actual_bytes: int) -> None:
class ProjectRecordsSqlite(ProjectRecordsStorageBase):
"""SQLite implementation of per-user project document storage.
- A project and its board are one unit: every write touching both happens inside a single
+ A project and its inbox are one unit: every write touching both happens inside a single
`self._db.transaction()`.
That transaction is why this class talks to `boards` in raw SQL rather than through
@@ -97,7 +97,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
try:
with self._db.transaction() as cursor:
if board_id is None:
- resolved_board_id = self._insert_board(cursor, user_id=user_id, name=name)
+ resolved_board_id = self._insert_board(cursor, user_id=user_id, name=name, project_id=project_id)
else:
self._claim_board(cursor, user_id=user_id, board_id=board_id, name=name, project_id=project_id)
resolved_board_id = board_id
@@ -265,7 +265,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
if cursor.rowcount == 0:
# Another SQLite connection can win after the read above but before this
# compare-and-swap. Re-read inside the transaction so the refusal reports the
- # actual winning revision and never renames the board.
+ # actual winning revision and never renames the inbox.
cursor.execute(
"""--sql
SELECT revision FROM projects
@@ -339,13 +339,32 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
client_maximum_version=client_maximum_version,
)
- def delete(self, user_id: str, project_id: str) -> None:
+ def delete(self, user_id: str, project_id: str, boards: Literal["release", "delete"] = "release") -> None:
with self._db.transaction() as cursor:
row = self._board_row(cursor, user_id=user_id, project_id=project_id)
if row is None:
return
+ # The project's other boards first, while the project row still identifies them. Both
+ # keys: project ids are unique per user only. Deleting a board cascades its memberships,
+ # returning the media to Uncategorized; the image and video records and their files are
+ # untouched either way.
+ if boards == "delete":
+ cursor.execute(
+ """--sql
+ DELETE FROM boards WHERE user_id = ? AND project_id = ? AND board_id != ?;
+ """,
+ (user_id, project_id, row[0]),
+ )
+ else:
+ cursor.execute(
+ """--sql
+ UPDATE boards SET project_id = NULL WHERE user_id = ? AND project_id = ? AND board_id != ?;
+ """,
+ (user_id, project_id, row[0]),
+ )
+
cursor.execute(
"""--sql
DELETE FROM projects
@@ -354,9 +373,8 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
(user_id, project_id),
)
delete_media_references(cursor, owner_kind="project", user_id=user_id, owner_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.
+ # Only after the project is gone: the inbox FK is RESTRICT, so a claimed board cannot be
+ # deleted.
cursor.execute(
"""--sql
DELETE FROM boards WHERE board_id = ?;
@@ -429,7 +447,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
return row[0]
def _board_row(self, cursor: sqlite3.Cursor, *, user_id: str, project_id: str) -> Optional[sqlite3.Row]:
- """The project's board row, or `None` when this user has no such project.
+ """The project's inbox row, or `None` when this user has no such project.
Cursor-taking rather than transaction-opening, so callers stay in charge of the unit of work
this class's docstring describes.
@@ -443,24 +461,29 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
return cursor.fetchone()
- def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str) -> str:
+ def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str, project_id: str) -> str:
board_id = uuid_string()
cursor.execute(
"""--sql
- INSERT INTO boards (board_id, board_name, user_id, board_visibility, archived)
- VALUES (?, ?, ?, ?, FALSE);
+ INSERT INTO boards (board_id, board_name, user_id, board_visibility, archived, project_id)
+ VALUES (?, ?, ?, ?, FALSE, ?);
""",
- (board_id, name[:BOARD_NAME_MAX_LENGTH], user_id, BoardVisibility.Private.value),
+ (board_id, name[:BOARD_NAME_MAX_LENGTH], user_id, BoardVisibility.Private.value, project_id),
)
return board_id
def _claim_board(self, cursor: sqlite3.Cursor, *, user_id: str, board_id: str, name: str, project_id: str) -> None:
- """Take ownership of an existing private board, or explain why it cannot be taken.
+ """Make an existing private Library board the new project's inbox, or explain why not.
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.
+ A board that belongs to another project is refused as unavailable: an inbox is created with
+ its project, and adopting a member would silently demote whatever board that project already
+ had. Membership of the project being created is excluded for the same reason the claimed
+ check is — a repeated create made it a member the first time round.
+
The project being created is excluded from the "already claimed" test, so a client that
re-sends a create it never got an answer for reaches the project insert and is refused there,
as `ProjectRecordExistsError` — the truth. Without the exclusion it would be told its board
@@ -478,28 +501,29 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
EXISTS(
SELECT 1 FROM projects p
WHERE p.board_id = b.board_id AND NOT (p.user_id = ? AND p.project_id = ?)
- )
+ ),
+ b.project_id IS NOT NULL AND b.project_id != ?
FROM boards b
WHERE b.board_id = ?;
""",
- (user_id, project_id, board_id),
+ (user_id, project_id, project_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]:
+ if row[1] != BoardVisibility.Private.value or row[2] or row[3] or row[4]:
raise ProjectBoardUnavailableError(board_id)
- # Un-archived as well as renamed. A project's board takes its archived state from the
- # project, and `PATCH /boards/{id}` refuses to set it on a claimed board — so a board that
+ # Un-archived as well as renamed. A project's inbox takes its archived state from the
+ # project, and `PATCH /boards/{id}` refuses to set it on an inbox — so a board that
# arrived archived would be invisible in every listing with no API left to fix it.
cursor.execute(
"""--sql
- UPDATE boards SET board_name = ?, archived = FALSE WHERE board_id = ?;
+ UPDATE boards SET board_name = ?, archived = FALSE, project_id = ? WHERE board_id = ?;
""",
- (name[:BOARD_NAME_MAX_LENGTH], board_id),
+ (name[:BOARD_NAME_MAX_LENGTH], project_id, board_id),
)
@staticmethod
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_08_add_board_project_membership.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_08_add_board_project_membership.py
new file mode 100644
index 0000000000..e70fd3148f
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_08_add_board_project_membership.py
@@ -0,0 +1,52 @@
+"""Let a board belong to a project, so a project can hold more than its inbox.
+
+`boards.project_id` says which of its owner's projects a board lives in; `NULL` is the Library,
+the tier every project can see. `projects.board_id` keeps its job of naming the one board that is
+the project's inbox, which the database already guarantees exists exactly once and cannot be
+deleted out from under the project.
+
+Membership is a plain nullable column rather than a foreign key, like `boards.user_id` before it.
+`projects` is keyed by `(user_id, project_id)`, so a foreign key would have to be composite and
+therefore a table constraint, which SQLite can only add by rebuilding `boards` — and rebuilding a
+table that `board_images`, `board_videos`, `shared_boards` and `projects` all reference, with
+foreign keys enforced, runs every one of those cascades. The services keep membership consistent
+instead, and the backfill below makes every inbox a member of its own project. Deleting an account
+cascades its projects but, as before, not its boards (`boards.user_id` has no foreign key either), so
+those orphans keep a `project_id` nothing resolves; readers treat an unresolvable membership as any
+other board, and `is_inbox` is derived from `projects`, so it turns false and admins can delete them.
+"""
+
+import sqlite3
+
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+
+
+class AddBoardProjectMembershipCallback:
+ def __call__(self, cursor: sqlite3.Cursor) -> None:
+ cursor.execute("PRAGMA table_info(boards);")
+ if not any(row[1] == "project_id" for row in cursor.fetchall()):
+ cursor.execute("ALTER TABLE boards ADD COLUMN project_id TEXT;")
+
+ cursor.execute(
+ """--sql
+ CREATE INDEX IF NOT EXISTS idx_boards_project_id ON boards(project_id);
+ """
+ )
+ # Every inbox is a member of its own project. Rows that already say so are left alone, so
+ # a board the user has since moved is not dragged back.
+ cursor.execute(
+ """--sql
+ UPDATE boards
+ SET project_id = (SELECT projects.project_id FROM projects WHERE projects.board_id = boards.board_id)
+ WHERE project_id IS NULL
+ AND EXISTS (SELECT 1 FROM projects WHERE projects.board_id = boards.board_id);
+ """
+ )
+
+
+def build_migration() -> Migration:
+ return Migration(
+ id="2026_10_08_add_board_project_membership",
+ depends_on="2026_08_27_add_project_canvas_schema_floor",
+ callback=AddBoardProjectMembershipCallback(),
+ )
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index a3663cf5f7..b2c7190350 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -10280,7 +10280,7 @@
"post": {
"tags": ["boards"],
"summary": "Create Board",
- "description": "Creates a board for the current user",
+ "description": "Creates a board for the current user, in one of their projects or in the Library",
"operationId": "create_board",
"security": [
{
@@ -10299,6 +10299,24 @@
"title": "Board Name"
},
"description": "The name of the board to create"
+ },
+ {
+ "name": "project_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "One of the current user's projects to create the board in; omit for the Library",
+ "title": "Project Id"
+ },
+ "description": "One of the current user's projects to create the board in; omit for the Library"
}
],
"responses": {
@@ -10509,7 +10527,7 @@
"patch": {
"tags": ["boards"],
"summary": "Update Board",
- "description": "Updates a board (user must have access to it)",
+ "description": "Updates a board (user must have access to it).\n\nA project's inbox takes its name, archived state and visibility from the project and cannot be\nmoved, so those changes are refused for it \u2014 for admins too; its cover is still fair game. A\nboard in a project is private and unshared, so a move into a project, or a visibility change on\na member, is refused when the result would be otherwise. The storage decides all of this in one\ntransaction; the DTO read here is only for the ownership check.",
"operationId": "update_board",
"security": [
{
@@ -15605,7 +15623,7 @@
"post": {
"tags": ["projects"],
"summary": "Create Project",
- "description": "Creates a project, and the private board it owns, for the current user.",
+ "description": "Creates a project, and the private inbox board it owns, for the current user.",
"operationId": "create_project",
"requestBody": {
"content": {
@@ -15767,7 +15785,7 @@
"delete": {
"tags": ["projects"],
"summary": "Delete Project",
- "description": "Deletes one of the current user's projects, and the board it owns, in one transaction.\n\nIdempotent. The media survives: deleting the board drops its memberships, so the images and\nvideos on it return to Uncategorized, exactly as they would if the board were deleted without\n`include_images`. There is deliberately no option to take them with it \u2014 a project is a\nworkspace, and emptying someone's gallery is not what deleting one should be able to mean.\nNothing is reported back for the same reason: nothing was destroyed to report.",
+ "description": "Deletes one of the current user's projects and its inbox, in one transaction.\n\nIdempotent. The media survives either way: deleting a board drops its memberships, so the images\nand videos on it return to Uncategorized, exactly as they would if the board were deleted without\n`include_images`. There is deliberately no option to take them with it \u2014 a project is a\nworkspace, and emptying someone's gallery is not what deleting one should be able to mean.\nNothing is reported back for the same reason: nothing was destroyed to report.",
"operationId": "delete_project",
"security": [
{
@@ -15785,6 +15803,19 @@
"title": "Project Id"
},
"description": "The id of the project to delete"
+ },
+ {
+ "name": "boards",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "enum": ["release", "delete"],
+ "type": "string",
+ "description": "What becomes of the project's boards other than its inbox: released to the Library with their media, or deleted so their media returns to Uncategorized",
+ "default": "release",
+ "title": "Boards"
+ },
+ "description": "What becomes of the project's boards other than its inbox: released to the Library with their media, or deleted so their media returns to Uncategorized"
}
],
"responses": {
@@ -15808,7 +15839,7 @@
"get": {
"tags": ["projects"],
"summary": "Get Project Board Snapshot",
- "description": "Lists everything on the project's board that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway. It is still bounded,\nbecause the answer is built entirely in memory and any client with a project id can ask for it;\na board past the ceiling is one an export could not have packed either, so it is refused as a\n413 rather than paged.",
+ "description": "Lists everything on the project's inbox that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway. It is still bounded,\nbecause the answer is built entirely in memory and any client with a project id can ask for it;\na board past the ceiling is one an export could not have packed either, so it is refused as a\n413 rather than paged.",
"operationId": "get_project_board_snapshot",
"security": [
{
@@ -20784,6 +20815,18 @@
}
],
"description": "The visibility of the board."
+ },
+ "project_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id",
+ "description": "Move the board into one of the owner's projects, or to the Library with an explicit null. Omit the field to leave the board where it is."
}
},
"additionalProperties": false,
@@ -20871,6 +20914,18 @@
"description": "The visibility of the board.",
"default": "private"
},
+ "project_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id",
+ "description": "The id of the owner's project this board belongs to; absent for a Library board."
+ },
"cover_video_name": {
"anyOf": [
{
@@ -20917,17 +20972,11 @@
"title": "Owner Username",
"description": "The username of the board owner (for admin view)."
},
- "project_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Project Id",
- "description": "The id of the project that owns this board, if any."
+ "is_inbox": {
+ "type": "boolean",
+ "title": "Is Inbox",
+ "description": "Whether this board is its project's inbox, which only the project APIs may change.",
+ "default": false
}
},
"type": "object",
@@ -90109,7 +90158,7 @@
}
],
"title": "Board Id",
- "description": "An existing unclaimed private board for the project to adopt, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import."
+ "description": "An existing unclaimed private Library board for the project to adopt as its inbox, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import."
},
"name": {
"type": "string",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 4c601f571f..986c443b9a 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -2418,7 +2418,7 @@ export type paths = {
put?: never;
/**
* Create Board
- * @description Creates a board for the current user
+ * @description Creates a board for the current user, in one of their projects or in the Library
*/
post: operations["create_board"];
delete?: never;
@@ -2450,7 +2450,13 @@ export type paths = {
head?: never;
/**
* Update Board
- * @description Updates a board (user must have access to it)
+ * @description Updates a board (user must have access to it).
+ *
+ * A project's inbox takes its name, archived state and visibility from the project and cannot be
+ * moved, so those changes are refused for it — for admins too; its cover is still fair game. A
+ * board in a project is private and unshared, so a move into a project, or a visibility change on
+ * a member, is refused when the result would be otherwise. The storage decides all of this in one
+ * transaction; the DTO read here is only for the ownership check.
*/
patch: operations["update_board"];
trace?: never;
@@ -4017,7 +4023,7 @@ export type paths = {
put?: never;
/**
* Create Project
- * @description Creates a project, and the private board it owns, for the current user.
+ * @description Creates a project, and the private inbox board it owns, for the current user.
*/
post: operations["create_project"];
delete?: never;
@@ -4046,10 +4052,10 @@ export type paths = {
post?: never;
/**
* Delete Project
- * @description Deletes one of the current user's projects, and the board it owns, in one transaction.
+ * @description Deletes one of the current user's projects and its inbox, in one transaction.
*
- * Idempotent. The media survives: deleting the board drops its memberships, so the images and
- * videos on it return to Uncategorized, exactly as they would if the board were deleted without
+ * Idempotent. The media survives either way: deleting a board drops its memberships, so the images
+ * and videos on it return to Uncategorized, exactly as they would if the board were deleted without
* `include_images`. There is deliberately no option to take them with it — a project is a
* workspace, and emptying someone's gallery is not what deleting one should be able to mean.
* Nothing is reported back for the same reason: nothing was destroyed to report.
@@ -4069,7 +4075,7 @@ export type paths = {
};
/**
* Get Project Board Snapshot
- * @description Lists everything on the project's board that the gallery would show.
+ * @description Lists everything on the project's inbox 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. It is still bounded,
@@ -6143,6 +6149,11 @@ export type components = {
archived?: boolean | null;
/** @description The visibility of the board. */
board_visibility?: components["schemas"]["BoardVisibility"] | null;
+ /**
+ * Project Id
+ * @description Move the board into one of the owner's projects, or to the Library with an explicit null. Omit the field to leave the board where it is.
+ */
+ project_id?: string | null;
};
/**
* BoardDTO
@@ -6194,6 +6205,11 @@ export type components = {
* @default private
*/
board_visibility?: components["schemas"]["BoardVisibility"];
+ /**
+ * Project Id
+ * @description The id of the owner's project this board belongs to; absent for a Library board.
+ */
+ project_id?: string | null;
/**
* Cover Video Name
* @description The name of the board's cover video, when the most recent item is a video.
@@ -6227,10 +6243,11 @@ export type components = {
*/
owner_username?: string | null;
/**
- * Project Id
- * @description The id of the project that owns this board, if any.
+ * Is Inbox
+ * @description Whether this board is its project's inbox, which only the project APIs may change.
+ * @default false
*/
- project_id?: string | null;
+ is_inbox?: boolean;
};
/**
* BoardField
@@ -38541,7 +38558,7 @@ export type components = {
project_id?: string | null;
/**
* Board Id
- * @description An existing unclaimed private board for the project to adopt, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import.
+ * @description An existing unclaimed private Library board for the project to adopt as its inbox, renamed to match. Omit to create one. Restoring a project uploads its media into such a board first, so that creating the project is the single commit point for an import.
*/
board_id?: string | null;
/**
@@ -56576,6 +56593,8 @@ export interface operations {
query: {
/** @description The name of the board to create */
board_name: string;
+ /** @description One of the current user's projects to create the board in; omit for the Library */
+ project_id?: string | null;
};
header?: never;
path?: never;
@@ -59936,7 +59955,10 @@ export interface operations {
};
delete_project: {
parameters: {
- query?: never;
+ query?: {
+ /** @description What becomes of the project's boards other than its inbox: released to the Library with their media, or deleted so their media returns to Uncategorized */
+ boards?: "release" | "delete";
+ };
header?: never;
path: {
/** @description The id of the project to delete */
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 50088a74d8..b81bde35dd 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -593,7 +593,7 @@ const boardDto = (state, board) => {
cover_image_name: cover?.kind === 'image' ? cover.name : null,
cover_video_name: cover?.kind === 'video' ? cover.name : null,
image_count: images.filter((image) => image.image_category === 'general').length,
- // The backend's BoardRecord excludes nulls, so an unclaimed board omits the key entirely.
+ is_inbox: projectId !== null,
...(projectId === null ? {} : { project_id: projectId }),
video_count: videos.length,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
index 07ce251c7c..9ed35cb641 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts
@@ -12,6 +12,7 @@ const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
imageCount: 50,
kind: 'board',
name: 'dogs',
+ isInbox: false,
projectId: null,
videoCount: 4,
...overrides,
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
index 94732a0916..bb229bb7f0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
@@ -60,10 +60,12 @@ export interface GalleryBoard {
createdAt?: string | null;
ownerName?: string | null;
/**
- * Project ownership controls naming and deletion; generic board actions must exclude all project-owned boards.
- * Null denotes an ordinary board.
+ * The project this board belongs to; null is the Library. Members are ordinary boards; only the inbox is
+ * managed through its project.
*/
projectId: string | null;
+ /** Its project's inbox: named after the project and only renamed, archived, moved or deleted through it. */
+ isInbox: boolean;
}
export interface GalleryImage extends GeneratedImageContract {
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index f1bd5d043f..4335e75f9b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -55,11 +55,10 @@ interface BackendBoardDTO {
created_at?: string | null;
/** Board owner's display name; populated only for admins on multi-user backends. */
owner_username?: string | null;
- /**
- * The project that owns this board. The backend's board DTO excludes nulls, so
- * an ordinary board omits the key entirely rather than sending `null`.
- */
+ /** The project this board belongs to; absent or null for a Library board. */
project_id?: string | null;
+ /** Its project's inbox, which only the project routes may rename, archive, move or delete. */
+ is_inbox?: boolean;
}
/**
@@ -180,6 +179,7 @@ const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({
createdAt: board.created_at ?? null,
id: board.board_id,
imageCount: board.image_count,
+ isInbox: board.is_inbox ?? false,
kind: 'board',
name: board.board_name,
ownerName: board.owner_username ?? null,
@@ -365,6 +365,7 @@ export const listGalleryBoards = async ({
assetVideoCount: uncategorizedAssetVideoCount,
id: 'none',
imageCount: uncategorizedImageCount,
+ isInbox: false,
kind: 'uncategorized',
// Synthesized, not stored: `kind` is the durable fact and the UI resolves
// the label from it, so no untranslatable name crosses the transport.
@@ -402,6 +403,7 @@ export const listGalleryDateBoards = async (signal?: AbortSignal): Promise<Galle
coverVideoName: board.cover_video_name,
id: board.virtual_board_id,
imageCount: board.image_count,
+ isInbox: false,
kind: 'date',
name: board.board_name,
// A virtual board is nobody's project board.
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
index 4879ac4926..0905fdb119 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
@@ -479,6 +479,7 @@ const createBoard = (id: string, overrides: Partial<GalleryBoard> = {}): Gallery
imageCount: 1,
kind: 'board',
name: `Board ${id}`,
+ isInbox: false,
projectId: null,
videoCount: 0,
...overrides,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
index 0af55503bf..260349c88b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
@@ -43,6 +43,7 @@ const board = {
imageCount: 2,
kind: 'board',
name: 'Board 1',
+ isInbox: false,
projectId: null,
videoCount: 1,
} as const;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 92fd618e61..99f5e80991 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -44,10 +44,10 @@ export const GalleryBoardMenu = ({
targetRef.current = target;
const board = target?.board ?? null;
- // Protect every project-owned board from rename/archive/delete. Also check the active project's board ID because
- // omitted project_id must not expose invalid actions.
+ // An inbox is renamed, archived and deleted through its project; every other real board is the user's to manage.
+ // The active project's own inbox is also checked by id, because a draft project's inbox can predate the listing.
const isManagedBoard =
- board !== null && board.kind === 'board' && board.projectId === null && board.id !== gallery.projectBoardId;
+ board !== null && board.kind === 'board' && !board.isInbox && board.id !== gallery.projectBoardId;
const positioning = useMemo(
() => ({
getAnchorRect: () => {
@@ -138,7 +138,7 @@ export const GalleryBoardMenu = ({
<Menu.Positioner>
{board && (
<MenuContent minW="12rem">
- {board.projectId !== null && (
+ {board.isInbox && board.projectId !== null && (
<>
<BoardExportProjectMenuItem board={board} />
<Menu.Separator />
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
index 9b374523e9..6aa15e895c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx
@@ -166,7 +166,7 @@ export const GalleryBoardRow = ({
</Badge>
</Tooltip>
) : null}
- {board.projectId !== null ? (
+ {board.isInbox ? (
<Badge colorPalette={isSelected ? undefined : 'accent'} flexShrink={0} variant="subtle">
{t('common.project')}
</Badge>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
index b81d72474d..23bd6fdfa0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx
@@ -55,6 +55,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'
assetVideoCount: 0,
imageCount: 50,
kind: 'board',
+ isInbox: false,
projectId: null,
videoCount: 0,
...overrides,
@@ -176,8 +177,10 @@ describe('GalleryBoardsPanel', () => {
});
/** Badges and protection follow every board's owner; only hoisting depends on the active project. */
- it('marks every project-owned board with a Project badge', async () => {
- const ownedBoards = boards.map((board) => (board.id === 'cats' ? { ...board, projectId: 'p1' } : board));
+ it('marks a project inbox with a Project badge', async () => {
+ const ownedBoards = boards.map((board) =>
+ board.id === 'cats' ? { ...board, isInbox: true, projectId: 'p1' } : board
+ );
await renderPanel({ ...createGallery(), boards: ownedBoards, projectBoardId: 'cats' } as GalleryStateView);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index a6113c5016..1969fb2e32 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -221,6 +221,7 @@ const board = {
imageCount: 3,
kind: 'board',
name: 'Board A',
+ isInbox: false,
projectId: null,
videoCount: 1,
} as const;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
index dd423be68c..4900486561 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx
@@ -43,6 +43,7 @@ const board: GalleryBoard = {
imageCount: 50,
kind: 'board',
name: 'dogs',
+ isInbox: false,
projectId: null,
videoCount: 0,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
index 32cbe4be99..6b2e8dbe99 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx
@@ -66,6 +66,7 @@ const createBoard = (id: string, name: string): GalleryBoard => ({
imageCount: 3,
kind: 'board',
name,
+ isInbox: false,
projectId: null,
videoCount: 0,
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
index 89c5295c52..c951f1aa01 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx
@@ -49,6 +49,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'
assetVideoCount: 0,
imageCount: 0,
kind: 'board',
+ isInbox: false,
projectId: null,
videoCount: 0,
...overrides,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts
index da4224837e..9ff5d9fa97 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts
@@ -16,6 +16,7 @@ const board: GalleryBoard = {
imageCount: 0,
kind: 'board',
name: 'Dogs',
+ isInbox: false,
projectId: null,
videoCount: 0,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
index a16e9505de..733af62e59 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts
@@ -10,6 +10,7 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'
assetVideoCount: 0,
imageCount: 0,
kind: 'board',
+ isInbox: false,
projectId: null,
videoCount: 0,
...overrides,
@@ -20,8 +21,10 @@ const dogs = createBoard({ id: 'dogs', name: 'dogs' });
const cats = createBoard({ id: 'cats', name: 'Cats' });
const archived = createBoard({ archived: true, id: 'gorl', name: 'GORL' });
const dateBoard = createBoard({ id: 'by_date:2026-07-28', kind: 'date', name: '28 July' });
-const otherProject = createBoard({ id: 'other', name: 'Someone else', projectId: 'project-2' });
-const ownProject = createBoard({ id: 'mine', name: 'My project', projectId: 'project-1' });
+const otherProject = createBoard({ id: 'other', isInbox: true, name: 'Someone else', projectId: 'project-2' });
+const ownProject = createBoard({ id: 'mine', isInbox: true, name: 'My project', projectId: 'project-1' });
+const ownMember = createBoard({ id: 'mine-member', name: 'Façades', projectId: 'project-1' });
+const otherMember = createBoard({ id: 'other-member', name: 'Their façades', projectId: 'project-2' });
const t = (key: string) => (key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key);
const groupsOf = (overrides: Partial<Parameters<typeof getGalleryBoardGroups>[0]> = {}) =>
@@ -71,6 +74,16 @@ describe('getGalleryBoardGroups', () => {
expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'mine', 'dogs', 'cats']);
});
+ it('keeps the open project members, but not other projects members, while other projects are hidden', () => {
+ const groups = groupsOf({
+ boards: [uncategorized, dogs, ownProject, ownMember, otherProject, otherMember],
+ projectBoardId: 'mine',
+ showOtherProjects: false,
+ });
+
+ expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'mine', 'dogs', 'mine-member']);
+ });
+
/** The fetched list can lag a rename; the live project name wins for the open project's row. */
it('shows the open project board under the live project name, and searches by it', () => {
const groups = groupsOf({ projectBoardId: 'mine', projectName: 'Renamed' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts
index f09add1607..64bd5c047a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts
@@ -47,9 +47,14 @@ export const getGalleryBoardGroups = ({
const projectBoard = fetchedProjectBoard ? { ...fetchedProjectBoard, name: projectName } : null;
const matchesBoardSearch = (board: GalleryBoard) => matchesSearch(getGalleryBoardLabel(board, t));
- // Always retain the active project's board regardless of the other-projects filter.
+ // The open project's own boards always show, whatever the other-projects filter says. Its id is read off its
+ // fetched inbox, which is a member of it; until the inbox arrives, no board can be known to be its.
+ const openProjectId = fetchedProjectBoard?.projectId ?? null;
const belongsToVisibleProject = (board: GalleryBoard) =>
- showOtherProjects || board.projectId === null || board.id === projectBoard?.id;
+ showOtherProjects ||
+ board.projectId === null ||
+ board.id === projectBoard?.id ||
+ (openProjectId !== null && board.projectId === openProjectId);
const regularBoards = boards.filter(
(board) =>
board.kind === 'board' &&
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
index 3755775166..52acc221e5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardLabels.test.ts
@@ -12,6 +12,7 @@ const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
imageCount: 50,
kind: 'board',
name: 'dogs',
+ isInbox: false,
projectId: null,
videoCount: 4,
...overrides,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index a52699fa65..c8925beca8 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -25,6 +25,7 @@ const boards: GalleryBoard[] = [
imageCount: 1,
kind: 'uncategorized',
name: '',
+ isInbox: false,
projectId: null,
videoCount: 0,
},
@@ -36,6 +37,7 @@ const boards: GalleryBoard[] = [
imageCount: 2,
kind: 'board',
name: 'Board 1',
+ isInbox: false,
projectId: null,
videoCount: 0,
},
@@ -94,7 +96,10 @@ describe('gallery state view', () => {
* Uncategorized.
*/
it('falls back to the project board before uncategorized', () => {
- const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];
+ const projectBoards = [
+ ...boards,
+ { ...boards[1]!, id: 'project-board', isInbox: true, name: 'My Project', projectId: 'p1' },
+ ];
const values = { projectBoardId: 'project-board', selectedBoardId: 'missing-board' };
expect(getGallerySelectedBoardId(values, projectBoards)).toBe('project-board');
@@ -102,7 +107,10 @@ describe('gallery state view', () => {
});
it('keeps a still-resolvable selection rather than reverting to the project board', () => {
- const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];
+ const projectBoards = [
+ ...boards,
+ { ...boards[1]!, id: 'project-board', isInbox: true, name: 'My Project', projectId: 'p1' },
+ ];
const values = { projectBoardId: 'project-board', selectedBoardId: 'board-1' };
expect(getGallerySelectedBoardId(values, projectBoards)).toBe('board-1');
@@ -116,7 +124,10 @@ describe('gallery state view', () => {
/** An absent saved destination is not an explicit choice of Uncategorized; use the project's board. */
it('uses the project board when nothing was ever selected', () => {
- const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];
+ const projectBoards = [
+ ...boards,
+ { ...boards[1]!, id: 'project-board', isInbox: true, name: 'My Project', projectId: 'p1' },
+ ];
expect(getGallerySelectedBoardId({ projectBoardId: 'project-board' }, projectBoards)).toBe('project-board');
expect(getGallerySelectedBoardId({}, projectBoards)).toBe('none');
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index f0e5228de0..6c6dbc15b0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -19,6 +19,7 @@ const UNCATEGORIZED_BOARD: GalleryBoard = {
assetVideoCount: 0,
id: 'none',
imageCount: 0,
+ isInbox: false,
kind: 'uncategorized',
name: '',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
index 08c6667915..2768d7311f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryMediaSlot.browser.test.tsx
@@ -72,6 +72,7 @@ const board: GalleryBoard = {
imageCount: 1,
kind: 'board',
name: 'Dogs',
+ isInbox: false,
projectId: null,
videoCount: 0,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
index 10ed6047b3..b847c3c4df 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx
@@ -72,6 +72,7 @@ const board: GalleryBoard = {
imageCount: 3,
kind: 'board',
name: 'Dogs',
+ isInbox: false,
projectId: null,
videoCount: 1,
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
index 1e9ad88883..89d7285a01 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
@@ -115,6 +115,7 @@ const Probe = ({
imageCount: 2,
kind: 'board',
name: 'Board 1',
+ isInbox: false,
projectId: null,
videoCount: 1,
},
@@ -126,6 +127,7 @@ const Probe = ({
imageCount: 0,
kind: 'uncategorized',
name: '',
+ isInbox: false,
projectId: null,
videoCount: 0,
},
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
index 1b1d55705d..566c6bb6fd 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx
@@ -129,6 +129,7 @@ const Probe = ({
imageCount: 2,
kind: 'board',
name: 'Board 1',
+ isInbox: false,
projectId: null,
videoCount: 1,
},
@@ -140,6 +141,7 @@ const Probe = ({
imageCount: 0,
kind: 'uncategorized',
name: '',
+ isInbox: false,
projectId: null,
videoCount: 0,
},
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index aacaae8f56..f22c7a4f01 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -254,6 +254,7 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<I
assetVideoCount: 0,
id: 'none',
imageCount: 0,
+ isInbox: false,
kind: 'uncategorized',
name: '',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
index d0f402c159..848ddfebf3 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
@@ -50,6 +50,7 @@ const uncategorized: GalleryBoard = {
assetVideoCount: 0,
id: 'none',
imageCount: 1,
+ isInbox: false,
kind: 'uncategorized',
name: '',
projectId: null,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 0b0944a913..5dd89378a2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -117,6 +117,7 @@ const fallbackBoards: GalleryBoard[] = [
assetVideoCount: 0,
id: 'none',
imageCount: 0,
+ isInbox: false,
kind: 'uncategorized',
name: '',
projectId: null,
diff --git a/tests/app/routers/test_boards_multiuser.py b/tests/app/routers/test_boards_multiuser.py
index b184c61deb..335e3a711c 100644
--- a/tests/app/routers/test_boards_multiuser.py
+++ b/tests/app/routers/test_boards_multiuser.py
@@ -952,18 +952,19 @@ def _claim_board_for_a_project(client: TestClient, mock_invoker: Invoker, token:
return board["board_id"]
-def test_a_project_board_reports_the_project_that_owns_it(client: TestClient, mock_invoker: Invoker, user1_token: str):
+def test_a_claimed_board_is_its_projects_inbox(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
+ assert response.json()["is_inbox"] is True
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
+ assert claimed[0]["is_inbox"] is True
def test_an_unclaimed_board_omits_the_project_id(client: TestClient, user1_token: str):
@@ -975,27 +976,6 @@ def test_an_unclaimed_board_omits_the_project_id(client: TestClient, 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
):
@@ -1073,6 +1053,40 @@ def test_board_update_cannot_race_a_project_claim(
assert getattr(board, field) == value
[email protected]("include_images", [False, True])
+def test_a_member_board_deletes_like_any_other(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, include_images: bool
+):
+ """Only the inbox is protected; a project's other boards go through the ordinary deletion, media and all."""
+ inbox_id = _claim_board_for_a_project(client, mock_invoker, user1_token, "Inbox")
+ project_id = client.get(f"/api/v1/boards/{inbox_id}", headers={"Authorization": f"Bearer {user1_token}"}).json()[
+ "project_id"
+ ]
+ member = client.post(
+ f"/api/v1/boards/?board_name=Member&project_id={project_id}",
+ headers={"Authorization": f"Bearer {user1_token}"},
+ ).json()
+ mock_invoker.services.board_images.get_all_board_image_names_for_board.return_value = ["member.png"]
+ mock_invoker.services.images.delete_images_by_names.return_value = (["member.png"], [])
+
+ response = client.delete(
+ f"/api/v1/boards/{member['board_id']}?include_images={'true' if include_images else 'false'}",
+ headers={"Authorization": f"Bearer {user1_token}"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ if include_images:
+ mock_invoker.services.images.delete_images_by_names.assert_called_once_with(["member.png"])
+ assert response.json()["deleted_images"] == ["member.png"]
+ else:
+ mock_invoker.services.images.delete_images_by_names.assert_not_called()
+ assert response.json()["deleted_board_images"] == ["member.png"]
+ assert (
+ client.get(f"/api/v1/boards/{inbox_id}", headers={"Authorization": f"Bearer {user1_token}"}).status_code
+ == status.HTTP_200_OK
+ )
+
+
@pytest.mark.parametrize("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
diff --git a/tests/app/routers/test_boards_projects.py b/tests/app/routers/test_boards_projects.py
new file mode 100644
index 0000000000..b782407988
--- /dev/null
+++ b/tests/app/routers/test_boards_projects.py
@@ -0,0 +1,240 @@
+"""The HTTP contract for boards that live in projects.
+
+A board belongs to exactly one of its owner's projects, or to the Library. Every project has an
+inbox, which only the project routes may rename, archive, move or delete; its other boards are
+ordinary boards that happen to be members. The storage rules live in the board records service;
+what these pin is which failure is a 404 and which a 409, and that members and inboxes are told
+apart on the wire.
+"""
+
+from typing import Any
+
+import pytest
+from fastapi import status
+from fastapi.testclient import TestClient
+
+from tests.app.routers.conftest import _auth, _create_board
+
+
+def _create_project(client: TestClient, token: str, name: str = "Project") -> dict[str, Any]:
+ response = client.post("/api/v1/projects/", json={"name": name, "data": {}}, headers=_auth(token))
+ assert response.status_code == status.HTTP_201_CREATED
+ return response.json()
+
+
+def _create_member(client: TestClient, token: str, project_id: str, name: str = "Member") -> dict[str, Any]:
+ response = client.post(f"/api/v1/boards/?board_name={name}&project_id={project_id}", headers=_auth(token))
+ assert response.status_code == status.HTTP_201_CREATED
+ return response.json()
+
+
+def _get_board(client: TestClient, token: str, board_id: str) -> dict[str, Any]:
+ response = client.get(f"/api/v1/boards/{board_id}", headers=_auth(token))
+ assert response.status_code == status.HTTP_200_OK
+ return response.json()
+
+
+def _move(client: TestClient, token: str, board_id: str, project_id: str | None):
+ return client.patch(f"/api/v1/boards/{board_id}", json={"project_id": project_id}, headers=_auth(token))
+
+
+# --- creating ---------------------------------------------------------------------------------
+
+
+def test_a_board_created_in_a_project_is_a_member_but_not_the_inbox(client: TestClient, user1_token: str):
+ project = _create_project(client, user1_token)
+
+ member = _create_member(client, user1_token, project["project_id"])
+
+ assert member["project_id"] == project["project_id"]
+ assert member["is_inbox"] is False
+ assert member["board_visibility"] == "private"
+ inbox = _get_board(client, user1_token, project["board_id"])
+ assert inbox["project_id"] == project["project_id"]
+ assert inbox["is_inbox"] is True
+
+
+def test_a_library_board_carries_neither_membership_nor_the_inbox_flag(client: TestClient, user1_token: str):
+ board = _get_board(client, user1_token, _create_board(client, user1_token, "Library+Board"))
+
+ assert board.get("project_id") is None
+ assert board["is_inbox"] is False
+
+
+def test_creating_a_board_in_someone_elses_or_a_missing_project_is_a_404(
+ client: TestClient, user1_token: str, user2_token: str
+):
+ theirs = _create_project(client, user2_token)
+
+ for project_id in (theirs["project_id"], "no-such-project"):
+ response = client.post(
+ f"/api/v1/boards/?board_name=Intruder&project_id={project_id}", headers=_auth(user1_token)
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ assert all(
+ b["board_name"] != "Intruder" for b in client.get("/api/v1/boards/?all=true", headers=_auth(user2_token)).json()
+ )
+
+
+# --- moving -----------------------------------------------------------------------------------
+
+
+def test_a_board_moves_between_the_library_and_projects(client: TestClient, user1_token: str):
+ first = _create_project(client, user1_token, "First")
+ second = _create_project(client, user1_token, "Second")
+ board_id = _create_board(client, user1_token, "Roaming")
+
+ into_first = _move(client, user1_token, board_id, first["project_id"])
+ assert into_first.status_code == status.HTTP_201_CREATED
+ assert into_first.json()["project_id"] == first["project_id"]
+
+ into_second = _move(client, user1_token, board_id, second["project_id"])
+ assert into_second.json()["project_id"] == second["project_id"]
+
+ to_library = _move(client, user1_token, board_id, None)
+ assert to_library.status_code == status.HTTP_201_CREATED
+ assert to_library.json().get("project_id") is None
+
+
+def test_omitting_project_id_leaves_a_member_where_it_is(client: TestClient, user1_token: str):
+ project = _create_project(client, user1_token)
+ member = _create_member(client, user1_token, project["project_id"])
+
+ renamed = client.patch(
+ f"/api/v1/boards/{member['board_id']}", json={"board_name": "Still here"}, headers=_auth(user1_token)
+ )
+
+ assert renamed.status_code == status.HTTP_201_CREATED
+ assert renamed.json()["board_name"] == "Still here"
+ assert renamed.json()["project_id"] == project["project_id"]
+
+
+def test_moving_into_someone_elses_project_is_a_404_and_moves_nothing(
+ client: TestClient, user1_token: str, user2_token: str, admin_token: str
+):
+ theirs = _create_project(client, user2_token)
+ board_id = _create_board(client, user1_token, "Mine")
+ admins_project = _create_project(client, admin_token, "Admin's")
+
+ assert _move(client, user1_token, board_id, theirs["project_id"]).status_code == status.HTTP_404_NOT_FOUND
+ assert _move(client, user1_token, board_id, "no-such-project").status_code == status.HTTP_404_NOT_FOUND
+ # An admin may edit the board, but only the board's owner's projects can hold it.
+ assert _move(client, admin_token, board_id, admins_project["project_id"]).status_code == status.HTTP_404_NOT_FOUND
+
+ assert _get_board(client, user1_token, board_id).get("project_id") is None
+
+
[email protected]("changes", [{"board_name": "Renamed"}, {"archived": True}, {"board_visibility": "public"}])
+def test_an_inbox_cannot_be_changed_or_moved_through_the_board_routes(
+ client: TestClient, user1_token: str, admin_token: str, changes: dict[str, Any]
+):
+ project = _create_project(client, user1_token, "Owning project")
+ other = _create_project(client, user1_token, "Other")
+
+ for token in (user1_token, admin_token):
+ for body in (changes, {"project_id": None}, {"project_id": other["project_id"]}):
+ response = client.patch(f"/api/v1/boards/{project['board_id']}", json=body, headers=_auth(token))
+ assert response.status_code == status.HTTP_409_CONFLICT, body
+
+ inbox = _get_board(client, user1_token, project["board_id"])
+ assert inbox["board_name"] == "Owning project"
+ assert inbox["archived"] is False
+ assert inbox["board_visibility"] == "private"
+ assert inbox["project_id"] == project["project_id"]
+
+
[email protected]("visibility", ["shared", "public"])
+def test_a_non_private_board_cannot_enter_a_project(client: TestClient, user1_token: str, visibility: str):
+ project = _create_project(client, user1_token)
+ board_id = _create_board(client, user1_token, "Visible")
+ assert (
+ client.patch(
+ f"/api/v1/boards/{board_id}", json={"board_visibility": visibility}, headers=_auth(user1_token)
+ ).status_code
+ == status.HTTP_201_CREATED
+ )
+
+ refused = _move(client, user1_token, board_id, project["project_id"])
+
+ assert refused.status_code == status.HTTP_409_CONFLICT
+ assert _get_board(client, user1_token, board_id).get("project_id") is None
+
+
+def test_an_explicitly_shared_board_cannot_enter_a_project(
+ client: TestClient, mock_invoker, user1_token: str, user2_token: str
+):
+ project = _create_project(client, user1_token)
+ board_id = _create_board(client, user1_token, "Shared+with+two")
+ recipient = client.get("/api/v1/auth/me", headers=_auth(user2_token)).json()["user_id"]
+ with mock_invoker.services.board_records._db.transaction() as cursor:
+ cursor.execute("INSERT INTO shared_boards (board_id, user_id) VALUES (?, ?);", (board_id, recipient))
+
+ assert _move(client, user1_token, board_id, project["project_id"]).status_code == status.HTTP_409_CONFLICT
+
+
[email protected]("visibility", ["shared", "public"])
+def test_a_member_cannot_be_published(client: TestClient, user1_token: str, visibility: str):
+ project = _create_project(client, user1_token)
+ member = _create_member(client, user1_token, project["project_id"])
+
+ refused = client.patch(
+ f"/api/v1/boards/{member['board_id']}", json={"board_visibility": visibility}, headers=_auth(user1_token)
+ )
+
+ assert refused.status_code == status.HTTP_409_CONFLICT
+ assert _get_board(client, user1_token, member["board_id"])["board_visibility"] == "private"
+
+
+def test_publishing_and_leaving_a_project_in_one_request_is_allowed(client: TestClient, user1_token: str):
+ """The rules apply to the board as it will be, not as it is."""
+ project = _create_project(client, user1_token)
+ member = _create_member(client, user1_token, project["project_id"])
+
+ response = client.patch(
+ f"/api/v1/boards/{member['board_id']}",
+ json={"board_visibility": "public", "project_id": None},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["board_visibility"] == "public"
+ assert response.json().get("project_id") is None
+
+
+# --- members are ordinary boards -------------------------------------------------------------
+
+
+def test_a_member_can_be_renamed_archived_and_deleted(client: TestClient, user1_token: str):
+ project = _create_project(client, user1_token)
+ member = _create_member(client, user1_token, project["project_id"])
+
+ changed = client.patch(
+ f"/api/v1/boards/{member['board_id']}",
+ json={"board_name": "Kitchen", "archived": True},
+ headers=_auth(user1_token),
+ )
+ assert changed.status_code == status.HTTP_201_CREATED
+ assert changed.json()["board_name"] == "Kitchen"
+ assert changed.json()["archived"] is True
+
+ deleted = client.delete(f"/api/v1/boards/{member['board_id']}", headers=_auth(user1_token))
+ assert deleted.status_code == status.HTTP_200_OK
+ assert client.get(f"/api/v1/boards/{member['board_id']}", headers=_auth(user1_token)).status_code == 404
+ # The project and its inbox are untouched.
+ assert _get_board(client, user1_token, project["board_id"])["is_inbox"] is True
+
+
+def test_the_listing_tells_inboxes_and_members_apart(client: TestClient, user1_token: str):
+ project = _create_project(client, user1_token)
+ member = _create_member(client, user1_token, project["project_id"])
+ loose = _create_board(client, user1_token, "Loose")
+
+ listed = {b["board_id"]: b for b in client.get("/api/v1/boards/?all=true", headers=_auth(user1_token)).json()}
+
+ assert listed[project["board_id"]]["is_inbox"] is True
+ assert listed[project["board_id"]]["project_id"] == project["project_id"]
+ assert listed[member["board_id"]]["is_inbox"] is False
+ assert listed[member["board_id"]]["project_id"] == project["project_id"]
+ assert listed[loose]["is_inbox"] is False
+ assert listed[loose].get("project_id") is None
diff --git a/tests/app/routers/test_projects.py b/tests/app/routers/test_projects.py
index 34e25fda5d..c36f2457d7 100644
--- a/tests/app/routers/test_projects.py
+++ b/tests/app/routers/test_projects.py
@@ -362,3 +362,41 @@ def test_projects_stay_private_to_their_owner(client: TestClient, user1_token: s
assert client.get(f"/api/v1/boards/{created['board_id']}", headers=_auth(user1_token)).status_code == (
status.HTTP_200_OK
)
+
+
+def _create_board_in_project(client: TestClient, token: str, project_id: str, name: str) -> str:
+ response = client.post(f"/api/v1/boards/?board_name={name}&project_id={project_id}", headers=_auth(token))
+ assert response.status_code == status.HTTP_201_CREATED
+ return response.json()["board_id"]
+
+
+def test_deleting_a_project_releases_its_other_boards_to_the_library(client: TestClient, user1_token: str):
+ created = _create_project(client, user1_token).json()
+ member = _create_board_in_project(client, user1_token, created["project_id"], "Member")
+
+ deleted = client.delete(f"/api/v1/projects/{created['project_id']}", headers=_auth(user1_token))
+
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert client.get(f"/api/v1/boards/{created['board_id']}", headers=_auth(user1_token)).status_code == 404
+ released = client.get(f"/api/v1/boards/{member}", headers=_auth(user1_token)).json()
+ assert released.get("project_id") is None
+ assert released["is_inbox"] is False
+
+
+def test_deleting_a_project_can_delete_its_other_boards(client: TestClient, user1_token: str):
+ created = _create_project(client, user1_token).json()
+ member = _create_board_in_project(client, user1_token, created["project_id"], "Member")
+
+ deleted = client.delete(f"/api/v1/projects/{created['project_id']}?boards=delete", headers=_auth(user1_token))
+
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert client.get(f"/api/v1/boards/{member}", headers=_auth(user1_token)).status_code == 404
+
+
+def test_an_unknown_boards_mode_is_rejected_before_anything_is_deleted(client: TestClient, user1_token: str):
+ created = _create_project(client, user1_token).json()
+
+ refused = client.delete(f"/api/v1/projects/{created['project_id']}?boards=burn", headers=_auth(user1_token))
+
+ assert refused.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
+ assert client.get(f"/api/v1/projects/{created['project_id']}", headers=_auth(user1_token)).status_code == 200
diff --git a/tests/app/services/project_records/test_project_records.py b/tests/app/services/project_records/test_project_records.py
index aebea1ffbf..622d97aa3d 100644
--- a/tests/app/services/project_records/test_project_records.py
+++ b/tests/app/services/project_records/test_project_records.py
@@ -799,3 +799,86 @@ def test_deleting_a_project_drops_its_references(db: SqliteDatabase, project_rec
project_records.delete(SYSTEM_USER_ID, created.project_id)
assert _media_references(db, created.project_id) == set()
+
+
+# --- board membership -------------------------------------------------------------------------
+
+
+def _board_project(db: SqliteDatabase, board_id: str) -> str | None:
+ with db.transaction() as cursor:
+ cursor.execute("SELECT project_id FROM boards WHERE board_id = ?;", (board_id,))
+ row = cursor.fetchone()
+ return None if row is None else row[0]
+
+
+def test_a_new_inbox_is_a_member_of_its_project(project_records: ProjectRecordsSqlite, db: SqliteDatabase) -> None:
+ created = project_records.create(SYSTEM_USER_ID, "Fresh", {})
+
+ assert _board_project(db, created.board_id) == created.project_id
+
+
+def test_a_claimed_inbox_joins_its_project(project_records: ProjectRecordsSqlite, db: SqliteDatabase) -> None:
+ _insert_board(db, "staging")
+
+ created = project_records.create(SYSTEM_USER_ID, "Imported", {}, board_id="staging")
+
+ assert _board_project(db, "staging") == created.project_id
+
+
+def test_a_board_in_another_project_cannot_become_an_inbox(
+ project_records: ProjectRecordsSqlite, db: SqliteDatabase
+) -> None:
+ """Adopting a member would silently demote the inbox the other project already has."""
+ other = project_records.create(SYSTEM_USER_ID, "Other", {})
+ _insert_board(db, "member")
+ with db.transaction() as cursor:
+ cursor.execute("UPDATE boards SET project_id = ? WHERE board_id = 'member';", (other.project_id,))
+
+ with pytest.raises(ProjectBoardUnavailableError):
+ project_records.create(SYSTEM_USER_ID, "Claimant", {}, board_id="member")
+
+ assert _board_project(db, "member") == other.project_id
+
+
+def test_deleting_a_project_releases_its_other_boards_to_the_library_by_default(
+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, other_user_id: str
+) -> None:
+ created = project_records.create(SYSTEM_USER_ID, "Doomed", {}, project_id="shared-id")
+ # The other account's same-id project is untouched: membership is keyed by owner too.
+ theirs = project_records.create(other_user_id, "Theirs", {}, project_id="shared-id")
+ _insert_board(db, "member")
+ _insert_board(db, "their-member", user_id=other_user_id)
+ with db.transaction() as cursor:
+ cursor.execute("UPDATE boards SET project_id = 'shared-id' WHERE board_id IN ('member', 'their-member');")
+ _add_image_to_board(db, "kept.png", "member")
+
+ project_records.delete(SYSTEM_USER_ID, created.project_id)
+
+ assert _board_name(db, created.board_id) is None
+ assert _board_project(db, "member") is None
+ assert _board_project(db, "their-member") == theirs.project_id
+ with db.transaction() as cursor:
+ cursor.execute("SELECT board_id FROM board_images WHERE image_name = 'kept.png';")
+ assert cursor.fetchone()[0] == "member"
+
+
+def test_deleting_a_project_can_take_its_other_boards_but_never_their_media(
+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, other_user_id: str
+) -> None:
+ created = project_records.create(SYSTEM_USER_ID, "Doomed", {}, project_id="shared-id")
+ project_records.create(other_user_id, "Theirs", {}, project_id="shared-id")
+ _insert_board(db, "member")
+ _insert_board(db, "their-member", user_id=other_user_id)
+ with db.transaction() as cursor:
+ cursor.execute("UPDATE boards SET project_id = 'shared-id' WHERE board_id IN ('member', 'their-member');")
+ _add_image_to_board(db, "kept.png", "member")
+
+ project_records.delete(SYSTEM_USER_ID, created.project_id, boards="delete")
+
+ assert _board_name(db, "member") is None
+ assert _board_name(db, "their-member") is not None
+ with db.transaction() as cursor:
+ cursor.execute("SELECT COUNT(*) FROM board_images WHERE image_name = 'kept.png';")
+ assert cursor.fetchone()[0] == 0
+ cursor.execute("SELECT COUNT(*) FROM images WHERE image_name = 'kept.png';")
+ assert cursor.fetchone()[0] == 1
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_08_add_board_project_membership.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_08_add_board_project_membership.py
new file mode 100644
index 0000000000..d73d62b8e5
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_08_add_board_project_membership.py
@@ -0,0 +1,141 @@
+"""Existing boards gain membership: every inbox joins its project, everything else is Library."""
+
+from logging import Logger
+from unittest.mock import MagicMock
+
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+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_10_08_add_board_project_membership import (
+ build_migration,
+)
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import SqliteMigrator
+from invokeai.app.services.users.users_common import UserCreateRequest
+from invokeai.app.services.users.users_default import UserService
+
+MIGRATION_ID = "2026_10_08_add_board_project_membership"
+
+
+def _run(db: SqliteDatabase, migrations: list[Migration]) -> bool:
+ migrator = SqliteMigrator(db=db)
+ for migration in migrations:
+ migrator.register_migration(migration)
+ return migrator.run_migrations()
+
+
+def _previous_state(migrations: list[Migration]) -> list[Migration]:
+ """Every migration except this one and those that depend on it, directly or not."""
+ by_id = {migration.id: migration for migration in migrations}
+
+ def depends_on_this(migration: Migration) -> bool:
+ current: str | None = migration.id
+ while current is not None:
+ if current == MIGRATION_ID:
+ return True
+ current = by_id[current].depends_on
+ return False
+
+ return [migration for migration in migrations if not depends_on_this(migration)]
+
+
+def _has_column(db: SqliteDatabase) -> bool:
+ return any(row[1] == "project_id" for row in db._conn.execute("PRAGMA table_info(boards);").fetchall())
+
+
+def _has_index(db: SqliteDatabase) -> bool:
+ return db._conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'idx_boards_project_id';").fetchone() is not None
+
+
+def _memberships(db: SqliteDatabase) -> dict[str, str | None]:
+ rows = db._conn.execute("SELECT board_id, project_id FROM boards ORDER BY board_id;").fetchall()
+ return {row[0]: row[1] for row in rows}
+
+
+def test_inboxes_join_their_projects_and_other_boards_stay_in_the_library() -> None:
+ logger = Logger("test")
+ context = MigrationBuildContext(
+ app_config=InvokeAIAppConfig(use_memory_db=True, node_cache_size=0), logger=logger, image_files=MagicMock()
+ )
+ migrations = build_migrations(context)
+ db = SqliteDatabase(db_path=None, logger=logger)
+ assert _run(db, _previous_state(migrations))
+ assert not _has_column(db)
+
+ # Two accounts, each with a project: every inbox joins the project that names it.
+ alice = UserService(db=db).create(
+ UserCreateRequest(email="[email protected]", display_name="Alice", password="TestPass123", is_admin=False)
+ )
+ bob = UserService(db=db).create(
+ UserCreateRequest(email="[email protected]", display_name="Bob", password="TestPass123", is_admin=False)
+ )
+ with db.transaction() as cursor:
+ cursor.executemany(
+ "INSERT INTO boards (board_id, board_name, user_id) VALUES (?, ?, ?);",
+ [
+ ("alice-inbox", "Alice's project", alice.user_id),
+ ("bob-inbox", "Bob's project", bob.user_id),
+ ("alice-loose", "References", alice.user_id),
+ ("system-loose", "Legacy", "system"),
+ ],
+ )
+ cursor.executemany(
+ "INSERT INTO projects (project_id, user_id, name, data, board_id) VALUES (?, ?, ?, '{}', ?);",
+ [
+ ("alice-project", alice.user_id, "Alice's project", "alice-inbox"),
+ ("bob-project", bob.user_id, "Bob's project", "bob-inbox"),
+ ],
+ )
+
+ assert _run(db, migrations)
+ assert _has_column(db)
+ assert _memberships(db) == {
+ "alice-inbox": "alice-project",
+ "alice-loose": None,
+ "bob-inbox": "bob-project",
+ "system-loose": None,
+ }
+ assert _has_index(db)
+ assert not _run(db, migrations)
+
+
+def test_rerunning_leaves_existing_memberships_alone() -> None:
+ """The callback is safe to apply again: it only fills in what is missing, never overwrites.
+
+ The inbox seeded as a member of `other` is a state the services never produce; it is here to prove
+ the backfill is gated on `project_id IS NULL` rather than on being an inbox.
+ """
+ logger = Logger("test")
+ context = MigrationBuildContext(
+ app_config=InvokeAIAppConfig(use_memory_db=True, node_cache_size=0), logger=logger, image_files=MagicMock()
+ )
+ db = SqliteDatabase(db_path=None, logger=logger)
+ assert _run(db, build_migrations(context))
+ user = UserService(db=db).create(
+ UserCreateRequest(email="[email protected]", display_name="Carol", password="TestPass123", is_admin=False)
+ )
+ with db.transaction() as cursor:
+ cursor.execute(
+ "INSERT INTO boards (board_id, board_name, user_id, project_id) VALUES ('inbox', 'P', ?, 'other');",
+ (user.user_id,),
+ )
+ cursor.execute(
+ "INSERT INTO boards (board_id, board_name, user_id, project_id) VALUES ('member', 'M', ?, 'elsewhere');",
+ (user.user_id,),
+ )
+ cursor.execute(
+ "INSERT INTO boards (board_id, board_name, user_id) VALUES ('unfilled-inbox', 'U', ?);", (user.user_id,)
+ )
+ cursor.execute(
+ "INSERT INTO projects (project_id, user_id, name, data, board_id) VALUES ('p', ?, 'P', '{}', 'inbox');",
+ (user.user_id,),
+ )
+ cursor.execute(
+ "INSERT INTO projects (project_id, user_id, name, data, board_id) VALUES ('u', ?, 'U', '{}', 'unfilled-inbox');",
+ (user.user_id,),
+ )
+
+ with db.transaction() as cursor:
+ build_migration().callback(cursor)
+
+ assert _memberships(db) == {"inbox": "other", "member": "elsewhere", "unfilled-inbox": "u"}