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.

refactor(projects): share the duplicated transport, walker and quarantine paths

Josh Corbettea2210ce15bd
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.py
index 117ff6ef5a..4804df21e8 100644
--- a/invokeai/app/api/routers/_access.py
+++ b/invokeai/app/api/routers/_access.py
@@ -11,6 +11,21 @@ from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.services.board_records.board_records_common import BoardVisibility
+def _board_grants_contribution(board_id: str, current_user: CurrentUserOrDefault) -> bool:
+ """Whether this user may put media on the board: they own it, or it is Public.
+
+ Shared boards are deliberately excluded — `Shared` grants visibility, not contribution. A board
+ that cannot be read at all answers `False` rather than raising, so the media-owner helpers below
+ can fall through to their own denial instead of reporting a board error for a media request.
+ """
+ try:
+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
+ except Exception:
+ return False
+
+ return board.user_id == current_user.user_id or board.board_visibility == BoardVisibility.Public
+
+
def assert_image_owner(image_name: str, current_user: CurrentUserOrDefault) -> None:
"""Raise 403 if the current user does not own the image and is not an admin.
@@ -29,15 +44,8 @@ def assert_image_owner(image_name: str, current_user: CurrentUserOrDefault) -> N
return
board_id = ApiDependencies.invoker.services.board_image_records.get_board_for_image(image_name)
- if board_id is not None:
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- if board.user_id == current_user.user_id:
- return
- if board.board_visibility == BoardVisibility.Public:
- return
- except Exception:
- pass
+ if board_id is not None and _board_grants_contribution(board_id, current_user):
+ return
raise HTTPException(status_code=403, detail="Not authorized to modify this image")
@@ -137,15 +145,8 @@ def assert_video_owner(video_name: str, current_user: CurrentUserOrDefault) -> N
return
board_id = ApiDependencies.invoker.services.board_video_records.get_board_for_video(video_name)
- if board_id is not None:
- try:
- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)
- if board.user_id == current_user.user_id:
- return
- if board.board_visibility == BoardVisibility.Public:
- return
- except Exception:
- pass
+ if board_id is not None and _board_grants_contribution(board_id, current_user):
+ return
raise HTTPException(status_code=403, detail="Not authorized to modify this video")
diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.py
index 5573b793bc..caecbd1567 100644
--- a/invokeai/app/services/project_records/project_records_sqlite.py
+++ b/invokeai/app/services/project_records/project_records_sqlite.py
@@ -34,15 +34,13 @@ _VISIBLE_CATEGORY_PLACEHOLDERS = ", ".join("?" for _ in _VISIBLE_BOARD_CATEGORIE
class ProjectRecordsSqlite(ProjectRecordsStorageBase):
"""SQLite implementation of per-user project document storage.
- A project and its board are one unit here. Every write that touches both — creating them,
- renaming them, deleting them — happens inside a single `self._db.transaction()` so the two can
- never disagree.
+ A project and its board are one unit: every write touching both happens inside a single
+ `self._db.transaction()`.
- That transaction is the reason this class talks to `boards` in raw SQL rather than through
+ That transaction is why this class talks to `boards` in raw SQL rather than through
`BoardService`. `SqliteDatabase.transaction()` guards a re-entrant lock and commits on the way
- out of *every* level, so calling another service's method from inside an open transaction would
- commit this one's half-finished work. Nothing between the `with` and its close may call anything
- that opens a transaction of its own, including `self.get()`.
+ out of *every* level, so calling another service from inside an open transaction would commit
+ this one's half-finished work — including `self.get()`.
"""
def __init__(self, db: SqliteDatabase) -> None:
@@ -183,13 +181,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
def delete(self, user_id: str, project_id: str) -> None:
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;
- """,
- (user_id, project_id),
- )
- row = cursor.fetchone()
+ row = self._board_row(cursor, user_id=user_id, project_id=project_id)
if row is None:
return
@@ -213,13 +205,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
def get_board_snapshot(self, user_id: str, project_id: str) -> ProjectBoardSnapshotDTO:
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;
- """,
- (user_id, project_id),
- )
- row = cursor.fetchone()
+ row = self._board_row(cursor, user_id=user_id, project_id=project_id)
if row is None:
raise ProjectRecordNotFoundError(project_id)
@@ -274,19 +260,28 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
def get_board_id(self, user_id: str, project_id: str) -> str:
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;
- """,
- (user_id, project_id),
- )
- row = cursor.fetchone()
+ row = self._board_row(cursor, user_id=user_id, project_id=project_id)
if row is None:
raise ProjectRecordNotFoundError(project_id)
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.
+
+ Cursor-taking rather than transaction-opening, so callers stay in charge of the unit of work
+ this class's docstring describes.
+ """
+ cursor.execute(
+ """--sql
+ SELECT board_id FROM projects WHERE user_id = ? AND project_id = ?;
+ """,
+ (user_id, project_id),
+ )
+
+ return cursor.fetchone()
+
def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str) -> str:
board_id = uuid_string()
cursor.execute(
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py
index 1ffdeb94af..f9813ae17b 100644
--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py
@@ -1,34 +1,25 @@
"""Give every project a first-class board that SQLite owns.
-Until now a "project board" was a fiction the client maintained: the Workbench created an ordinary
-board on demand and stashed its id in the opaque project document at
-`widgetInstances.<id>.state.values.projectBoardId`. Nothing on the server knew the board belonged to
-a project, so the board could be renamed, archived or deleted out from under it, two projects could
-name the same board, and a project restored on another install pointed at a board id that did not
-exist there.
-
-This migration moves the relationship into the schema: `projects.board_id` becomes `NOT NULL UNIQUE`
-with a foreign key to `boards`. The `UNIQUE` makes "a board belongs to at most one project" a
-database fact, and the FK makes "a claimed board cannot be deleted" one too,
-backing the application's 409 rather than merely agreeing with it.
-
-Existing projects keep the board they were already using **only when that is unambiguously safe**.
-The document is opaque and client-written, so its `projectBoardId` is treated as a hint to be
-verified, never as an assertion: a candidate is adopted only when exactly one distinct value survives
-every ownership test. Anything ambiguous — two candidates, a board owned by someone else, a shared or
-public board, one another project already took — gets a fresh empty board instead. That is the
-conservative direction: a project that adopts nothing merely starts with an empty board, whereas a
-project that adopts the wrong board takes ownership of media it does not own.
-
-Nothing is moved between boards. `board_images` and `board_videos` are read but never written, so no
-image or video changes hands here. The projects table gains a column, boards may gain rows and a new
-name, and an FK-free quarantine table is created only when a legacy project refers to a user row it
-cannot reach — either because that account is gone, or because the database has no `users` table at
-all. See `_quarantine_every_project` for how the second case arises.
+A "project board" used to be a client-side fiction: an ordinary board whose id lived in the opaque
+project document. Nothing on the server knew it belonged to a project, so it could be renamed,
+archived or deleted out from under one, and two projects could name the same board.
+
+`projects.board_id` becomes `NOT NULL UNIQUE` with a foreign key to `boards`, making "at most one
+project per board" and "a claimed board cannot be deleted" database facts rather than application
+conventions.
+
+Existing projects keep their board **only when that is unambiguously safe**. The document is
+client-written, so its `projectBoardId` is a hint to verify, never an assertion: adopted only when
+exactly one distinct value survives every ownership test. Anything ambiguous gets a fresh empty
+board — a project that adopts nothing merely starts empty, whereas one that adopts the wrong board
+takes ownership of media it does not own.
+
+Nothing moves between boards: `board_images` and `board_videos` are read but never written.
"""
import json
import sqlite3
+from collections.abc import Callable
from logging import Logger
from typing import Any, Optional
@@ -61,50 +52,46 @@ class AddProjectBoardsMigrationCallback:
self._rebuild_projects_table(cursor, assignments)
- def _quarantine_orphaned_projects(self, cursor: sqlite3.Cursor) -> None:
- """Preserve project rows whose owner no longer exists outside the live table.
-
- The rebuilt table re-inserts every row under `FOREIGN KEY (user_id) REFERENCES users`, with
- `PRAGMA foreign_keys = ON` and no way to turn it off inside the migrator's transaction. The
- old table tolerated an orphan; the new one aborts on it, which would take the whole
- migration — and with it the app's ability to open the database — over a row nothing can
- reach. They cannot remain live, but deleting their documents would make repair impossible.
- A deliberately FK-free quarantine keeps the complete original row for an operator to
- inspect or restore after repairing the missing account.
+ def _quarantine(self, cursor: sqlite3.Cursor, where: str, describe: Callable[[str, str], str]) -> None:
+ """Copy the project rows matching `where` into a FK-free table, keeping them whole.
+
+ The rebuild re-inserts every row under `FOREIGN KEY (user_id) REFERENCES users` with
+ `PRAGMA foreign_keys = ON`, which cannot be turned off inside the migrator's transaction, so
+ an unreachable row would abort the whole migration — and with it the app's ability to open
+ the database. Deleting the documents instead would make repair impossible.
"""
- cursor.execute(
- """--sql
- SELECT project_id, user_id FROM projects
- WHERE user_id NOT IN (SELECT user_id FROM users);
- """
- )
- orphans = cursor.fetchall()
+ cursor.execute(f"SELECT project_id, user_id FROM projects WHERE {where};")
+ rows = cursor.fetchall()
- if not orphans:
+ if not rows:
return
self._create_quarantine_table(cursor)
cursor.execute(
- """--sql
+ f"""--sql
INSERT OR IGNORE INTO orphaned_projects_2026_08_06
(project_id, user_id, name, data, revision, created_at, updated_at)
SELECT project_id, user_id, name, data, revision, created_at, updated_at
- FROM projects
- WHERE user_id NOT IN (SELECT user_id FROM users);
+ FROM projects WHERE {where};
"""
)
- for project_id, user_id in orphans:
- self._logger.warning(
- f"Project boards migration: quarantining project {project_id}, whose owner {user_id} no longer exists,"
- " in orphaned_projects_2026_08_06."
- )
+ for project_id, user_id in rows:
+ self._logger.warning(describe(project_id, user_id))
- cursor.execute(
- """--sql
- DELETE FROM projects WHERE user_id NOT IN (SELECT user_id FROM users);
- """
+ def _quarantine_orphaned_projects(self, cursor: sqlite3.Cursor) -> None:
+ """Rescue rows whose owner no longer exists, then delete them from the live table."""
+ orphaned = "user_id NOT IN (SELECT user_id FROM users)"
+
+ self._quarantine(
+ cursor,
+ orphaned,
+ lambda project_id, user_id: (
+ f"Project boards migration: quarantining project {project_id}, whose owner {user_id}"
+ " no longer exists, in orphaned_projects_2026_08_06."
+ ),
)
+ cursor.execute(f"DELETE FROM projects WHERE {orphaned};")
def _quarantine_every_project(self, cursor: sqlite3.Cursor) -> None:
"""The same rescue, for a database that has no `users` table at all.
@@ -116,38 +103,21 @@ class AddProjectBoardsMigrationCallback:
reference to `users` was a foreign key clause, which SQLite does not resolve until DML, so
such a root opened without complaint until this migration became the first to read the table.
- Note what is *not* done here: the rows are copied out but never deleted. With the foreign key
- enforced and its target missing, SQLite refuses any DML against `projects` — including a
- `DELETE`. Dropping the table in the rebuild is what removes them, and that needs no
- resolution.
+ Note what is *not* done here, unlike the orphan case: the rows are copied out but never
+ deleted. With the foreign key enforced and its target missing, SQLite refuses any DML against
+ `projects` — including a `DELETE`. Dropping the table in the rebuild is what removes them,
+ and that needs no resolution.
"""
- cursor.execute(
- """--sql
- SELECT project_id, user_id FROM projects;
- """
- )
- projects = cursor.fetchall()
-
- if not projects:
- return
-
- self._create_quarantine_table(cursor)
- cursor.execute(
- """--sql
- INSERT OR IGNORE INTO orphaned_projects_2026_08_06
- (project_id, user_id, name, data, revision, created_at, updated_at)
- SELECT project_id, user_id, name, data, revision, created_at, updated_at
- FROM projects;
- """
- )
-
- for project_id, user_id in projects:
- self._logger.warning(
+ self._quarantine(
+ cursor,
+ "1 = 1",
+ lambda project_id, user_id: (
f"Project boards migration: quarantining project {project_id} in"
" orphaned_projects_2026_08_06. This database has no users table, so its owner"
f" {user_id} cannot be resolved — it was last opened by an upstream build and this"
" fork's multiuser migration never ran on it."
- )
+ ),
+ )
def _create_quarantine_table(self, cursor: sqlite3.Cursor) -> None:
"""Deliberately free of foreign keys, so it can hold rows the live table cannot."""
@@ -170,14 +140,13 @@ class AddProjectBoardsMigrationCallback:
def _assign_boards(self, cursor: sqlite3.Cursor) -> list[tuple[int, str]]:
"""Resolve one board per project, creating boards as needed.
- Returns (rowid, board_id) pairs. Projects are visited in `rowid` order so that when two of
- them name the same board the earlier one wins, deterministically and repeatably.
+ Returns (rowid, board_id) pairs, visited in `rowid` order so the earlier project wins when
+ two name the same board.
- Read one row at a time, through a cursor of its own. `data` is a whole project document —
- canvas layers, queue history, the lot — so a `fetchall()` here would hold every project on
- the install in memory at once, and this runs at startup on a machine that is about to load
- models. The second cursor is what makes that safe: the writes below run on `cursor`, and
- issuing them on the cursor being iterated would discard the result set out from under it.
+ Row at a time, through a cursor of its own: `data` is a whole project document, so
+ `fetchall()` would hold every project in memory at startup. The second cursor is what makes
+ that safe — the writes below run on `cursor`, which would discard the result set being
+ iterated.
"""
reader = cursor.connection.cursor()
reader.execute(
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 9c32fe81e2..bc9c37f1e7 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -13,50 +13,19 @@ import { INVK_MAX_ARCHIVE_BYTES } from './archive';
import { InvkFormatError } from './format';
/**
- * The asset half of a project file: pulling referenced bytes off the server on
- * the way out, and putting the missing ones back on the way in.
+ * The asset half of a project file: pulling referenced bytes off the server on the way out, and
+ * putting the missing ones back on the way in.
*
- * This lives beside the archive rather than reaching for
- * `canvas-operations/backend/canvasImages.ts`, which does the same upload for
- * paint layers. That module is private to canvas-operations, and exporting it
- * would make importing a project file — a Launchpad action, on a route that
- * deliberately never loads the editor — pull the canvas graph behind it.
+ * Not reached through `canvas-operations/backend/canvasImages.ts`, which does the same upload:
+ * importing is a Launchpad action on a route that never loads the editor, and it must not pull the
+ * canvas graph behind it.
*
- * ### Two upload paths, because a restore carries two kinds of media
- *
- * A document *reference* is a pointer to pixels the project draws with. Those go
- * up under the category `'other'` and onto no board — that is the canvas's
- * private category: the backend lists it in neither `IMAGE_CATEGORIES` nor
- * `ASSETS_CATEGORIES`, so it appears in no gallery view and no board count (the
- * reasoning is written out in full at `canvas-operations/backend/canvasImages.ts`).
- * The previous frontend uploaded restored images as `'general'`, which empties a
- * stranger's project into your gallery; the pixels a document points at are not
- * gallery content, they are the document.
- *
- * A project *board item* is the opposite: it is gallery content, and the archive
- * recorded the category it was filed under. {@link uploadBoardImage} and its
- * video twin put it back under that category, on the project's staging board, so
- * the restored board looks like the exported one rather than like a pile of
- * uncategorized uploads.
- *
- * ### Images and videos are not symmetric
- *
- * Everything here exists twice because the backend keeps the two in separate
- * namespaces with separate routes. The one place they genuinely differ in shape
- * is the existence check: images have a bulk `images_by_names`, videos have no
- * equivalent, so the video check fans out one request per name behind a
- * concurrency limit. That is what `hydrateVideoRefs` in the gallery's data layer
- * already does for the same reason, and what the previous frontend did for
- * images before the bulk endpoint existed.
+ * Document references upload under category `'other'` — the canvas's private category, in neither
+ * `IMAGE_CATEGORIES` nor `ASSETS_CATEGORIES` — because pixels a document points at are the
+ * document, not gallery content. Board items upload under the category the archive recorded.
*/
-/**
- * Simultaneous requests any one transfer may have in flight, in either direction.
- *
- * Matches the previous frontend's limit. One number rather than four identical ones, because it is
- * one budget: the point is to be kind to a backend that is very likely also generating, and a limit
- * per phase would multiply exactly what it exists to bound.
- */
+/** One budget for the whole transfer: a per-phase limit would multiply what it exists to bound. */
export const INVK_TRANSFER_CONCURRENCY = 5;
const BOARDS_BASE = '/api/v1/boards';
@@ -67,39 +36,19 @@ const VIDEOS_BASE = '/api/v1/videos';
const MAX_BOARD_NAME_LENGTH = 300;
/**
- * Whether a failed request means "the work this belonged to is over" rather
- * than "this one asset could not be served".
+ * Whether a failure means "this work is over" rather than "this one asset could not be served".
*
- * Export treats an unservable asset as a skip, which is right — half a
- * project's pixels beats none. But an aborted signal makes *every* asset
- * unservable, and a skip-everything export writes an archive full of nothing
- * and hands it to the browser as though it had succeeded. The two have to be
- * told apart at the point the request fails, because by the time the archive is
- * packed they look identical.
+ * An aborted signal makes *every* asset unservable, and a skip-everything export writes an empty
+ * archive and hands it over as a success. Distinguishable only where the request fails — by the
+ * time the archive is packed the two look identical.
*/
export const isRequestCancellation = (error: unknown): boolean =>
error instanceof HttpRequestIdentityExpiredError || (error instanceof Error && error.name === 'AbortError');
-/**
- * Names per existence request. The endpoint answers any length, but a URL-free
- * POST body of ten thousand names is still a request worth splitting so that one
- * slow lookup cannot stall the whole check.
- */
+/** Names per existence request, so one slow lookup cannot stall the whole check. */
const EXISTENCE_BATCH_SIZE = 500;
-/** Simultaneous existence batches, matching the transfer limit. */
-const EXISTENCE_BATCH_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
-
-/** Simultaneous per-name video lookups, matching the image fetch limit. */
-const VIDEO_EXISTENCE_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
-
-/**
- * Maximum names accepted by the backend's synchronous media batch routes.
- *
- * This is deliberately smaller than the archive's entry ceiling: archive size bounds a complete
- * transfer, while this bounds one unit of server work. Every adapter below owns the split so callers
- * can reason in project-sized lists without learning transport limits.
- */
+/** Maximum names the backend's synchronous batch routes accept. Adapters below own the split. */
const MEDIA_REQUEST_BATCH_SIZE = 1_000;
const toBatches = <T>(items: readonly T[], size: number): T[][] => {
@@ -112,14 +61,7 @@ const toBatches = <T>(items: readonly T[], size: number): T[][] => {
return batches;
};
-/**
- * Let go of a response whose body this module is not going to read.
- *
- * `apiFetchRaw` hands back the response untouched, so a skipped asset or an existence probe leaves
- * an unconsumed stream holding its connection until the collector gets to it. This module's whole
- * argument is that it is bounded and kind to the backend; that has to include the requests it
- * decides not to use.
- */
+/** `apiFetchRaw` returns the response untouched, so an unread body pins its connection. */
const discardBody = async (response: Response): Promise<void> => {
try {
await response.body?.cancel();
@@ -150,35 +92,20 @@ interface VideoDTOSubset {
export type AssetResponseReader = (response: Response, signal?: AbortSignal) => Promise<Uint8Array>;
-const createAssetResponseByteWriter = () => {
- const chunks: Uint8Array[] = [];
- let byteLength = 0;
-
- return {
- finish: () => {
- if (chunks.length === 0) {
- return new Uint8Array();
- }
-
- if (chunks.length === 1) {
- return chunks[0]!;
- }
+const concatChunks = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array => {
+ if (chunks.length < 2) {
+ return chunks[0] ?? new Uint8Array();
+ }
- const bytes = new Uint8Array(byteLength);
- let offset = 0;
+ const bytes = new Uint8Array(byteLength);
+ let offset = 0;
- for (const chunk of chunks) {
- bytes.set(chunk, offset);
- offset += chunk.byteLength;
- }
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
- return bytes;
- },
- write: (chunk: Uint8Array) => {
- chunks.push(chunk);
- byteLength += chunk.byteLength;
- },
- };
+ return bytes;
};
const getDeclaredContentLength = (response: Response): number | null => {
@@ -194,9 +121,8 @@ const getDeclaredContentLength = (response: Response): number | null => {
};
/**
- * A single export-scoped reader. Every response is streamed through the same
- * fixed byte budget, so both one hostile response and many individually-small
- * responses stop before they can materialize an oversized project in memory.
+ * A single export-scoped reader: every response streams through one fixed byte budget, so neither a
+ * hostile response nor many small ones can materialize an oversized project in memory.
*/
export const createAssetResponseReader = (): AssetResponseReader => {
type AssetStreamReader = ReadableStreamDefaultReader<Uint8Array>;
@@ -263,7 +189,8 @@ export const createAssetResponseReader = (): AssetResponseReader => {
return refuseBeforeReading(refuseTooLarge(`Project assets exceed ${INVK_MAX_ARCHIVE_BYTES} bytes.`));
}
- const writer = createAssetResponseByteWriter();
+ const chunks: Uint8Array[] = [];
+ let chunkBytesTotal = 0;
let remainingReservation = declaredByteLength ?? 0;
let responseBytes = 0;
@@ -272,7 +199,7 @@ export const createAssetResponseReader = (): AssetResponseReader => {
if (body === null) {
reservedBytes -= remainingReservation;
- return writer.finish();
+ return concatChunks(chunks, chunkBytesTotal);
}
const reader = body.getReader();
@@ -303,7 +230,7 @@ export const createAssetResponseReader = (): AssetResponseReader => {
reservedBytes -= remainingReservation;
remainingReservation = 0;
- return writer.finish();
+ return concatChunks(chunks, chunkBytesTotal);
}
const chunkBytes = result.value.byteLength;
@@ -322,7 +249,8 @@ export const createAssetResponseReader = (): AssetResponseReader => {
usedBytes += chunkBytes;
reservedBytes -= reservationConsumed;
remainingReservation -= reservationConsumed;
- writer.write(result.value);
+ chunks.push(result.value);
+ chunkBytesTotal += chunkBytes;
}
} catch (error) {
usedBytes -= responseBytes;
@@ -343,26 +271,16 @@ export const createAssetResponseReader = (): AssetResponseReader => {
};
};
-/**
- * Which of `imageNames` the server already has. The endpoint silently omits
- * names it cannot serve, which is exactly the answer wanted here: anything
- * missing from the response has to come out of the archive.
- */
+/** Which of `imageNames` the server already has; anything omitted must come out of the archive. */
export const findExistingImageNames = async (
imageNames: readonly string[],
signal?: AbortSignal
): Promise<Set<string>> => {
- const batches: string[][] = [];
-
- for (let offset = 0; offset < imageNames.length; offset += EXISTENCE_BATCH_SIZE) {
- batches.push(imageNames.slice(offset, offset + EXISTENCE_BATCH_SIZE));
- }
-
// Through the same pool as everything else. Splitting the names was meant to stop one slow
// lookup stalling the check, which a sequential loop gives straight back.
const found = await mapWithConcurrency(
- batches,
- EXISTENCE_BATCH_CONCURRENCY,
+ toBatches(imageNames, EXISTENCE_BATCH_SIZE),
+ INVK_TRANSFER_CONCURRENCY,
(batch) =>
apiFetchJson<ImageDTOSubset[]>(`${IMAGES_BASE}/images_by_names`, {
body: JSON.stringify({ image_names: batch }),
@@ -376,11 +294,8 @@ export const findExistingImageNames = async (
};
/**
- * Which of `videoNames` the server already has.
- *
- * There is no bulk equivalent of `images_by_names` for videos, so this asks per
- * name behind a concurrency limit. A 404 is the answer, not an error — the whole
- * question is which names are absent.
+ * Which of `videoNames` the server already has. No bulk equivalent of `images_by_names` exists for
+ * videos, so this asks per name; a 404 is the answer, not an error.
*/
export const findExistingVideoNames = async (
videoNames: readonly string[],
@@ -388,7 +303,7 @@ export const findExistingVideoNames = async (
): Promise<Set<string>> => {
const found = await mapWithConcurrency(
videoNames,
- VIDEO_EXISTENCE_CONCURRENCY,
+ INVK_TRANSFER_CONCURRENCY,
async (videoName) => {
const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}`, { signal });
@@ -414,44 +329,43 @@ export const findExistingVideoNames = async (
};
/**
- * Full-resolution bytes for one image, or `null` when the server will not serve
- * it. A missing asset is not an export failure: the previous frontend logged and
- * skipped, and a project that exports every layer but one is far more use than
- * one that refuses to export at all.
+ * Bytes for one asset, or `null` when the server will not serve it. A missing asset is not an export
+ * failure: a project that exports every layer but one is far more use than one that refuses.
*/
-const fetchImageBytesWithReader = async (
- imageName: string,
+const fetchAsset = async (
+ url: string,
signal: AbortSignal | undefined,
readResponse: AssetResponseReader
-): Promise<Uint8Array | null> => {
- const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/full`, { signal });
+): Promise<{ bytes: Uint8Array; contentType: string | null } | null> => {
+ const response = await apiFetchRaw(url, { signal });
if (!response.ok) {
await discardBody(response);
return null;
}
- return readResponse(response, signal);
+ return { bytes: await readResponse(response, signal), contentType: response.headers.get('content-type') };
};
+const assetUrl = (base: string, name: string, variant: 'full' | 'thumbnail'): string =>
+ `${base}/i/${encodeURIComponent(name)}/${variant}`;
+
+const fetchImageBytesWithReader = async (
+ imageName: string,
+ signal: AbortSignal | undefined,
+ readResponse: AssetResponseReader
+): Promise<Uint8Array | null> =>
+ (await fetchAsset(assetUrl(IMAGES_BASE, imageName, 'full'), signal, readResponse))?.bytes ?? null;
+
export const fetchImageBytes = (imageName: string, signal?: AbortSignal): Promise<Uint8Array | null> =>
fetchImageBytesWithReader(imageName, signal, createAssetResponseReader());
-/** The same, for a video. */
const fetchVideoBytesWithReader = async (
videoName: string,
signal: AbortSignal | undefined,
readResponse: AssetResponseReader
-): Promise<Uint8Array | null> => {
- const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}/full`, { signal });
-
- if (!response.ok) {
- await discardBody(response);
- return null;
- }
-
- return readResponse(response, signal);
-};
+): Promise<Uint8Array | null> =>
+ (await fetchAsset(assetUrl(VIDEOS_BASE, videoName, 'full'), signal, readResponse))?.bytes ?? null;
export const fetchVideoBytes = (videoName: string, signal?: AbortSignal): Promise<Uint8Array | null> =>
fetchVideoBytesWithReader(videoName, signal, createAssetResponseReader());
@@ -462,23 +376,14 @@ export interface FetchedThumbnail {
contentType: string;
}
-/** Thumbnail bytes for the cover entry. `null` when the server will not serve it. */
const fetchImageThumbnailWithReader = async (
imageName: string,
signal: AbortSignal | undefined,
readResponse: AssetResponseReader
): Promise<FetchedThumbnail | null> => {
- const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/thumbnail`, { signal });
-
- if (!response.ok) {
- await discardBody(response);
- return null;
- }
+ const fetched = await fetchAsset(assetUrl(IMAGES_BASE, imageName, 'thumbnail'), signal, readResponse);
- return {
- bytes: await readResponse(response, signal),
- contentType: response.headers.get('content-type') ?? 'image/webp',
- };
+ return fetched === null ? null : { bytes: fetched.bytes, contentType: fetched.contentType ?? 'image/webp' };
};
export const fetchImageThumbnail = (imageName: string, signal?: AbortSignal): Promise<FetchedThumbnail | null> =>
@@ -499,53 +404,75 @@ export const createAssetExportTransport = () => {
};
/**
- * Put archived bytes back on the server. The returned name is authoritative and
- * frequently differs from the archived one — the server names images itself —
- * which is why every import ends with a remapping pass.
+ * Put bytes on the server. The returned name is authoritative and frequently differs from the one
+ * asked for — the server names media itself — which is why every import ends with a remapping pass.
+ *
+ * A board upload's name is a genuinely new identity, always — see the `board_images` rule in
+ * `transfer.ts`.
*/
-export const uploadArchiveImage = async (
+const uploadMedia = async <T>(
+ base: string,
+ query: Record<string, string>,
bytes: Uint8Array,
fileName: string,
- options: { contentType?: string; signal?: AbortSignal } = {}
-): Promise<UploadedImage> => {
- const query = new URLSearchParams({ image_category: 'other', is_intermediate: 'false' });
+ defaultContentType: string,
+ options: { contentType?: string; signal?: AbortSignal }
+): Promise<T> => {
const body = new FormData();
- body.append(
- 'file',
- new File([bytes as BlobPart], fileName, { type: options.contentType || 'application/octet-stream' })
- );
+ body.append('file', new File([bytes as BlobPart], fileName, { type: options.contentType || defaultContentType }));
- const response = await apiFetch(`${IMAGES_BASE}/upload?${query.toString()}`, {
+ const response = await apiFetch(`${base}/upload?${new URLSearchParams(query).toString()}`, {
body,
method: 'POST',
signal: options.signal,
});
- const dto = (await response.json()) as ImageDTOSubset;
- return { height: dto.height, imageName: dto.image_name, width: dto.width };
+ return (await response.json()) as T;
};
-/** The same, for a video. Dimensions are not read: nothing in the document needs them. */
-export const uploadArchiveVideo = async (
+const IMAGE_UPLOAD_MIME = 'application/octet-stream';
+const VIDEO_UPLOAD_MIME = 'video/mp4';
+
+/** Dimensions travel for images because the document needs them; nothing needs a video's. */
+const toUploadedImage = (dto: ImageDTOSubset): UploadedImage => ({
+ height: dto.height,
+ imageName: dto.image_name,
+ width: dto.width,
+});
+
+export const uploadArchiveImage = async (
bytes: Uint8Array,
fileName: string,
options: { contentType?: string; signal?: AbortSignal } = {}
-): Promise<UploadedVideo> => {
- const query = new URLSearchParams({ is_intermediate: 'false', video_category: 'other' });
- const body = new FormData();
-
- body.append('file', new File([bytes as BlobPart], fileName, { type: options.contentType || 'video/mp4' }));
-
- const response = await apiFetch(`${VIDEOS_BASE}/upload?${query.toString()}`, {
- body,
- method: 'POST',
- signal: options.signal,
- });
- const dto = (await response.json()) as VideoDTOSubset;
+): Promise<UploadedImage> =>
+ toUploadedImage(
+ await uploadMedia<ImageDTOSubset>(
+ IMAGES_BASE,
+ { image_category: 'other', is_intermediate: 'false' },
+ bytes,
+ fileName,
+ IMAGE_UPLOAD_MIME,
+ options
+ )
+ );
- return { videoName: dto.video_name };
-};
+export const uploadArchiveVideo = async (
+ bytes: Uint8Array,
+ fileName: string,
+ options: { contentType?: string; signal?: AbortSignal } = {}
+): Promise<UploadedVideo> => ({
+ videoName: (
+ await uploadMedia<VideoDTOSubset>(
+ VIDEOS_BASE,
+ { is_intermediate: 'false', video_category: 'other' },
+ bytes,
+ fileName,
+ VIDEO_UPLOAD_MIME,
+ options
+ )
+ ).video_name,
+});
export interface BoardUploadOptions {
/** The project's staging board. Board media is never uploaded unboarded. */
@@ -556,66 +483,38 @@ export interface BoardUploadOptions {
signal?: AbortSignal;
}
-/**
- * Put one of the project board's images back, under its archived category and on
- * the staging board the new project is about to claim.
- *
- * The returned name is a genuinely new identity, always — `board_images` has
- * `PRIMARY KEY (image_name)`, so an image sits on exactly one board and a restore
- * that reused an existing name would be moving a stranger's picture onto this
- * project's board rather than copying it.
- */
export const uploadBoardImage = async (
bytes: Uint8Array,
fileName: string,
options: BoardUploadOptions
-): Promise<UploadedImage> => {
- const query = new URLSearchParams({
- board_id: options.boardId,
- image_category: options.category,
- is_intermediate: 'false',
- });
- const body = new FormData();
-
- body.append(
- 'file',
- new File([bytes as BlobPart], fileName, { type: options.contentType || 'application/octet-stream' })
+): Promise<UploadedImage> =>
+ toUploadedImage(
+ await uploadMedia<ImageDTOSubset>(
+ IMAGES_BASE,
+ { board_id: options.boardId, image_category: options.category, is_intermediate: 'false' },
+ bytes,
+ fileName,
+ IMAGE_UPLOAD_MIME,
+ options
+ )
);
- const response = await apiFetch(`${IMAGES_BASE}/upload?${query.toString()}`, {
- body,
- method: 'POST',
- signal: options.signal,
- });
- const dto = (await response.json()) as ImageDTOSubset;
-
- return { height: dto.height, imageName: dto.image_name, width: dto.width };
-};
-
-/** The same, for one of the board's videos. */
export const uploadBoardVideo = async (
bytes: Uint8Array,
fileName: string,
options: BoardUploadOptions
-): Promise<UploadedVideo> => {
- const query = new URLSearchParams({
- board_id: options.boardId,
- is_intermediate: 'false',
- video_category: options.category,
- });
- const body = new FormData();
-
- body.append('file', new File([bytes as BlobPart], fileName, { type: options.contentType || 'video/mp4' }));
-
- const response = await apiFetch(`${VIDEOS_BASE}/upload?${query.toString()}`, {
- body,
- method: 'POST',
- signal: options.signal,
- });
- const dto = (await response.json()) as VideoDTOSubset;
-
- return { videoName: dto.video_name };
-};
+): Promise<UploadedVideo> => ({
+ videoName: (
+ await uploadMedia<VideoDTOSubset>(
+ VIDEOS_BASE,
+ { board_id: options.boardId, is_intermediate: 'false', video_category: options.category },
+ bytes,
+ fileName,
+ VIDEO_UPLOAD_MIME,
+ options
+ )
+ ).video_name,
+});
/** One copy the server made, under the identity it assigned. */
export interface CopiedMedia {
@@ -658,9 +557,9 @@ const copyMediaToBoard = async <Entry>({
}
try {
- // Do not abort an in-flight copy request. The server performs synchronous work and may have
- // created identities even after the browser disconnects; retaining its response is the only
- // way the restore ledger can remove them. Cancellation is honored between bounded requests.
+ // Deliberately unaborted: the server works synchronously and may create identities after the
+ // browser disconnects, and its response is the only way the ledger learns to remove them.
+ // Cancellation is honoured between requests instead.
const body = await apiFetchJson<{ copied?: Entry[]; failed?: string[] }>(endpoint, {
body: JSON.stringify({ board_id: boardId, [requestKey]: batch }),
method: 'POST',
@@ -685,14 +584,8 @@ const copyMediaToBoard = async <Entry>({
};
/**
- * Copy media onto a board without the bytes leaving the server.
- *
- * Duplication needs new identities for the same reason import does — `board_images` keys on the
- * image name — but both projects live on this one server, so round-tripping the pixels through the
- * browser would cost twice the board's size in traffic, two requests per item, and would run into
- * the same cumulative budget that bounds an export. The endpoint carries category, origin and the
- * metadata embedded in the PNG; starring is not part of a copy, so callers star afterwards through
- * the same path an import uses.
+ * Copy media onto a board without the bytes leaving the server. Carries category, origin and
+ * embedded metadata; starring is not part of a copy, so callers star afterwards.
*/
export const copyImagesToBoard = (
imageNames: readonly string[],
@@ -729,14 +622,8 @@ export interface BulkStarResult {
}
/**
- * What a bulk star actually achieved.
- *
- * Both endpoints answer with the names they *did* star, and only the video one
- * also lists failures — a name it skipped (a foreign one, or one deleted between
- * the upload and the star) appears in neither list. Deriving the failures from
- * the success list rather than reading `failed_*` therefore covers both routes
- * with one rule, and the rule is the honest one: anything not reported as starred
- * did not get starred.
+ * Failures are derived from the success list, not read from `failed_*`: only the video endpoint
+ * reports failures, and a name it silently skipped appears in neither list.
*/
const toBulkStarResult = (requested: readonly string[], starred: readonly string[]): BulkStarResult => {
const succeeded = new Set(starred);
@@ -788,15 +675,10 @@ export const starVideos = async (videoNames: readonly string[], signal?: AbortSi
};
/**
- * An unclaimed private board for a restore to upload into, which project creation
- * then claims and renames.
+ * An unclaimed private board for a restore to upload into, which project creation then claims.
*
- * Creating the project first would mean posting it with the old asset names and
- * then updating it with the remapped ones, making the *update* the commit point:
- * a failure there leaves a real project full of references to media that never
- * arrived. Staging inverts that — the media is in place before the project
- * exists, and the create either claims the board and its contents or leaves
- * nothing a person can see.
+ * This is what makes the create the commit point: the media is in place before the project exists,
+ * so the create either claims the board and its contents or leaves nothing a person can see.
*/
export const createStagingBoard = async (boardName: string, signal?: AbortSignal): Promise<string> => {
const query = new URLSearchParams({ board_name: boardName.slice(0, MAX_BOARD_NAME_LENGTH) });
@@ -809,12 +691,9 @@ export const createStagingBoard = async (boardName: string, signal?: AbortSignal
};
/**
- * Drop a staging board whose project was never created.
- *
- * `include_images=false` deliberately: the restore deletes the identities it
- * created itself, one by one, and anything else that wandered onto the board in
- * the meantime — a generation that finished while the import ran — must survive
- * as Uncategorized rather than be collected by a cleanup that never meant it.
+ * Drop a staging board whose project was never created. `include_images=false` deliberately: the
+ * restore deletes its own identities one by one, and a generation that landed on the board
+ * meanwhile must survive as Uncategorized.
*/
export const deleteStagingBoard = async (boardId: string, signal?: AbortSignal): Promise<void> => {
await apiFetchJson<unknown>(`${BOARDS_BASE}/${encodeURIComponent(boardId)}?include_images=false`, {
@@ -883,11 +762,7 @@ const IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
webp: 'image/webp',
};
-/**
- * Only MP4 survives the backend's upload path — it probes the container and
- * 415s anything else (`_is_mp4_file` in `videos.py`) — so this is a table of
- * what a bundled entry might be *named*, not of what will be accepted.
- */
+/** What a bundled entry might be *named*; only MP4 survives the backend's `_is_mp4_file` probe. */
const VIDEO_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
m4v: 'video/mp4',
mkv: 'video/x-matroska',
@@ -897,14 +772,8 @@ const VIDEO_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
};
/**
- * Best guess at a bundled entry's MIME type, from its name and the folder it
- * came out of. Only ever a hint for the upload's multipart part.
- *
- * The fallback is per kind because the receiving endpoint checks it. A video
- * whose extension is not in the table falling back to `image/png` would be
- * announced to `/videos/upload` as an image and refused before its bytes were
- * ever read — the entry's folder already established what it is, so the guess
- * should never contradict it.
+ * Best guess at a bundled entry's MIME type. The fallback is per kind because the endpoint checks
+ * it: an unknown video extension falling back to `image/png` would be refused by `/videos/upload`.
*/
export const mimeForEntryName = (entryName: string, kind: 'image' | 'video' = 'image'): string => {
const extension = entryName.split('.').pop()?.toLowerCase() ?? '';
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
index 8607b08019..ed0df91194 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
@@ -26,74 +26,27 @@ import {
import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './transfer';
/**
- * Putting a project's media on this server, for whichever direction needs it.
- *
- * Import and duplication ask the same question — "make this project's media exist here, under
- * identities this project owns" — and differ in exactly one step: where the bytes come from.
- * Import has them in the archive; duplication has them already on this server and copies them
- * without a byte ever reaching the browser. That step is {@link MediaMaterializer}, and everything
- * around it — planning, remapping, starring, issue reporting, the rollback ledger — is shared.
- *
- * ### Board media always gets a new identity; document references may be reused
- *
- * `board_images` has `PRIMARY KEY (image_name)`: an image sits on exactly one board. A restore that
- * saw its own name already on the destination and reused it would not be restoring the project's
- * board, it would be *moving* somebody else's image onto it — and deleting either project's board
- * would then take that image from both. So every board item is materialized fresh, with no
- * existence check, and the document is rewritten to the new name.
- *
- * Document-only references are pointers rather than membership, so an image the destination already
- * has satisfies them. That is the v2 behaviour and it is still right: it is what makes re-importing
- * your own export nearly free instead of doubling your disk.
+ * Putting a project's media on this server, for whichever direction needs it. Import and
+ * duplication differ in exactly one step — where the bytes come from, {@link MediaMaterializer} —
+ * and share everything around it.
*
* ### A failed board item must not resolve to a stranger
*
- * The dangerous case is an item that is *both* on the board and named by the document, whose
- * materialization fails. Leaving the reference on the old name is not "no worse than before": on the
- * same server — every duplication, and every re-import — that name is already taken, by the source
- * project's own image. The project would open showing the right picture from the wrong owner, and
- * deleting the original would break it with no explanation. So a failed board item forces its
- * document references onto {@link buildMissingMediaName}, which resolves to nothing and renders as
- * a missing layer, exactly as a dangling v2 reference already does.
+ * An item both on the board and named by the document, whose materialization fails, must not keep
+ * its old name: on the same server that name is already taken, by the *source* project's image, so
+ * the project would open showing the right picture from the wrong owner. Failed items are forced
+ * onto {@link buildMissingMediaName}, which resolves to nothing and renders as a missing layer.
*
- * "Named by the document" means anywhere in it. `remapAssetRefs` walks the whole document; the live
- * reference set does not, because `collectLiveAssetRefs` skips history — `recentImages`, canvas
- * snapshots, the queue. So the placeholder is written for every failed item, and the live set decides
- * only what is worth *reporting*: a gallery recent that stops resolving is not something the person
- * lost from this project, and counting it would inflate every report.
+ * The placeholder is written for every failed item, because `remapAssetRefs` walks the whole
+ * document. The live reference set — which skips history — decides only what is worth *reporting*:
+ * a gallery recent that stops resolving is not something the person lost from this project.
*/
/**
- * A `catch` handler that degrades to `fallback`, except for the errors that must end the restore.
- *
- * Nothing in a restore is worth the whole restore. Starring is a flag; an existence probe only
- * spares a redundant upload. A batch of either failing should cost what it is worth, not reach the
- * caller's rollback and delete every asset that had already arrived.
- *
- * Cancellation is the exception, and has to be, because it is not a failure of the call: an aborted
- * signal or a rotated account makes *every* remaining call fail. Degrading those would report the
- * project as half-restored and then create it anyway.
- */
-/**
- * Hold a check's outcome — value or failure — so an early-started promise cannot become an
- * unhandled rejection while the restore is busy elsewhere.
+ * Degrade to `fallback`, except for cancellation. Starring is a flag and an existence probe only
+ * spares an upload — neither is worth reaching the caller's rollback. Cancellation is the
+ * exception because it makes *every* remaining call fail, which is not a half-restored project.
*/
-type SettledExisting = { names: Set<string> } | { error: unknown };
-
-const settleExisting = (promise: Promise<Set<string>>): Promise<SettledExisting> =>
- promise.then(
- (names) => ({ names }),
- (error: unknown) => ({ error })
- );
-
-const unwrapExisting = (settled: SettledExisting): Set<string> => {
- if ('error' in settled) {
- throw settled.error;
- }
-
- return settled.names;
-};
-
const degradeUnlessCancelled =
<T>(fallback: T) =>
(error: unknown): T => {
@@ -126,11 +79,8 @@ export interface MaterializeResult {
}
/**
- * Make board media exist on `boardId`, however this direction gets its bytes.
- *
- * `onItemSettled` is called once per descriptor, succeeded or failed. Restoring a board is the bulk
- * of an import's wall time, so a progress count that only moved once the whole board was done would
- * sit at zero through the part people actually wait for.
+ * Make board media exist on `boardId`, however this direction gets its bytes. `onItemSettled` fires
+ * once per descriptor, so progress moves through the part people actually wait for.
*/
export type MediaMaterializer = (
items: readonly InvkBoardItem[],
@@ -139,11 +89,8 @@ export type MediaMaterializer = (
) => Promise<MaterializeResult>;
/**
- * Every identity a restore created, so a failure can undo exactly what it did and nothing else.
- *
- * Filled in as the restore runs rather than returned at the end: a restore that throws part way —
- * a cancelled signal, an account rotation — has still created things, and a ledger only handed back
- * on success would leave them behind.
+ * Every identity a restore created, so a failure can undo exactly what it did. Filled in as it
+ * runs, not returned at the end: a restore that throws part way has still created things.
*/
export interface RestoredMediaLedger {
/** The staging board these were created on, when this restore created one. */
@@ -227,19 +174,11 @@ interface RestoreKindAdapter {
upload: (bytes: Uint8Array, name: string, signal?: AbortSignal) => Promise<string>;
}
-const emptyMaterializeResult = (): MaterializeResult => ({ failed: [], materialized: [] });
-
/**
- * The cover, preferring an image the restore already put on this server.
- *
- * The archive's `cover` entry is a thumbnail of an image the document also references, and
- * `getProjectCoverUrl` asks for a thumbnail anyway — so once that image is restored, pointing the
- * index at it is the same picture without a second copy. Uploading the entry unconditionally
- * instead left one orphan per import: covers go up under the canvas's private `'other'` category,
- * which appears in no gallery view and no board count, so nobody could ever find or delete them.
- *
- * The bundled bytes are the fallback, for the case that made them worth carrying: a cover whose
- * source image is dangling here.
+ * The cover, preferring an image the restore already put here — the same picture without a second
+ * copy. Uploading the bundled entry unconditionally left one orphan per import, in the private
+ * `'other'` category where nobody could find or delete it. The bytes are the fallback, for a cover
+ * whose source image is dangling.
*/
const resolveCoverImageName = async (input: {
coverBytes: { bytes: Uint8Array; entryName: string } | null;
@@ -279,11 +218,9 @@ const resolveCoverImageName = async (input: {
};
/**
- * Restore a project's media and report what could not be carried.
- *
- * Nothing here throws for a media failure — a project that opens with two broken layers is worth
- * far more than no project at all — so the only rejections are the ones that end the whole
- * operation: a cancelled signal, an expired account.
+ * Restore a project's media and report what could not be carried. Nothing throws for a media
+ * failure; the only rejections are the ones that end the operation — cancellation, an expired
+ * account.
*/
export const restoreProjectMedia = async (
input: RestoreProjectMediaInput,
@@ -303,12 +240,9 @@ export const restoreProjectMedia = async (
/** Descriptor position, so a placeholder name does not depend on the order failures happened in. */
const descriptorIndexes = new Map(input.boardItems.map((item, index) => [toMediaKey(item), index]));
/**
- * A distinct placeholder index for every failed name.
- *
- * Descriptor position is the stable answer and is used wherever it exists. A materializer that
- * reports a failure for a name that was never a descriptor has no position — and collapsing those
- * onto one index would give two unrelated missing items the same placeholder, quietly merging
- * them into a single dangling reference. Counting past the descriptors keeps them apart.
+ * Descriptor position where it exists; counting past the descriptors otherwise. Collapsing
+ * position-less failures onto one index would merge two unrelated missing items into a single
+ * dangling reference.
*/
let nextUnknownIndex = input.boardItems.length;
const missingNameIndex = (key: string): number => {
@@ -367,32 +301,25 @@ export const restoreProjectMedia = async (
},
};
- // Started before the board upload, awaited after it. The existence checks depend only on the
- // document's own references, which are known here — and the board upload is the minutes-long part
- // of a large import, so waiting it out first meant the video probe, which is one request per
- // name, began only once everything else had finished.
- //
- // An empty answer is the safe degradation: the check exists only to skip uploading something the
- // destination already has, so failing it costs bandwidth, never correctness. Aborting the import
- // over it would be losing the project to save a request.
+ // Started before the board upload, awaited after it: the probes need only the document's own
+ // references, and the board upload is the minutes-long part. An empty answer degrades safely —
+ // the check only skips redundant uploads, so failing it costs bandwidth, never correctness.
//
- // Settled rather than left to reject: a promise started here but not awaited until after the
- // board upload would surface as an unhandled rejection if the upload threw first. Cancellation
- // still ends the restore — it is re-thrown at the await below, in its proper order.
- const existingImagesPromise = settleExisting(
+ // `allSettled` is constructed here, not at the await: a promise started now and awaited after the
+ // upload would surface as an unhandled rejection if the upload threw first. Cancellation still
+ // ends the restore, re-thrown at the await below in its proper order.
+ const settledProbes = Promise.allSettled([
documentOnlyImages.length === 0
? Promise.resolve(new Set<string>())
- : checkExistingImages(documentOnlyImages, deps.signal).catch(degradeUnlessCancelled(new Set<string>()))
- );
- const existingVideosPromise = settleExisting(
+ : checkExistingImages(documentOnlyImages, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),
documentOnlyVideos.length === 0
? Promise.resolve(new Set<string>())
- : checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>()))
- );
+ : checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),
+ ]);
const boardResult =
stagingBoardId === null
- ? emptyMaterializeResult()
+ ? ({ failed: [], materialized: [] } satisfies MaterializeResult)
: await deps.materializeBoardMedia(input.boardItems, stagingBoardId, advance);
const starTargets = { image: [] as string[], video: [] as string[] };
@@ -429,12 +356,9 @@ export const restoreProjectMedia = async (
settledBoardKeys.add(key);
issues.addBoardItemIssue(failure, failure.reason);
- // Mapped unconditionally, because `remapAssetRefs` rewrites the *whole* document while
- // `documentKeys` describes only its live references — `collectLiveAssetRefs` deliberately skips
- // `recentImages`, `snapshots` and the queue. A name left unmapped therefore survives in history,
- // and on this server that name is already taken: by the source project's own image. The copy
- // would open showing the right picture from the wrong owner, and deleting the original would
- // break it with no explanation. Every occurrence goes to the placeholder instead.
+ // Mapped unconditionally: `remapAssetRefs` rewrites the whole document while `documentKeys`
+ // covers only live references, so a name left unmapped survives in history — pointing, on this
+ // server, at the source project's own image.
kindAdapters[failure.kind].mapping.set(
failure.name,
buildMissingMediaName(input.projectId, failure.kind, missingNameIndex(key))
@@ -451,22 +375,16 @@ export const restoreProjectMedia = async (
failBoardItem(failure);
}
- // A descriptor the materializer reported neither way is a failure too. Silently dropping it would
- // leave its document reference on the old name, which is the one outcome this module exists to
- // prevent.
+ // A descriptor reported neither way is a failure too: dropping it silently would leave its
+ // document reference on the old name.
for (const item of input.boardItems) {
if (!settledBoardKeys.has(toMediaKey(item))) {
failBoardItem({ kind: item.kind, name: item.name, reason: 'upload-failed' });
}
}
- // Starring is a separate call by design: the same one import and duplication use, and the same
- // one the gallery uses. A star that fails costs a flag, not the media, so it is reported against
- // the board item and nowhere else — the document does not care whether a layer is starred.
- //
- // Which is why the call itself must not reject: a rejection here reaches the caller's rollback
- // and deletes every image that was just uploaded, over a flag. A whole batch that failed to send
- // is every name in it failing to be starred.
+ // A failed star costs a flag, not the media, so it must not reject: a rejection here reaches the
+ // caller's rollback and deletes every image just uploaded, over a flag.
const [imageStars, videoStars] = await Promise.all([
starRestoredImages(starTargets.image, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.image })),
starRestoredVideos(starTargets.video, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.video })),
@@ -483,9 +401,13 @@ export const restoreProjectMedia = async (
}
}
- const [existingImages, existingVideos] = (await Promise.all([existingImagesPromise, existingVideosPromise])).map(
- unwrapExisting
- ) as [Set<string>, Set<string>];
+ const [existingImages, existingVideos] = (await settledProbes).map((settled) => {
+ if (settled.status === 'rejected') {
+ throw settled.reason;
+ }
+
+ return settled.value;
+ }) as [Set<string>, Set<string>];
const pending: PendingUpload[] = [];
const plannedTotal = total;
@@ -525,9 +447,8 @@ export const restoreProjectMedia = async (
const { kind, name } = item;
const bytes = item.bytes;
- // Dropped from the queue before the request, not after: the upload body holds its own
- // reference for as long as it needs one, and the queue was the reason a restore of a large
- // project held every asset it had not sent yet.
+ // Dropped before the request, not after: the upload body holds its own reference, and this
+ // queue was why a large restore held every asset it had not sent yet.
item.bytes = null;
if (bytes === null) {
@@ -545,9 +466,8 @@ export const restoreProjectMedia = async (
adapter.mapping.set(name, restoredName);
}
} catch (error) {
- // Not a failure of this asset: an aborted signal or an expired account makes every remaining
- // upload fail too, and reporting them one by one would finish with a warning naming hundreds
- // of dangling references and a project created anyway.
+ // Not a failure of this asset: cancellation makes every remaining upload fail too, and
+ // reporting them one by one would name hundreds of dangling references.
if (isRequestCancellation(error)) {
throw error;
}
@@ -579,20 +499,10 @@ export const restoreProjectMedia = async (
/**
* Run a restore's rollback, but only when the project it was staging certainly does not exist.
- *
- * Both directions of this — import and duplication — got here the same way and get it wrong the
- * same way, so the decision lives once. Three things have to hold before anything is deleted:
- *
- * - the create did not already succeed, because after that the media belongs to a real project;
- * - the failure is one that proves the project is absent, which is what
- * {@link ProjectCreateAbsentError} means and why the create goes through `createProjectSettled`
- * rather than a bare `POST`. An unknown outcome must never authorize a deletion: the uploads are
- * recoverable clutter, whereas a project stripped of its media is not recoverable at all;
- * - the account has not changed underneath us, so the deletes are aimed at the right server and the
- * right person.
- *
- * The rollback itself is best-effort — the original failure is the actionable result and must not be
- * replaced by a message about a delete request nobody asked for.
+ * Three things must hold: the create did not already succeed; the failure *proves* absence, which
+ * is what {@link ProjectCreateAbsentError} means and why the create goes through
+ * `createProjectSettled`; and the account has not changed. An unknown outcome must never authorize
+ * a deletion — uploads are recoverable clutter, a project stripped of its media is not.
*/
export const rollbackUnlessProjectExists = async (
error: unknown,
@@ -619,14 +529,9 @@ export interface RollbackRestoredMediaDeps {
}
/**
- * Undo a restore whose project was never created — exactly the identities it made, then the board
- * it made them on.
- *
- * Best-effort throughout: the failure that brought us here is the actionable one, and a cleanup
- * that threw would replace it with a message about a delete request nobody asked for. The board
- * goes last and without `include_images`, so a generation that landed on the staging board while
- * the import ran survives as Uncategorized instead of being collected by a cleanup that never
- * meant it.
+ * Undo a restore whose project was never created — exactly the identities it made, then the board.
+ * Best-effort throughout, so a failing cleanup cannot replace the actionable error. The board goes
+ * last and without `include_images`; see {@link deleteStagingBoard}.
*/
export const rollbackRestoredMedia = async (
ledger: RestoredMediaLedger,
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
index 7d01b134ca..44d3693458 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts
@@ -305,7 +305,7 @@ describe('library mutations', () => {
});
});
- await library.readProjectForDuplication('source', account.accountLifecycle.capture());
+ await library.readAcknowledgedProject('source', account.accountLifecycle.capture());
expect(calls).toEqual(['flush', 'get']);
});
@@ -324,9 +324,10 @@ describe('library mutations', () => {
return Promise.resolve<ProjectPushOutcome>({ documentJson: '{}', kind: 'unsynced' });
});
- await expect(library.readProjectForDuplication('source', account.accountLifecycle.capture())).rejects.toMatchObject(
- { name: 'ProjectFlushError', reason: 'unsynced' }
- );
+ await expect(library.readAcknowledgedProject('source', account.accountLifecycle.capture())).rejects.toMatchObject({
+ name: 'ProjectFlushError',
+ reason: 'unsynced',
+ });
expect(calls).toEqual(['flush']);
expect(api.getProject).not.toHaveBeenCalled();
@@ -337,9 +338,9 @@ describe('library mutations', () => {
handle.flush.mockResolvedValue({ documentJson: '{}', kind: 'superseded' });
- await expect(library.readProjectForDuplication('source', account.accountLifecycle.capture())).rejects.toMatchObject(
- { reason: 'superseded' }
- );
+ await expect(library.readAcknowledgedProject('source', account.accountLifecycle.capture())).rejects.toMatchObject({
+ reason: 'superseded',
+ });
});
it('duplicates through the shared restore engine and adopts the copy', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.ts
index 285e2330f6..a4b6b90fb3 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts
@@ -196,12 +196,10 @@ export const upsertProjectSummary = (
};
/**
- * Every mutation below branches on one question: does the workbench currently hold this project?
- *
- * If it does, the mutation goes through {@link getOpenProject} — the sync engine — and if it does
- * not, it goes over HTTP. A library write landing beside an open project's revision chain used to
- * fork it into a conflict copy; now that a project's board renames with it, such a write would
- * rename the board too, from outside the transaction that is supposed to own both.
+ * Every mutation below branches on one question: does the workbench hold this project? If so it
+ * goes through {@link getOpenProject} — the sync engine — otherwise over HTTP. A library write
+ * landing beside an open project's revision chain forks it into a conflict copy, and now that a
+ * board renames with its project, would rename the board from outside the owning transaction.
*/
/** Permanently remove a project from the server, its board with it. The only deletion path. */
@@ -268,14 +266,12 @@ export const renameLibraryProject = async (projectId: string, name: string): Pro
};
/**
- * The acknowledged record for a project about to be copied.
- *
- * An open project is flushed first and the flush is fatal if it fails. Duplicating what the server
- * last acknowledged would silently drop everything the person can see on screen, and a copy that
- * quietly omits the last ten minutes of work is worse than no copy — so a flush that did not land,
- * or that landed under a different id, raises rather than letting the GET below answer for it.
+ * The server record for a project about to be copied or exported, flushed first when the editor
+ * holds it, and fatal if that flush does not land. The GET returns the last *acknowledged*
+ * document, so without this an unacknowledged push is indistinguishable from a successful one and
+ * the copy silently omits the last ten minutes of work under a success toast.
*/
-export const readProjectForDuplication = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {
+export const readAcknowledgedProject = async (projectId: string, owner: AccountScope): Promise<ProjectRecordDTO> => {
const openProject = getOpenProject(projectId);
if (openProject) {
@@ -301,20 +297,16 @@ export interface DuplicatedProject extends ProjectTransferIssues {
}
/**
- * Copy a project, its board and everything on it, under a fresh id.
- *
- * The board is enumerated before anything is created, and a failure to enumerate it aborts: a copy
- * whose board came back silently empty would look like a successful duplication of a project that
- * had produced nothing. The copying itself lives behind the lazy `invk/` boundary with import's
- * restore engine, which it shares — this is where the two directions meet, not a second
- * implementation of them.
+ * Copy a project, its board and everything on it, under a fresh id. Enumerating the board is fatal:
+ * a board that came back silently empty would look like a successful copy of a project that had
+ * produced nothing. The copying shares import's restore engine behind the lazy `invk/` boundary.
*/
export const duplicateLibraryProject = async (
projectId: string,
options: { onProgress?: (progress: { completed: number; total: number }) => void; owner?: AccountScope } = {}
): Promise<DuplicatedProject> => {
const owner = options.owner ?? captureAccountScope();
- const record = await readProjectForDuplication(projectId, owner);
+ const record = await readAcknowledgedProject(projectId, owner);
assertAccountScopeCurrent(owner);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index 0da365a7da..3d0e3dd9db 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -1,50 +1,24 @@
/**
* Which assets a project document points at, and how to rewrite those pointers.
*
- * The document stores pixels the way `canvas-engine/contracts.ts` describes:
- * by name, never by URL or inline data. That is what makes the document small
- * enough to autosave, and also what makes a bare document export useless on
- * another install — the names resolve to nothing there. Bundling the bytes into
- * an `.invk` archive means first knowing which names the document actually uses.
- *
- * ### Two kinds, kept apart
- *
- * Images and videos live in separate backend namespaces, with separate tables,
- * separate fetch and upload routes, and no shared name space. A document can
- * carry both — `video_name` reaches `projectGraph` through an imported workflow
- * whose node value was authored elsewhere (`VideoField` in the backend's
- * `fields.py`; webv2 cannot author one yet, but it round-trips one verbatim).
- * So collection returns a set per kind and remapping takes a mapping per kind:
- * an image and a video could in principle share a name, and a single flat map
- * would let one rewrite the other.
- *
* ### Collection is by key, not by path
*
- * Three keys in the document hold an asset name: `imageName` (the webv2 canvas
- * contracts), `image_name` and `video_name` (graph node values, which mirror the
- * backend's field naming). Collecting every string found at those keys is
- * complete by construction — a new control-adapter kind, a new node field, a
- * widget nobody has written yet, all get picked up without touching this file.
+ * Three keys hold an asset name: `imageName`, `image_name` and `video_name`. Collecting every
+ * string found at those keys is complete by construction — a new adapter kind or node field is
+ * picked up without touching this file. The legacy frontend walks a hand-written list of paths
+ * instead, which is why it enumerates `ip_adapter` and `flux_redux` by name and drops the pixels of
+ * anything added since. A false positive costs nothing: it fails to resolve and is skipped.
*
- * The alternative, walking a hand-written list of paths, is what the legacy
- * frontend does, and it is why its collector enumerates `ip_adapter` and
- * `flux_redux` by name and silently drops the pixels of any adapter added since.
- * A false positive here costs nothing: a string that is not really an asset name
- * fails to resolve on the server and is skipped.
+ * Images and videos get a set and a mapping each, because they are separate backend namespaces and
+ * could share a name — one flat map would let one rewrite the other.
*
* ### Collection skips history, remapping does not
*
- * A project document carries far more than the live document. Every queue entry
- * embeds a whole canvas snapshot, `canvas.snapshots` holds full document copies,
- * and the gallery widget keeps up to sixty recent results. Bundling all of that
- * turns a working project into a multi-gigabyte archive, so
- * {@link collectLiveAssetRefs} walks only what the project needs in order to
- * open correctly.
- *
- * {@link remapAssetRefs} walks everything, with no skips. The asymmetry is the
- * point: if a bundled asset comes back from the server under a new name, every
- * reference to it has to follow — including the ones in history we chose not to
- * bundle, which would otherwise point at the pre-import name forever.
+ * Queue entries embed whole canvas snapshots and the gallery keeps sixty recents, so bundling
+ * everything turns a working project into a multi-gigabyte archive; {@link collectLiveAssetRefs}
+ * walks only what the project needs to open. {@link remapAssetRefs} walks everything, because a
+ * renamed asset's references must all follow — including the history we chose not to bundle, which
+ * would otherwise point at the pre-import name forever.
*/
/** Keys whose string values name an image. */
@@ -60,29 +34,12 @@ export const PROJECT_HISTORY_ROOT_KEYS: ReadonlySet<string> = new Set(['events',
export const PROJECT_HISTORY_KEYS: ReadonlySet<string> = new Set(['recentImages', 'snapshot', 'snapshots']);
/**
- * The gallery widget's selection: pointers into gallery content rather than
- * anything the document renders. `selectedImage` holds a whole polymorphic
- * `GalleryItem` (image or video), the two name keys hold `"<kind>:<name>"`, and
- * `compareImage` holds the image the Preview widget is comparing against.
+ * The gallery widget's selection: per-install content, so a project arriving elsewhere opens with
+ * nothing selected rather than dragging a stranger's gallery behind it.
*
- * All are skipped deliberately. The gallery is per-install content: a project
- * that arrives on another machine should open with nothing selected, not drag a
- * stranger's gallery in behind it.
- *
- * Skipping them during collection is only half of that. A reference that is not
- * bundled and not stripped still travels — it simply travels broken, pointing at
- * an image the receiving server has never had, and import cannot even report it
- * as dangling because the same skip hides it from the restore pass.
- * {@link stripGallerySelection} is the other half, and the export planner
- * applies it before the document is serialized.
- *
- * The two halves got here differently, which is why the skip is by key rather
- * than left to chance. `selectedImage` and the name keys were already missed,
- * but only because `GalleryItem` spells its name field `name` and no collector
- * key matches it — an accident that renaming the field would have undone.
- * `compareImage` is a `GeneratedImageContract`, so it carries `imageName` and
- * was genuinely being bundled: excluding it is a real change, and the right one,
- * since a comparison someone happened to leave open is not part of the project.
+ * Skipping them during collection is only half of it — an unbundled, unstripped reference still
+ * travels, just broken, and the same skip hides it from the restore pass so import cannot even
+ * report it as dangling. {@link stripGallerySelection} is the other half.
*/
export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set([
'compareImage',
@@ -92,36 +49,24 @@ export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set([
]);
/**
- * Board ids the gallery widget holds: which board this project owns, and which
- * one new results are routed to. Both are *installation* state, not project
- * state — a board id means nothing on the machine the project arrives at.
+ * Board ids the gallery widget holds. Installation state, not project state: `projectBoardId` is a
+ * cache the server owns and hydration overwrites.
*
- * `projectBoardId` in particular is a cache, not a fact. The server owns the
- * project-to-board relationship, and hydration overwrites this from the project
- * record. Exporting it would carry a stale pointer to a board the receiving
- * install has never had, and importing it would fight the authoritative value
- * the create response is about to supply.
- *
- * Board ids elsewhere in the document — a workflow node's board input, say — are
- * semantically meaningful and are deliberately NOT stripped. That is why this
- * set names only the two keys the gallery widget owns.
+ * Board ids elsewhere in the document — a workflow node's board input — are meaningful and
+ * deliberately NOT stripped, which is why this names only the gallery widget's two keys.
*/
export const GALLERY_INSTALLATION_KEYS: ReadonlySet<string> = new Set(['projectBoardId', 'selectedBoardId']);
const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([...GALLERY_SELECTION_KEYS, ...GALLERY_INSTALLATION_KEYS]);
/**
- * URLs the document caches beside a media name, which name *this* install's server and this
- * install's copy of the media.
+ * URLs the document caches beside a media name, naming *this* install's copy.
*
- * They are installation state like the keys above, but they cannot be removed the way those are.
- * The persisted-recents validator (`getBoundedRecentImages`) requires both to be strings and drops
- * any entry missing one, so deleting them would silently discard the whole gallery-recents overlay
- * on import. Blanked instead: every consumer already falls back to deriving the URL from the media
- * name (`item.thumbnailUrl || item.fullUrl`, `slot.candidate.thumbnailUrl || galleryImageUrls…`),
- * which is the only correct answer once a transfer has renamed the media anyway. The name is
- * remapped; a URL built around the *old* name is not, and would keep resolving — to the source
- * project's picture.
+ * Blanked, not removed: `getBoundedRecentImages` requires both to be strings and drops any entry
+ * missing one, so deleting them would discard the whole gallery-recents overlay on import. Every
+ * consumer already falls back to deriving the URL from the name, which is the only correct answer
+ * once a transfer has renamed the media — the name is remapped, a URL built around the old one is
+ * not, and would keep resolving to the source project's picture.
*/
const DERIVED_URL_KEYS: ReadonlySet<string> = new Set(['imageUrl', 'thumbnailUrl', 'videoUrl']);
@@ -186,15 +131,24 @@ export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>):
return refs;
};
-const stripNode = (node: unknown): unknown => {
+/** `{ drop: true }` removes the key, `{ value }` replaces it, `null` recurses into it. */
+type NodeVisit = { drop: true } | { value: unknown } | null;
+
+/**
+ * Walk every entry of a project document at every depth, applying `visit`.
+ *
+ * Subtrees with nothing to change keep their identity, so a document that matches nothing comes
+ * back as the very same object rather than a structurally-equal copy.
+ */
+const mapDocument = (node: unknown, visit: (key: string, value: unknown) => NodeVisit): unknown => {
if (Array.isArray(node)) {
let hasChanged = false;
const next = node.map((item) => {
- const stripped = stripNode(item);
+ const mapped = mapDocument(item, visit);
- hasChanged ||= stripped !== item;
+ hasChanged ||= mapped !== item;
- return stripped;
+ return mapped;
});
return hasChanged ? next : node;
@@ -208,95 +162,49 @@ const stripNode = (node: unknown): unknown => {
const next: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
- if (INSTALLATION_STATE_KEYS.has(key)) {
- hasChanged = true;
+ const visited = visit(key, value);
+
+ if (visited === null) {
+ const mapped = mapDocument(value, visit);
+
+ next[key] = mapped;
+ hasChanged ||= mapped !== value;
continue;
}
- if (DERIVED_URL_KEYS.has(key) && typeof value === 'string') {
- next[key] = '';
- hasChanged ||= value !== '';
+ if ('drop' in visited) {
+ hasChanged = true;
continue;
}
- const stripped = stripNode(value);
-
- next[key] = stripped;
- hasChanged ||= stripped !== value;
+ next[key] = visited.value;
+ hasChanged ||= visited.value !== value;
}
return hasChanged ? next : node;
};
/**
- * Drop everything that describes *this install* rather than the project — the
- * gallery's selection, its board ids, and the URLs cached beside media names — at
- * every depth, so an exported project opens with nothing selected, on the board
- * the receiving server assigns it, resolving its pictures through the names it
- * actually owns.
+ * Drop everything describing *this install* rather than the project, at every depth.
*
- * Every reader of the selection and board values already tolerates their absence —
- * selection is parsed with `typeof`/`Array.isArray` guards and falls back to
- * nothing, and the board ids are re-supplied from the project record — so removing
- * the key is the same as clearing it, without inventing a shape. The cached URLs
- * are blanked rather than removed, for the reason {@link DERIVED_URL_KEYS} gives.
- * Subtrees with nothing to change keep their identity.
- *
- * Stripping by key at any depth rather than by walking into `widgetInstances` is
- * what makes this cover the legacy `widgetStates.gallery` shape for free, and it
- * is safe because these keys occur nowhere else in a project document.
+ * Removing a key is the same as clearing it here: every reader already tolerates absence. By key at
+ * any depth rather than by walking `widgetInstances`, which covers the legacy `widgetStates.gallery`
+ * shape for free and is safe because these keys occur nowhere else in a document.
*/
export const stripInstallationState = (projectDocument: Record<string, unknown>): Record<string, unknown> =>
- stripNode(projectDocument) as Record<string, unknown>;
+ mapDocument(projectDocument, (key, value) => {
+ if (INSTALLATION_STATE_KEYS.has(key)) {
+ return { drop: true };
+ }
+
+ return DERIVED_URL_KEYS.has(key) && typeof value === 'string' ? { value: '' } : null;
+ }) as Record<string, unknown>;
export interface ProjectAssetMappings {
images: ReadonlyMap<string, string>;
videos: ReadonlyMap<string, string>;
}
-const remapNode = (node: unknown, mappings: ProjectAssetMappings): unknown => {
- if (Array.isArray(node)) {
- let hasChanged = false;
- const next = node.map((item) => {
- const mapped = remapNode(item, mappings);
-
- hasChanged ||= mapped !== item;
-
- return mapped;
- });
-
- return hasChanged ? next : node;
- }
-
- if (!isRecord(node)) {
- return node;
- }
-
- let hasChanged = false;
- const next: Record<string, unknown> = {};
-
- for (const [key, value] of Object.entries(node)) {
- if (typeof value === 'string') {
- const mapping = IMAGE_NAME_KEYS.has(key) ? mappings.images : VIDEO_NAME_KEYS.has(key) ? mappings.videos : null;
-
- if (mapping) {
- const replacement = mapping.get(value);
-
- next[key] = replacement ?? value;
- hasChanged ||= replacement !== undefined && replacement !== value;
- continue;
- }
- }
-
- const mapped = remapNode(value, mappings);
-
- next[key] = mapped;
- hasChanged ||= mapped !== value;
- }
-
- return hasChanged ? next : node;
-};
-
/**
* Rewrite every asset reference in the document through the mapping for its
* kind. Names absent from their mapping are left alone, and subtrees with
@@ -309,7 +217,15 @@ export const remapAssetRefs = (
): Record<string, unknown> =>
mappings.images.size === 0 && mappings.videos.size === 0
? projectDocument
- : (remapNode(projectDocument, mappings) as Record<string, unknown>);
+ : (mapDocument(projectDocument, (key, value) => {
+ if (typeof value !== 'string') {
+ return null;
+ }
+
+ const mapping = IMAGE_NAME_KEYS.has(key) ? mappings.images : VIDEO_NAME_KEYS.has(key) ? mappings.videos : null;
+
+ return mapping === null ? null : { value: mapping.get(value) ?? value };
+ }) as Record<string, unknown>);
const readGalleryRecentImageName = (projectDocument: Record<string, unknown>): string | null => {
const instances = projectDocument.widgetInstances;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 4128502855..cd54b1cdd2 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -11,39 +11,26 @@ import {
import type { ProjectTransferIssues } from './invk/transfer';
-import {
- createProjectSettled,
- getProject as apiGetProject,
- getProjectBoardSnapshot,
- type ProjectRecordDTO,
-} from './api';
+import { createProjectSettled, getProjectBoardSnapshot, type ProjectRecordDTO } from './api';
import { recordProjectCover } from './covers';
import { createProjectId } from './ids';
import { INVK_EXTENSION, InvkFormatError } from './invk/format';
-import { upsertProjectSummary } from './library';
+import { readAcknowledgedProject, upsertProjectSummary } from './library';
import { remapAssetRefs, stripInstallationState } from './projectAssets';
-import { assertProjectFlushed } from './projectFlush';
-import { getOpenProject } from './syncStore';
-export const PROJECT_FILE_KIND = 'invokeai-project';
-export const PROJECT_FILE_VERSION = 1;
export const LEGACY_PROJECT_FILE_EXTENSION = '.invokeproject.json';
-export interface ProjectFile {
+const PROJECT_FILE_KIND = 'invokeai-project';
+const PROJECT_FILE_VERSION = 1;
+
+/** The JSON envelope shipped before `.invk`. Read only — nothing writes one any more. */
+interface ProjectFile {
document: Record<string, unknown>;
exportedAt: string;
kind: typeof PROJECT_FILE_KIND;
version: typeof PROJECT_FILE_VERSION;
}
-/** Kept for callers that still construct the JSON envelope shipped before `.invk`. */
-export const buildProjectFile = (projectDocument: Record<string, unknown>): ProjectFile => ({
- document: projectDocument,
- exportedAt: new Date().toISOString(),
- kind: PROJECT_FILE_KIND,
- version: PROJECT_FILE_VERSION,
-});
-
/** Returns the embedded legacy document, or null when the text is not one of our exports. */
export const parseProjectFile = (text: string): Record<string, unknown> | null => {
try {
@@ -67,44 +54,15 @@ export const parseProjectFile = (text: string): Record<string, unknown> | null =
};
/**
- * Export and import a project as an `.invk` archive.
- *
- * This module is the workflow; `./invk` is the format. The split matters
- * because the two have different reasons to change: the archive layout is a
- * compatibility surface shared with the previous frontend, while what an export
- * means here — which project, under whose account, landing where — is app
- * behavior.
- *
- * ### Why an archive and not a JSON file
- *
- * A project document references its pixels by server image name. Exporting the
- * document alone produced a file that opened perfectly on the machine that
- * wrote it and showed nothing but missing layers anywhere else. An `.invk`
- * carries the bytes, so the file is the project rather than a description of it.
+ * Export and import a project as an `.invk` archive. This module is the workflow; `./invk` is the
+ * format.
*
- * ### Import never overwrites
+ * An imported document gets a fresh id, never the one in the file: two people exchanging a project
+ * would otherwise collide the moment both saved.
*
- * An imported document gets a fresh id, never the one in the file. Two people
- * exchanging a project would otherwise collide the moment both saved, and
- * re-importing your own export would silently replace the original.
- *
- * The heavy halves — the ZIP codec and the workbench reducer — are both loaded
- * with `await import()`. The Launchpad offers Import and Export on a route that
- * never mounts the editor, and it should not pay for either until someone
- * actually picks a file.
- *
- * ### Both directions report as they go, and report what they lost
- *
- * A project file is the one operation here whose duration is set by how much
- * someone has drawn: a few hundred full-resolution layers is a few hundred
- * round trips and hundreds of megabytes. Silence for that long reads as a
- * broken button, so {@link ProjectFileProgress} is reported throughout.
- *
- * Both directions can also half-succeed. Export skips an asset the server will
- * not serve; import leaves a reference dangling when the archive did not carry
- * it and this server does not have it. Both were computed and discarded before,
- * which made a project that lost forty layers indistinguishable from a clean
- * round trip. They are returned now, and every call site says so.
+ * The ZIP codec and the workbench reducer are both `await import()`ed. The Launchpad offers Import
+ * and Export on a route that never mounts the editor, and should not pay for either until someone
+ * picks a file.
*/
/**
@@ -196,32 +154,13 @@ const exportProjectDocument = async (
};
};
-/**
- * Export a project from its server record.
- *
- * Flushed first when the editor holds it, for the reason duplication is: the surfaces that call
- * this — a project card, a gallery board's menu — are reachable while that project is open, and the
- * board most likely to be right-clicked is the open project's own. Exporting what the server last
- * acknowledged would hand someone a file that silently omits the last ten minutes of their work.
- *
- * A flush that does not land therefore ends the export. The archive is built from the record read
- * below, so an unacknowledged push means the file would be wrong in exactly the way this call
- * exists to prevent — and wrong invisibly, under a download and a success toast.
- */
+/** Export a project from its server record, flushing it first — see {@link readAcknowledgedProject}. */
export const exportLibraryProject = async (
projectId: string,
options: ProjectFileOptions = {}
): Promise<ProjectExportOutcome> => {
const owner = options.owner ?? captureAccountScope();
- const openProject = getOpenProject(projectId);
-
- if (openProject) {
- assertProjectFlushed(await openProject.flush());
- }
-
- assertAccountScopeCurrent(owner);
-
- const record = await apiGetProject(projectId, owner.signal);
+ const record = await readAcknowledgedProject(projectId, owner);
assertAccountScopeCurrent(owner);
@@ -245,24 +184,12 @@ export const exportOpenProject = async (
};
/**
- * Import an `.invk` as a new server project: restore its media, rewrite every
- * reference the server renamed, then create the project — claiming the board its
- * media was staged on, in the same request. Throws {@link InvkFormatError} so
- * callers can translate the reason rather than surface an internal message.
- *
- * ### Creating the project is the commit point
- *
- * Everything before it is either free to abandon or cleaned up: the document is
- * canonicalized before a board exists, the board is created before any media is
- * uploaded, and the create either claims that board with its contents or leaves
- * nothing a person can see. The alternative — create the project, upload, then
- * update it with the remapped names — makes the *update* the commit point, and a
- * failure there leaves a real project full of references to media that never
- * arrived.
+ * Import an `.invk` as a new server project: restore its media, rewrite every reference the server
+ * renamed, then create the project — claiming its staging board in the same request. Throws
+ * {@link InvkFormatError} so callers can translate the reason.
*
- * A v2 archive and a legacy JSON document have no board to stage, so they create
- * no staging board and the server gives the new project an empty one, exactly as
- * it does for a project made from scratch.
+ * Creating the project is the commit point; see {@link createStagingBoard}. A v2 archive or a
+ * legacy JSON document stages no board, and the server gives the new project an empty one.
*/
export const importProjectFile = async (
file: File,