Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(projects): cut narrative comments back to their reasons
Josh Corbett78666c286bae
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.pyindex 3183f5da53..d2674e768c 100644--- a/invokeai/app/services/image_files/image_files_disk.py+++ b/invokeai/app/services/image_files/image_files_disk.py@@ -190,14 +190,9 @@ class DiskImageFileStorage(ImageFileStorageBase):) -> None:"""Duplicate an image's files under a new name, without decoding them.- A copy is byte-identical, so `shutil.copy2` is both the cheapest way to make one and the- most faithful: every PNG chunk travels, including ones this application does not parse and- would silently drop on a re-encode. Going through `save()` instead would decode and- re-encode the pixels — hundreds of milliseconds and a fresh compression pass per image, to- arrive at the same picture.-- Nothing is cached here. The source's cache entry belongs to the source, and a copy nobody- has read yet has no business occupying a slot.+ `shutil.copy2` is both cheapest and most faithful: every PNG chunk travels, including ones+ this application does not parse and would drop on a re-encode. Nothing is cached — a copy+ nobody has read yet has no business occupying a slot."""try:self.__validate_storage_folders()diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.pyindex 55b6d03cec..359e5bcd76 100644--- a/invokeai/app/services/images/images_default.py+++ b/invokeai/app/services/images/images_default.py@@ -120,24 +120,16 @@ class ImageService(ImageServiceABC):) -> ImageDTO:"""Duplicate an existing image under a new identity, optionally onto a board.- Duplicating a project needs genuinely new identities — `board_images` keys on- `image_name`, so one image sits on exactly one board — but the *picture* is the same- picture. So the record is cloned from the source's record and the file is copied byte for- byte. Nothing is decoded, nothing is re-encoded, and the embedded metadata, workflow and- graph travel because they are chunks in the file rather than something re-derived here.+ New identity, same picture: the record is cloned and the file copied byte for byte, so+ embedded metadata, workflow and graph travel as file chunks rather than being re-derived.+ The copy is never intermediate, and starring is not copied.- The copy is never intermediate: an intermediate is a step in someone else's run, and a- copy is a thing a person asked for. Starring is not copied either — callers that want it- use the same star route the gallery uses.-- Attaching to the board is checked *before* the file is written, where the video twin writes- the file first and removes it again on discovering the attachment was lost. Both are fatal- and both leave nothing behind; the orders differ because `create` — which the video path- reuses — swallows a failed attachment, so there it can only be detected after the fact.+ Board attachment is checked *before* the file is written, where the video twin writes first+ and withdraws on failure. The orders differ because `create` — which the video path reuses —+ swallows a failed attachment, so there it can only be detected after the fact.Nothing partial survives a failure: the unwind covers everything after the record exists,- including reading the DTO back, and removes the file as well as the row. A row whose file- endpoints 404 is a broken gallery entry; a file with no row is disk nobody can reach.+ including reading the DTO back, and removes the file as well as the row."""try:record = self.__invoker.services.image_records.get(source_image_name)diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex d7bf368369..c5459d3fab 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -35,11 +35,7 @@ export interface ProjectCreateRequest {project_id?: string;/*** An existing unclaimed private board for the new project to adopt, renamed to match. Omit to- * have the server create one.- *- * Restoring a project uploads its media into such a board first and passes it here, which makes- * creating the project the single commit point for an import: the media is in place before the- * project exists, and a create that fails leaves no half-built project behind.+ * have the server create one. This is what makes the create an import's single commit point.*/board_id?: string;name: string;@@ -124,22 +120,17 @@ export class ProjectCreateAbsentError extends Error {/*** Create a project, resolving the one outcome a bare `POST` cannot report: a create that reached- * the server but whose response did not reach us.+ * the server but whose response did not reach us. Getting that wrong orphans a board's worth of+ * already-uploaded media, or *deletes* it out from under a project that does exist.*- * This matters because the caller has already uploaded a board's worth of media by the time it runs.- * Getting the answer wrong in one direction orphans those uploads; in the other it *deletes* them,- * out from under a project that does exist, leaving every reference in its document dangling.- *- * A read cannot decide it. `GET` on the chosen id returns 404 while the create transaction is still- * committing, which is exactly the window a dropped connection leaves open — so the probe reports- * "absent" about a project that is moments from existing. A write can: SQLite has a single writer,- * so a second `POST` cannot commit before the first one finishes, and its answer is about a settled- * database rather than one mid-transaction.+ * A read cannot decide it — `GET` returns 404 while the create transaction is still committing,+ * exactly the window a dropped connection leaves open. A write can: SQLite has a single writer, so+ * a second `POST` cannot commit before the first finishes and its answer is about a settled+ * database.** - `201` — the first attempt never landed and this one did.- * - `409` — the retry ran to completion against the server, so the follow-up `GET` is no longer- * racing anything: a record means the first create committed and is adopted; a 404 means the id is- * genuinely free and something else (another importer holding the staging board) refused this.+ * - `409` — the retry ran to completion, so the follow-up `GET` races nothing: a record means the+ * first create committed and is adopted; a 404 means something else holds the staging board.* - any other deterministic rejection — the server answered, and answered no.* - another transport failure — still unknown, and unknown must not authorize deletion.*/diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.tsindex 7df59f65d1..a3239626fa 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.ts@@ -11,39 +11,20 @@ import { absolutizeApiUrl } from '@platform/transport/http';import { getClientStateValue, setClientStateValue } from './api';/**- * Which image stands for each project, as an index in the per-user client-state- * KV — the same place the editor session lives (`session.ts`).+ * Which image stands for each project, as an index in the per-user client-state KV.*- * The project document is the source of truth: `selectCoverImageName` derives a- * cover from the newest result or the top-most canvas layer, and an `.invk`- * carries those bytes as its `cover` entry. But the library grid lists projects- * from `GET /projects`, which returns summaries with no document — deriving a- * cover there would mean fetching every project's document to render a page of- * thumbnails. So the answer is written down once, when a project is saved or- * imported, and read back as one small blob.- *- * Being an index and not a truth, it is allowed to be stale or incomplete. A- * project saved by a build without this has no entry and shows the folder glyph,- * which is also what a project that has produced nothing shows — the absence is- * already a state `ProjectCover` handles.- *- * Writes are skipped when the value has not changed, which is almost always: a- * cover changes when a generation lands, not on every autosave.+ * The document is the source of truth, but the library grid lists projects from `GET /projects`,+ * which returns summaries with no document. So the answer is written down once, on save or import.+ * Being an index, it is allowed to be stale: a project with no entry shows the folder glyph.** ### The whole index is one value, so a write must not precede a read*- * The KV holds one blob and `setClientStateValue` replaces it outright. Writing- * from a store that has not loaded would therefore not add an entry — it would- * delete every entry but the one being written.+ * The KV holds one blob and `setClientStateValue` replaces it outright, so writing from a store+ * that has not loaded would delete every entry but the one being written. Not hypothetical:+ * autosave reaches {@link recordProjectCover} from the editor, which loads the index only when the+ * switcher or Open dialog opens. Records made before the load wait in {@link pendingCoverNames}.*- * That ordering is not hypothetical. Autosave reaches {@link recordProjectCover}- * from the editor, which loads the index only when the project switcher or the- * Open dialog is opened; someone who reloads straight into a project and- * generates has never loaded it. So a record made before the load is held in- * {@link pendingCoverNames}, applied on top of the server's answer once it- * arrives, and persisted then. A read that *fails* is not a read: the store- * stays unloaded and the pending records wait, because merging onto a blank- * answer is the same destructive write by another route.+ * A read that *fails* is not a read — merging onto a blank answer is the same destructive write.*/export const PROJECT_COVERS_KEY = 'webv2:project-covers';@@ -68,11 +49,7 @@ const EMPTY: ProjectCoversSnapshot = { coverImageNames: {}, isDirty: false, isLoconst store = createExternalStore<ProjectCoversSnapshot>(EMPTY);let mutationQueue: CoverMutationQueue | null = null;-/**- * Covers recorded before the index loaded, newest write per project. Drained by- * {@link loadProjectCovers} — see the module docblock for why they cannot be- * persisted where they are made.- */+/** Covers recorded before the index loaded, newest per project. Drained by {@link loadProjectCovers}. */const pendingCoverNames = new Map<string, string | null>();registerAccountOwnedResource({@@ -123,9 +100,8 @@ const enqueuePersist = (coverImageNames: Record<string, string>, owner: AccountStry {await setClientStateValue(PROJECT_COVERS_KEY, value, owner.signal);} catch {- // A cover is a thumbnail on a card. Losing the write costs a glyph until- // the next save, which is not worth surfacing to anyone. Keeping the- // snapshot dirty lets the next matching save retry the complete blob.+ // Losing the write costs a glyph until the next save. Keeping the snapshot dirty is what+ // lets that save retry the complete blob.return;}@@ -139,8 +115,7 @@ const enqueuePersist = (coverImageNames: Record<string, string>, owner: AccountS/*** Trim to the cap, oldest first. Insertion order is recency order because- * {@link recordProjectCover} re-inserts the project it touches, so the entry- * being written can never be the one evicted.+ * {@link recordProjectCover} re-inserts what it touches, so the entry being written is never evicted.*/const boundCovers = (coverImageNames: Record<string, string>): Record<string, string> => {const entries = Object.entries(coverImageNames);@@ -164,9 +139,8 @@ export const loadProjectCovers = (): Promise<void> => {try {raw = await getClientStateValue(PROJECT_COVERS_KEY, owner.signal);} catch {- // Not "no covers yet": a failed read leaves the store unloaded so that- // nothing writes over an index we were unable to see. The next refresh- // tries again, and any pending records wait for it.+ // Not "no covers yet": a failed read leaves the store unloaded so nothing writes over an+ // index we could not see. Pending records wait for the next refresh.return;}@@ -207,10 +181,7 @@ export const getProjectCoverImageName = (projectId: string): string | undefinedexport const subscribeProjectCovers = store.subscribe;-/**- * Record (or clear) a project's cover. A no-op when nothing changed, which is- * the common case on autosave.- */+/** Record (or clear) a project's cover. A no-op when nothing changed — the autosave case. */export const recordProjectCover = (projectId: string,coverImageName: string | null,@@ -228,9 +199,8 @@ export const recordProjectCover = (const next = { ...coverImageNames };- // Deleted before it is set, so an existing project moves to the end: the cap- // below evicts in insertion order, and the entry being written now is the one- // that must survive it.+ // Deleted before it is set, so the project moves to the end and survives the insertion-order+ // eviction below.delete next[projectId];if (coverImageName !== null) {@@ -258,10 +228,6 @@ export const forgetProjectCover = (projectId: string, owner: AccountScope = captrecordProjectCover(projectId, null, owner);};-/**- * Thumbnail URL for a cover image name. Built here rather than imported from- * `@features/gallery/core/imagePaths`, which is private to that feature; the- * palette's provider does the same for the same reason.- */+/** Built here rather than imported from `@features/gallery`, which is private to that feature. */export const getProjectCoverUrl = (coverImageName: string): string =>absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(coverImageName)}/thumbnail`);diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.tsindex 46928a1ac9..bf1790a472 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts@@ -1,54 +1,29 @@import { INVK_MIME_TYPE, InvkFormatError } from './format';/**- * The ZIP seam. The only module in the app that knows `.invk` is a ZIP, and the- * only one that imports fflate.+ * The ZIP seam. The only module that knows `.invk` is a ZIP, and the only one that imports fflate —+ * lazily, so a route that never opens a project file never pays for it.*- * fflate is loaded with `await import()` at call time, exactly as `psdExport.ts`- * loads ag-psd and `wildcardFiles.ts` loads `yaml`. Reading or writing a project- * file is a deliberate, occasional act; the bytes that make it possible have no- * business in the graph a person downloads to look at their projects. The- * architecture budget enforces this — a new package appearing in a route's- * initial chunk fails the gate on the source-owner set alone, before anyone- * looks at kilobytes.+ * JSON entries are deflated, image entries stored: bitmaps are already PNG or WEBP, while the+ * document is repetitive JSON that compresses tenfold.*- * ### Compression+ * ### Why the read guard lives in fflate's filter*- * JSON entries are deflated; image entries are stored. Layer bitmaps and- * generated results are already PNG or WEBP, so deflating them spends CPU- * proportional to the archive to save a fraction of a percent. The project- * document, by contrast, is repetitive JSON that routinely compresses tenfold.+ * `unzip` is fully buffered — by the time it returns, every entry is already inflated in memory, so+ * a total measured there is a postmortem rather than a guard. The filter is consulted per entry+ * *before* inflation, using the central directory's declared size, which is the only place a+ * ceiling can actually stop a zip bomb.*- * ### Guards- *- * Both directions are bounded. An `.invk` is a file someone was handed, and an- * unbounded `unzip` on a hostile one is a way to be handed an out-of-memory- * crash instead of an error message.- *- * Reading enforces its budget in fflate's entry filter rather than after the- * fact. `unzip` is fully buffered — by the time it hands back a record of- * entries, every one of them has already been inflated into memory, so a total- * measured there is a postmortem, not a guard. The filter is consulted per- * entry *before* inflation, with the declared uncompressed size from the- * central directory, which is the only place a ceiling can actually stop a zip- * bomb rather than describe one.- *- * fflate allocates deflated entries from `originalSize`, but stored entries- * from `size`. Stored ZIP entries must declare those sizes identically; the- * filter rejects a mismatch before fflate can copy the payload.+ * fflate allocates deflated entries from `originalSize` but stored entries from `size`. Stored+ * entries must declare those identically, so the filter rejects a mismatch before the copy.*//**- * Ceiling for a single archive, in either direction. Large enough for a real- * project with hundreds of full-resolution layers and a video or two; small- * enough that a malicious file fails fast rather than exhausting the tab.+ * Ceiling for a single archive, in either direction.*- * Deliberately well under 4 GiB. That is where ZIP32's 32-bit sizes and offsets- * stop being able to describe the file, and fflate writes no zip64 records — it- * reads them, but `zip()` has no path that emits them — so an archive at that- * boundary would be written structurally invalid rather than rejected. The- * browser gives out first anyway: `zip()` holds the entries and the packed- * output in memory at once.+ * Deliberately well under 4 GiB, where ZIP32's 32-bit sizes stop describing the file: fflate reads+ * zip64 records but `zip()` never emits them, so an archive at that boundary would be written+ * structurally invalid rather than rejected.*/export const INVK_MAX_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024;@@ -125,14 +100,9 @@ export interface InvkExpansionBudget {}/**- * The read-side ceiling, as a value the ZIP walk consults rather than a total- * measured afterwards.- *- * The refusal is *returned* rather than thrown from `accept`, because a throw- * inside fflate's own walk unwinds through its decoder and arrives as a decode- * failure — the caller would be told the file was not a project when what- * actually happened is that it was too big. Refusing the entry and reporting- * afterwards keeps the two reasons distinct while still inflating nothing.+ * The read-side ceiling, consulted during the walk. The refusal is *returned* rather than thrown+ * from `accept`: a throw inside fflate's walk unwinds through its decoder and arrives as a decode+ * failure, so the caller would be told the file was not a project when it was merely too big.*/export const createExpansionBudget = (): InvkExpansionBudget => {let entryCount = 0;diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.tsindex 574e4d1a36..2be6664d65 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts@@ -4,26 +4,19 @@ import { INVK_MAX_ENTRIES } from './archive';import { InvkFormatError } from './format';/**- * `board.json`: what was on the project's board when the archive was written.- *- * A project document names only the media it draws with. Everything else the project produced —- * results generated but never placed on canvas, uploads kept for later — is board membership and- * appears nowhere in the document, so a reader cannot infer it. This entry states it, and is the- * difference between an `.invk` carrying a project's canvas and carrying its workspace.+ * `board.json`: what was on the project's board when the archive was written. A document names only+ * the media it draws with, so everything else the project produced appears nowhere in it — this+ * entry is the difference between carrying a project's canvas and carrying its workspace.** ```json* { "version": 1, "items": [{ "category": "general", "kind": "image", "name": "…", "starred": false }] }* ```*- * The version here is the *file's*, not the API's. The board snapshot endpoint returns the same- * items but carries no version of its own, deliberately: an archive format that moved whenever the- * wire format did would be pinned to it forever, and vice versa.+ * The version is the *file's*, not the API's: an archive format pinned to the wire format would+ * have to move whenever it did, and vice versa.*- * Validation is strict and structural. A duplicate `(kind, name)` or a name that is not a plain- * basename is not a warning to be reported alongside the import — it means the file is malformed,- * and a malformed archive must be refused before anything is uploaded. Import cannot sensibly- * "partially trust" an enumeration: a name containing a path separator is either an attempt to- * write outside the archive's namespace or a bug, and neither is something to restore.+ * Validation is strict and structural — a duplicate `(kind, name)` or a non-basename name means the+ * file is malformed and must be refused before anything is uploaded, not reported alongside it.*/export type InvkMediaKind = 'image' | 'video';diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsindex 3c6576086c..3f02297b31 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -31,23 +31,14 @@ import {import { toMediaRefs } from './transfer';/**- * Duplicating a project: the same restore, with the bytes taking a shortcut.+ * Duplicating a project: the same restore as import, with the bytes taking a shortcut.*- * A copy has to own its media outright — `board_images` keys on the image name, so two projects- * cannot share a board image — which makes duplication the same problem as import: materialize the- * board under new identities, rewrite the document onto them, claim the staging board by creating- * the project. Only the materialization differs, and it differs because both projects live on this- * one server: the copy endpoints do it in place, so a 2 GiB board costs no traffic instead of 4 GiB- * and 2N requests through a browser tab.+ * A copy must own its media outright (see `transfer.ts`), which makes this import's problem. Only+ * materialization differs, and it differs because both projects live on this one server: the copy+ * endpoints work in place, so a 2 GiB board costs no traffic instead of 4 GiB and 2N requests.*- * Document-only references are the other half of that. They point at media that already exists here- * and is not the project's own board content, so the copy reuses the identities rather than- * duplicating them — the shared engine's existence check finds every one of them, and nothing is- * uploaded.- *- * What the previous implementation did was `POST` the source's document with a new id and name. It- * carried no media at all, so the copy's board was empty, and it did not canonicalize or strip- * installation state either — the copy inherited the original's board id and gallery selection.+ * Document-only references already exist here and are not the project's own board content, so the+ * shared engine's existence check finds them all and nothing is uploaded.*/export interface DuplicateProjectInput {@@ -71,17 +62,12 @@ export interface DuplicateProjectResult extends ProjectTransferIssues {}/**- * The duplication half of the materialization seam: one bounded request sequence per kind, and the- * pixels stay put.- *- * Progress moves per item once the sequence answers rather than during it. Each request is a- * synchronous server-side copy capped by the transport, so there is no finer event to report — and- * unlike an import, there is no browser upload to sit and watch.+ * The duplication half of the materialization seam: one bounded request sequence per kind, pixels+ * staying put. Progress moves per item once the sequence answers — there is no finer event.*- * A batch that does not answer at all — a proxy timing out a large board — is every name in it- * failing, not the duplication failing. The route reports per-item failures precisely so one bad- * source cannot cost the caller the batch; letting a transport error do what the route refuses to- * would give that guarantee away at the last step.+ * A batch that does not answer at all is every name in it failing, not the duplication failing:+ * the route reports per-item failures so one bad source cannot cost the batch, and letting a+ * transport error do what the route refuses would give that away at the last step.*/export const createCopyMediaMaterializer = (deps: { copyImages?: typeof copyImagesToBoard; copyVideos?: typeof copyVideosToBoard; signal?: AbortSignal } = {}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex 2a0bcf8b57..dfbd66c8e0 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -26,27 +26,14 @@ import { buildInvkManifest, toInvkFileName } from './manifest';import { createTransferIssueLog, planMediaTransfer, toMediaRefs } from './transfer';/**- * Writing an `.invk`, split into a pure planner and an impure executor the same- * way `canvas-engine/export/psdExport.ts` splits PSD export.+ * Writing an `.invk`, split into a pure planner and an impure executor, as+ * `canvas-engine/export/psdExport.ts` splits PSD export. {@link planInvkExport} decides what the+ * archive contains from the document alone, so that decision is a node test.*- * {@link planInvkExport} decides what the archive contains — entry names, which- * asset names to bundle and of which kind, which image becomes the cover — from- * the document alone. No network, no DOM, no fflate, so the interesting decision- * (what belongs in a project file) is a node test rather than a manual round trip.- *- * {@link executeInvkExport} does the parts that can fail: fetching each image,- * packing the ZIP, handing it to the browser.- *- * An image the server will not serve is logged in the result and skipped, never- * fatal. Half a project's pixels beats none, and the reference survives in the- * document either way — importing onto the machine that still has the image- * resolves it.- *- * Cancellation is the one failure that is *not* a skip. An aborted signal makes- * every asset unservable at once, and skipping all of them would pack an archive- * of nothing and hand it to the browser as a finished download. So a cancelled- * request propagates, and the signal is checked once more before the archive is- * written — nothing reaches the disk after the export stopped being wanted.+ * An unservable image is logged and skipped, never fatal. Cancellation is the one failure that is+ * *not* a skip: it makes every asset unservable at once, and skipping all of them would pack an+ * archive of nothing and hand it over as a finished download. The signal is checked once more+ * before the archive is written.*/export interface InvkExportPlan {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.tsindex 2748792f19..7670f6e46a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts@@ -1,27 +1,18 @@/*** What an `.invk` is called and how reading one can fail.*- * Split from `manifest.ts`, which owns the zod schemas, because these few- * constants and the error class are needed *eagerly*: the file picker names the- * extension, and every import call site catches the error to translate its- * reason. The schema is needed only once someone has actually chosen a file.- * Keeping them apart is what lets the picker and the toast stay in the- * Launchpad's initial graph while zod and the parser stay behind the lazy- * import that pulls in the ZIP codec.+ * Split from `manifest.ts`, which owns the zod schemas, because these are needed *eagerly* — the+ * picker names the extension and every call site translates the error's reason. That is what keeps+ * zod and the ZIP codec behind the lazy import.*/export const INVK_EXTENSION = '.invk';export const INVK_MIME_TYPE = 'application/zip';/**- * Workbench projects are version 2 of this container; version 1 is the previous frontend's canvas- * project, which is refused by name.- *- * Board membership did not bump this. A version exists to tell a reader what it is allowed to- * assume about a file *someone else wrote*, and webv2 has not shipped — no v2 archive exists- * anywhere that predates `board.json`, so a version that distinguished them would describe a- * population of files with no members. An archive without the entry is still read (dev builds wrote- * some), and it means what its absence says: this file names no board.+ * Workbench projects are version 2; version 1 is the previous frontend's canvas project, refused by+ * name. Board membership did not bump this — webv2 has not shipped, so no v2 archive predating+ * `board.json` exists outside dev builds, and an archive without the entry names no board.*/export const INVK_VERSION = 2;@@ -29,27 +20,14 @@ export const INVK_VERSION = 2;export const INVK_MANIFEST_ENTRY = 'manifest.json';export const INVK_DOCUMENT_ENTRY = 'project.json';-/**- * The project board's contents, as the exporting server enumerated them.- *- * A project document only references the media it draws with. Everything else the project produced- * — results generated but never placed on canvas — is on its board and named nowhere in the- * document, so a reader has no way to infer it. This entry states it, which is what makes an- * `.invk` the project's workspace rather than only its canvas.- */+/** The project board's contents; see `board.ts` for why a reader cannot infer them. */export const INVK_BOARD_ENTRY = 'board.json';/**- * Bundled bytes are filed by kind, not pooled. Images and videos are separate- * backend namespaces with separate fetch and upload routes, so import has to- * know which an entry is before it can restore it — and a folder states that- * where a shared one would leave it to be guessed from a file extension.- *- * `images/` is also byte-identical to the legacy v1 container, which is the- * continuity this format was built around. Adding `videos/` needs no version- * bump: `readInvkArchive` ignores entries it does not recognize, so a reader- * predating videos reads such an archive and simply leaves those references- * dangling — the same degradation an absent image already gets.+ * Filed by kind, not pooled: import must know which namespace an entry belongs to, and a folder+ * states it where a shared one would leave it to a file extension. `images/` is byte-identical to+ * the legacy v1 container. `videos/` needed no version bump — `readInvkArchive` ignores entries it+ * does not recognize, so an older reader just leaves those references dangling.*/export const INVK_IMAGES_PREFIX = 'images/';export const INVK_VIDEOS_PREFIX = 'videos/';diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex 514109b29a..573be1b121 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -34,27 +34,16 @@ import { toMediaRefs } from './transfer';/*** Reading an `.invk` back, in two steps a caller can put a decision between.*- * {@link readInvkArchive} is pure inspection: unpack, validate the manifest, parse the document and- * the board enumeration, then index the bundled bytes. It touches no network and mutates nothing, so- * a caller can read a file, discover it is a legacy canvas project, and say so without having- * created anything. Everything structural fails here, before a board or a single uploaded image- * exists.- *- * {@link restoreArchiveMedia} is the part with consequences. It is a thin wiring of- * `restoreProjectMedia`, which is shared with duplication: this module supplies the one thing that- * differs, namely that the bytes come out of the archive.- *- * Neither touches the document. The caller applies the returned mapping, because the caller is also- * the one assigning the new project id.+ * {@link readInvkArchive} is pure inspection — no network, no mutation — so everything structural+ * fails before a board or a single uploaded image exists. {@link restoreArchiveMedia} is the part+ * with consequences. Neither touches the document: the caller applies the returned mapping,+ * because the caller is also the one assigning the new project id.*/export interface InvkArchiveContents {/**- * What the project's board held, or `null` for an archive that names no board.- *- * `null` and `{items: []}` are deliberately different answers. "This file does not describe a- * board" calls for the server to create an empty one; "this project's board was empty" is a fact- * the restore already knows. Only the first may have a board invented for it.+ * What the project's board held, or `null` for an archive that names no board. `null` and+ * `{items: []}` are different answers: only the first may have a board invented for it.*/boardSnapshot: InvkBoardSnapshot | null;/** Bundled preview bytes and the entry they came from, when the archive has one. */@@ -84,11 +73,8 @@ const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {};/**- * The board enumeration, or `null` when the archive carries none.- *- * Absent is a valid archive — a build from before project boards wrote one — but *malformed* is- * not: an enumeration that cannot be trusted has to fail before anything is created, because half- * of it is not a board.+ * The board enumeration, or `null` when the archive carries none. Absent is valid; *malformed* is+ * not, and must fail before anything is created — half an enumeration is not a board.*/const parseBoardEntry = (entries: ReadonlyMap<string, Uint8Array>): InvkBoardSnapshot | null => {const entry = entries.get(INVK_BOARD_ENTRY);@@ -109,12 +95,9 @@ const parseBoardEntry = (entries: ReadonlyMap<string, Uint8Array>): InvkBoardSna};/**- * The part of `images/<name>` that is a name, or `null` for anything that is not.- *- * A ZIP path is attacker-controlled text. `images/../../x.png` and `images/nested/x.png` both have a- * remainder that is not a file name, and either would let an entry masquerade as media the board- * enumeration then asks for by name. Media names on the server never contain a separator, so the- * check costs nothing legitimate.+ * The part of `images/<name>` that is a name, or `null` otherwise. A ZIP path is attacker-controlled:+ * `images/../../x.png` would let an entry masquerade as media the board enumeration asks for by+ * name. Server media names never contain a separator, so the check costs nothing legitimate.*/const toSafeBasename = (path: string, prefix: string): string | null => {const name = path.slice(prefix.length);@@ -192,16 +175,12 @@ export interface ArchiveBoardUploadDeps {}/**- * The import half of the materialization seam: board media comes out of the archive.- *- * Every descriptor is uploaded, with no existence check — see `restoreProjectMedia` for why board- * media can never reuse a name the destination already has. A descriptor the archive carries no- * bytes for is reported rather than skipped silently: the exporting server told us it was there,- * so its absence is a loss worth naming.+ * The import half of the materialization seam: board media comes out of the archive. Uploaded with+ * no existence check — see `transfer.ts`. A descriptor the archive carries no bytes for is reported+ * rather than skipped: the exporting server said it was there.*- * Each entry is dropped from the archive as it lands. An `.invk` may be two gigabytes, and holding- * every entry until the import finishes means holding the whole archive *and* everything unpacked- * from it through the restore and the create that follows — for bytes the server already has.+ * Entries are dropped as they land. An `.invk` may be two gigabytes, and holding every one until+ * the import finishes means holding the archive *and* everything unpacked from it.*/export const createArchiveMediaMaterializer = (archive: Pick<InvkArchiveContents, 'images' | 'videos'>,@@ -270,11 +249,8 @@ export type RestoreArchiveMediaDeps = ArchiveBoardUploadDeps &Omit<RestoreProjectMediaDeps, 'documentMediaBytes' | 'materializeBoardMedia'>;/**- * Make an archive's media exist on this server: board items onto the staging board under fresh- * identities, document-only references deduplicated against what is already here.- *- * An archive that names no board restores its document references and nothing else — the shared- * engine simply sees an empty descriptor list.+ * Make an archive's media exist here: board items onto the staging board under fresh identities,+ * document-only references deduplicated against what is already present.*/export const restoreArchiveMedia = (archive: InvkArchiveContents,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.tsindex 3dbabf8769..f78dd45def 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts@@ -3,15 +3,9 @@ import { z } from 'zod';import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';/**- * The `.invk` manifest: what an archive is, before anything reads what is in it.- *- * `.invk` is not new. The canvas project files written by the previous frontend- * are ZIPs with this same root `manifest.json` — `{version, appVersion,- * createdAt, name}` — alongside an `images/` folder keyed by backend image name.- * That container is kept verbatim. Version 2 changes only the payload: where a- * v1 archive carried four canvas-shaped state files, a v2 archive carries one- * `project.json` holding the whole workbench project document, `board.json`- * describing the project's board, and an optional cover.+ * The `.invk` manifest. The previous frontend's canvas project files are ZIPs with this same root+ * `manifest.json` and `images/` folder; that container is kept verbatim, and version 2 changes only+ * the payload.** ```* <name>.invk@@ -23,21 +17,12 @@ import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';* └── videos/<video_name> the same, for the other namespace* ```*- * Parsing is a discriminated union rather than a strict `z.literal(2)` so that- * every version this app has written can be named precisely when refused. "This- * is a canvas project from an earlier version" is a sentence someone can act on;- * a zod issue list is not. The legacy reader is the mirror image — it pins- * `version: 1` and will refuse the others, which is correct and needs no change.- *- * Adding `board.json` did not bump the version, because a version tells a reader- * what it may assume about a file *someone else wrote* and no such file predates- * the entry — webv2 has not shipped. A reader treats the entry as optional and- * its absence as "this archive names no board", which is exactly what a dev build- * from before boards produced.+ * Parsed as a discriminated union rather than `z.literal(2)` so a refusal can name the version+ * precisely: "this is a canvas project from an earlier version" is actionable, a zod issue list is+ * not.*- * The names and the error class live in `./format`, which carries no zod, so- * that the file picker and the error toast do not drag the schema into the- * Launchpad's initial bundle.+ * Adding `board.json` did not bump the version — a version tells a reader what it may assume about+ * a file *someone else wrote*, and webv2 has not shipped. Readers treat the entry as optional.*/const zManifestV1 = z.object({diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.tsindex e5146eda5b..cd4a86bab3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts@@ -3,23 +3,18 @@ import type { ProjectAssetRefs } from '@workbench/projects/projectAssets';import type { InvkBoardItem, InvkMediaKind } from './board';/**- * The vocabulary shared by everything that moves a project's media: export, import, and- * duplication.+ * The vocabulary shared by export, import and duplication — and the one rule they all turn on.*- * All three face the same problem. A project's media comes from two places that overlap — the- * board, which is membership, and the document, which is references — and an item can be in- * either, or both. What must happen to it differs by which:+ * A project's media comes from two overlapping places, and what must happen differs by which:*- * - **Board membership** must be *copied*. `board_images` keys on the image name, so one image sits- * on exactly one board; a restored project that reused an existing name would be sharing another- * project's media, and deleting either board would take it from both.+ * - **Board membership** must be *copied*. `board_images` has `PRIMARY KEY (image_name)`, so one+ * image sits on exactly one board; reusing an existing name would *share* another project's+ * media, and deleting either board would take it from both.* - **Document references** may be *reused*. They are pointers, not membership, so an image the- * destination already has satisfies the reference without a second copy. This is the v2- * behaviour, and it is still right for media that lives outside the project's own board.+ * destination already has satisfies them without a second copy.*- * The consequence is the rule this module exists to encode: an item that is *both* is restored as- * board media, and its document references are rewritten to the copy. And when that copy fails, the- * reference must not be left pointing at the old name — see {@link buildMissingMediaName}.+ * So an item that is *both* is restored as board media and its references rewritten to the copy.+ * When that copy fails the reference must not keep the old name — see {@link buildMissingMediaName}.*//** One item, in whichever namespace it belongs to. */@@ -50,15 +45,9 @@ export interface InvkMediaIssue extends InvkMediaRef {}/**- * What a transfer could not carry, split by what it means to the person holding the file.- *- * A missing board item costs a result they can still see elsewhere. A missing document reference- * costs a layer in the canvas — the project opens with a hole in it. Reporting one number for both- * made "12 assets could not be included" mean anything from "nothing you will notice" to "the- * canvas is broken", so they are counted apart.- *- * An item that was both appears in both arrays. That is not double-counting: it genuinely failed- * in both roles.+ * What a transfer could not carry, counted apart: a missing board item costs a result still+ * findable elsewhere, a missing document reference costs a layer in the canvas. An item that was+ * both appears in both arrays — it genuinely failed in both roles.*/export interface ProjectTransferIssues {boardItemIssues: InvkMediaIssue[];@@ -105,11 +94,9 @@ export interface InvkTransferItem extends InvkMediaRef {}/**- * Merge board membership and document references into one list, each item appearing once.- *- * Fetching is the expensive half of an export and uploading the expensive half of an import, so an- * item that is both must be handled once, not twice — and the union is also what lets a single- * failure be reported correctly against both roles.+ * Merge board membership and document references into one list, each item once. An item that is+ * both must be fetched or uploaded once, and the union is what lets one failure be reported+ * against both roles.*/export const planMediaTransfer = (boardItems: readonly InvkBoardItem[],@@ -150,17 +137,11 @@ export const planMediaTransfer = (/*** A name guaranteed not to resolve, for a document reference whose board media could not be- * restored.- *- * Leaving the original name in place would be worse than a broken reference. Names are assigned by- * the exporting server, and the destination may well have its own image under that exact name —- * on the same server, during a duplication, it certainly does. The project would then open- * pointing at a stranger's picture, silently and plausibly, with nothing to indicate it is the- * wrong one. A reference that resolves to nothing is honest: it renders as a missing layer,- * exactly as a dangling v2 reference already does.+ * restored. Keeping the original would be worse: the destination may hold its own image under that+ * exact name — during a duplication it certainly does — so the project would open pointing at a+ * stranger's picture, plausibly and silently.*- * Derived from the new project id, so it is stable within one import (every occurrence of the old- * name maps to the same placeholder) and unique across imports.+ * Derived from the new project id, so it is stable within one import and unique across them.*/export const buildMissingMediaName = (projectId: string, kind: InvkMediaKind, index: number): string =>`${projectId}-missing-${kind}-${index}`;diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.tsindex ee4454f48c..261ab2a385 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts@@ -3,17 +3,11 @@ import type { ProjectPushOutcome } from './projectFlush';import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';/**- * Publishes one {@link OpenProjectHandle} per open tab, for the whole life of the mounted editor.+ * Publishes one {@link OpenProjectHandle} per open tab, for the life of the mounted editor.*- * The registry has to say exactly which projects the workbench holds, because that is what decides- * whether the library mutates a project through the sync engine or over HTTP — and a registry that- * disagreed with the tabs would put a write on the wrong side of the invariant. So it is derived- * from workbench state on every change rather than maintained by open and close call sites, which- * is a rule that cannot drift as new ways to open a project are added.- *- * The dependencies are plain functions rather than the store and the persistence service. This- * module belongs to the project layer, which the workbench shell wires up; taking the aggregates- * themselves would invert that.+ * Derived from workbench state on every change rather than maintained by open and close call sites:+ * the registry decides whether the library mutates through the sync engine or over HTTP, so one+ * that disagreed with the tabs would put a write on the wrong side of that invariant.*/export interface OpenProjectBrokerDeps {/** Drop the tab. Called after the project is already gone from the server. */@@ -60,11 +54,9 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjec/*** Publish the current open set, unregistering whatever is no longer in it.*- * Registration is unconditional rather than skipped for ids already published. The registry is- * cleared when the account changes, and a `published` set that believed it was still there would- * never re-register — silently sending every library mutation back over HTTP for the rest of the- * mount, which is the one thing this module exists to prevent. `published` therefore records only- * what to *retract*, and the registry stays the single source of what is currently published.+ * Registration is unconditional: the registry is cleared when the account changes, and a+ * `published` set that believed otherwise would never re-register, silently sending every library+ * mutation over HTTP for the rest of the mount. `published` records only what to *retract*.*/const sync = (): void => {const openIds = new Set(deps.getOpenProjectIds());diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.tsindex 2dd6cc50d2..5911be8911 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts@@ -2,29 +2,15 @@ import { InvkFormatError } from './invk/format';import { ProjectFlushError } from './projectFlush';/**- * Turn a failed project-file read or write into something worth showing.+ * Turn a failed project-file read or write into something worth showing. `InvkFormatError` carries+ * a `reason` rather than a message so the wording lives in the catalog and differs per failure: the+ * fix for a legacy canvas project is not the fix for a corrupt archive.*- * Every import entry point — Home, the Projects page, the in-editor Open dialog- * — used to pass `error.message` straight into a toast, which meant a person who- * picked the wrong file got a sentence written for a developer. `InvkFormatError`- * carries a `reason` instead of a message so the wording lives in the catalog- * and, importantly, says something different for each way this can go wrong:- * the fix for a legacy canvas project is not the fix for a corrupt archive.+ * `direction` matters for the two reasons both halves raise. Telling someone their project "is too+ * large to open" while they were exporting it names the wrong operation and the wrong file.*- * The direction matters for the two reasons both halves can raise. `too-large`- * comes from the export planner, the archive writer and the response reader as- * readily as from opening a file, and `damaged` is raised by duplication for a- * document that will not rehydrate. Telling someone their project "is too large- * to open" while they were exporting it names the wrong operation and the wrong- * file — theirs, not one they were handed.- *- * `ProjectFlushError` is the third case: not a bad file but a project whose- * newest content never reached the server, so there is nothing correct to- * export or copy yet. Its own message names the mechanism rather than the fix,- * which is the wrong half to show someone.- *- * Anything else reached us from the network or the reducer. Those already carry- * messages meant for people, so they pass through.+ * `ProjectFlushError` is not a bad file but a project whose newest content never reached the+ * server. Anything else already carries a message meant for people and passes through.*/export type ProjectFileDirection = 'read' | 'write';diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex 48d0c4c1a6..d5c6b27ccc 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -6,30 +6,11 @@ import type { ProjectFileProgress } from './projectFile';import { describeProjectFileError, type ProjectFileDirection } from './projectFileErrors';/**- * How a project file reports itself while it runs, and what it says when it is- * done.+ * One live toast per transfer, updated in place. No progress bar: the countable unit is assets and+ * the expensive one is bytes, so a bar drawn from the first would sit at 99% through the second.*- * Every entry point — Home, the Projects page, the in-editor Open dialog, the- * project switcher, each project card — used to start one of these and then say- * nothing until it either finished or threw. For an operation whose duration is- * set by how much someone has drawn, that is a long silence: a few hundred- * full-resolution layers is a few hundred round trips and hundreds of megabytes.- * A button that appears to do nothing for two minutes gets pressed again.- *- * The reporter is one live toast rather than a new one per phase, so a slow- * export occupies one line and updates in place instead of stacking. It is- * deliberately unglamorous: a count, then a result. There is no progress bar,- * because the honest unit here is assets and the expensive one is bytes, and a- * bar drawn from the first would sit at 99% through the whole of the second.- *- * ### Half-success is a result, not a success- *- * Export skips assets the server will not serve; import leaves references- * dangling when neither the archive nor this server has them. Both are correct- * — a project that exports every layer but one is far more use than one that- * refuses — but both are things the person holding the file needs to know- * before they hand it to someone else. So a lossy run finishes as a warning- * naming the count, and only a clean one finishes as a plain success.+ * A lossy run settles as a warning naming the count, not a success — the person holding the file+ * needs to know before they hand it to someone else.*//** i18next's `t`, narrowed to what this module needs. */@@ -44,12 +25,8 @@ export interface ProjectFileReporter {/** Update the live toast from a transfer's progress. */report: (progress: ProjectFileProgress) => void;/**- * Finish cleanly, or as a warning naming what was left behind.- *- * Board items and document references are counted apart because they cost different things: a- * missing board item is a result still findable elsewhere, a missing document reference is a- * hole in the canvas. One combined number meant anything from "you will not notice" to "the- * project is broken".+ * Board items and document references are counted apart: a missing board item is a result still+ * findable elsewhere, a missing document reference is a hole in the canvas.*/succeed: (title: string, issues: ProjectTransferIssues) => void;/** Finish as a failure, translating an `InvkFormatError` reason where there is one. */@@ -57,14 +34,8 @@ export interface ProjectFileReporter {}/**- * The reasons that mean the media is *not here*, as opposed to here without its flag.- *- * `star-failed` is the odd one out: the item arrived, it just did not get its star back. Folding it- * into "could not be included" tells someone their project lost media when nothing was lost, which- * is the one thing these counts exist to answer accurately.- *- * Phrasing a reason is this module's job, so the set lives here — `transfer.ts` owns the taxonomy- * and is imported type-only, which also keeps it out of the two routes' initial chunks.+ * The reasons that mean the media is *not here*. `star-failed` is excluded: the item arrived, it+ * just did not get its star back, and counting it would report lost media when nothing was lost.*/const MISSING_REASONS: ReadonlySet<InvkMediaIssueReason> = new Set(['fetch-failed', 'missing-entry', 'upload-failed']);@@ -84,24 +55,13 @@ const describeProgress = (t: Translate, progress: ProjectFileProgress): string =return t(key, { completed: progress.completed, total: progress.total });};-/**- * How often the live toast may redraw while a transfer runs.- *- * Progress arrives once per asset, and a project can have hundreds — each one otherwise a toaster- * state update, during the phase that is already saturating the network. A count that moves five- * times a second is as much as anyone reads, and the final value is always drawn, so the number a- * person is left looking at is never a stale one.- */+/** Progress arrives once per asset; five redraws a second is as much as anyone reads. */const PROGRESS_REDRAW_INTERVAL_MS = 200;/**- * Open the live toast for a transfer that is starting. The returned reporter- * owns that toast for the rest of the operation; every path through a caller's- * `try`/`catch` has to end in `succeed` or `fail`, or the toast stays up.- *- * `direction` decides how a failure is worded: the same `too-large` reason is raised by opening a- * file someone handed you and by exporting a project of your own, and those need different- * sentences.+ * Open the live toast. The reporter owns it for the rest of the operation — every path through a+ * caller's `try`/`catch` must end in `succeed` or `fail`, or the toast stays up. `direction` words+ * the failure: the same `too-large` reason arises from opening a file and from exporting one.*/export const startProjectFileReport = (t: Translate,diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.tsindex 90bfb6787e..70955253af 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFlush.ts@@ -1,14 +1,12 @@/*** What a push to the server actually achieved, as distinct from whether the call threw.*- * Its own module rather than part of the sync engine, because the two callers that need it —- * `library.ts` for duplication and `projectFile.ts` for export — are modules the sync engine itself- * imports. Reaching back into it for this would make that a cycle.+ * Its own module rather than part of the sync engine: the caller that needs it, `library.ts`, is a+ * module the sync engine itself imports, so reaching back would be a cycle.*- * Every failure the engine can hit is recoverable: the document is cached locally and the next save- * retries, which is why a push swallows them all rather than rejecting. But "recoverable" is not the- * same as "done", and reading a project back from the server after an unacknowledged push is how an- * export or a copy silently ships someone's work minus the last ten minutes of it.+ * A push swallows every failure because they are all recoverable — the document is cached and the+ * next save retries. But "recoverable" is not "done", and reading a project back after an+ * unacknowledged push is how an export ships someone's work minus the last ten minutes of it.*//** The document the push was carrying, so a caller can compare it with what the engine recorded. */@@ -42,14 +40,7 @@ export class ProjectFlushError extends Error {}}-/**- * Read back only what the server has certainly acknowledged.- *- * Both callers — export and duplicate — do the same two things: flush the open project, then GET- * the record. The GET returns the last *acknowledged* document, so without this the flush's failure- * is indistinguishable from its success and the copy is built from stale bytes under a clean- * success toast.- */+/** Refuse anything the server has not certainly acknowledged. See {@link readAcknowledgedProject}. */export const assertProjectFlushed = (outcome: ProjectPushOutcome): void => {if (outcome.kind !== 'acknowledged') {throw new ProjectFlushError(outcome.kind);@@ -57,13 +48,10 @@ export const assertProjectFlushed = (outcome: ProjectPushOutcome): void => {};/**- * Who a recovery fork *is*, separately from what it holds.- *- * The fork's `recoveredProject` is built from the document as it was when the push started, so- * applying it wholesale overwrites anything edited since. The identity is the only part of it the- * local store actually needs: a project that is still open can adopt these four fields and keep its- * live content, which is both newer and already what the person is looking at. The snapshot stays- * for the case where there is no live project left to re-identify — a tab closed mid-flight.+ * Who a recovery fork *is*, separately from what it holds. `recoveredProject` is built from the+ * document as it was when the push started, so applying it wholesale overwrites anything edited+ * since; a project still open adopts these four fields instead and keeps its live content. The+ * snapshot stays for the case with no live project left to re-identify — a tab closed mid-flight.*/export interface ProjectRecoveredIdentity {id: string;diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.tsindex 8dd860600e..1409626cd8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts@@ -5,15 +5,12 @@ import type { WorkbenchPreferences } from '@workbench/settings/contracts';import { getClientStateValue, setClientStateValue } from './api';/**- * The per-user session blob in the client-state KV: the editor session — which- * projects are open as tabs and which is active — plus a legacy account snapshot- * for older installs. Current settings live in `settings.ts` so Home can load- * them without mounting the workbench provider.+ * The per-user session blob in the client-state KV: which projects are open as tabs and which is+ * active, plus a legacy account snapshot. Settings live in `settings.ts` so Home can load them+ * without mounting the workbench provider.*- * `openProjectIds` arrived with the library/session split. Blobs written- * before it have no open set; `undefined` there means "unknown — open every- * project", which is exactly what those versions did, so old sessions migrate- * without anything visibly changing.+ * An `undefined` `openProjectIds` means "unknown — open every project", which is what the versions+ * predating the library/session split did, so old sessions migrate without visible change.*/export const SESSION_STATE_KEY = 'webv2:workbench-account';@@ -81,15 +78,9 @@ export const fetchSessionBlob = async (signal?: AbortSignal): Promise<WorkbenchS};/**- * Take a deleted project out of the saved session.- *- * A project is deleted from surfaces that may not have the editor mounted, and the session blob is- * what the `/app` guard and the Launchpad's "open" grouping read. Leaving the id there means the- * next boot tries to hydrate a project the server no longer has, and the Launchpad shows it as- * open until something else rewrites the blob.- *- * Best-effort and silent: the deletion has already happened, and failing to tidy the session after- * it is not a reason to tell someone their project was not deleted.+ * Take a deleted project out of the saved session, which the `/app` guard and the Launchpad's+ * "open" grouping read. Best-effort and silent: the deletion has already happened, and failing to+ * tidy up after it is not a reason to say the project was not deleted.*/export const pruneSessionProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {try {diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex f5960c24fa..62add3dc78 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -5,23 +5,16 @@ import type { ProjectPushOutcome } from './projectFlush';/*** The bridge between the project sync layer and everything outside the editor.- *- * Two things live here. {@link ProjectSyncSnapshot} is a read-only window for shell surfaces (the- * Project panel's debug section), written by `syncedPersistence` after each load/save pass.- * {@link OpenProjectHandle} is the other direction: a way for non-workbench code to mutate a project- * the workbench is currently holding, *through* the sync engine rather than behind its back.+ * {@link ProjectSyncSnapshot} is a read-only window for shell surfaces; {@link OpenProjectHandle}+ * is the other direction.** ### One invariant, replacing three races*- * A project the workbench holds is mutated only through the sync engine; every other project is- * mutated over HTTP. The library used to GET-and-PUT unconditionally, which meant renaming an open- * project landed a write beside its revision chain — the next autosave then saw a revision it did- * not expect and forked the project into a conflict copy. Duplicating one copied whatever the- * server last acknowledged, which is not what the person could see on screen. And deleting one- * raced the autosave that was about to recreate it.- *- * Now that a project's board commits with its name, a stray write is worse still: it renames the- * board too. So the branch is explicit, and there is exactly one of it per operation.+ * A project the workbench holds is mutated only through the sync engine; every other project over+ * HTTP. Unconditional GET-and-PUT meant renaming an open project forked it into a conflict copy,+ * duplicating one copied what the server last acknowledged rather than what was on screen, and+ * deleting one raced the autosave about to recreate it. Now that a board commits with its project's+ * name, a stray write renames the board too.*/export interface ProjectSyncInfo {@@ -64,11 +57,10 @@ export interface OpenProjectHandle {/*** Delete the project on the server, from inside the sync engine's mutation queue.*- * The queue is the point. Marking the project deleted stops a save that has not begun, but says- * nothing to a `PUT` already on the wire — that one returns 404 once the delete commits, and the- * engine's answer to a 404 is to fork the local edits into a new server-side project. Deleting- * *through* the queue means the in-flight push finishes first, so there is no 404 to misread and- * no copy of the project the person just deleted.+ * The queue is the point. Marking the project deleted stops a save that has not begun but says+ * nothing to a `PUT` already on the wire, which returns 404 once the delete commits — and the+ * engine's answer to a 404 is to fork the local edits into a new server-side project, a copy of+ * the thing just deleted. Deleting *through* the queue lets the in-flight push finish first.*/deleteOnServer: () => Promise<void>;/**diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex a3d061c2a8..ccac0a4e3d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -46,22 +46,15 @@ export { serializeProjectDocument } from './projectDocument';/*** Backend-first workbench persistence (spec: Persistence Model).*- * The backend database is the source of truth: each project is one- * revision-versioned document on the server, and the small session blob- * (open tabs + active project, with legacy account data) lives in the per-user- * client-state KV. The user-scoped localStorage snapshot is kept as a- * write-through cache so the workbench still loads and autosaves while the- * backend is unreachable; un-pushed changes are replayed on the next save or- * reconnect.+ * The server is the source of truth: one revision-versioned document per project, plus a session+ * blob in the per-user client-state KV. The localStorage snapshot is a write-through cache, so the+ * workbench still loads and autosaves offline and replays on reconnect.*- * Workbench state only ever holds the open projects (the session); the full- * set of saved projects lives in the project library as summaries. Saving- * pushes what is open and never deletes — projects leave the server only- * through the library's explicit delete.+ * Workbench state holds only the open projects; the rest live in the library as summaries. Saving+ * never deletes — projects leave the server only through the library's explicit delete.*- * Conflicts never lose work: when a save is based on a stale revision, the- * server version wins for that project id and the local version is forked- * into a "(recovered)" project beside it.+ * Conflicts never lose work: the server version keeps the id, and the local version forks into a+ * "(recovered)" project beside it.*/const SYNC_MAP_BASE_KEY = 'invokeai:v7:webv2:workbench-sync';@@ -125,12 +118,9 @@ interface SyncedPersistenceState {/** Ids deleted in this runtime lifetime, guarding against racing saves. */deletedProjectIds: Set<string>;/**- * Ids that have already been forked because the server no longer had them.- *- * The fork exists on the server from the moment it is made, but the original stays in the- * aggregate until the reconciliation reaches it. In that window `pushProject` would find no sync- * entry and re-create the project under its old id — undoing the very deletion the fork exists to- * respect. So a forked id is never pushed again.+ * Ids already forked because the server no longer had them. The original stays in the aggregate+ * until reconciliation reaches it, and in that window `pushProject` would find no sync entry and+ * re-create it under its old id — undoing the deletion the fork exists to respect.*/forkedProjectIds: Set<string>;hasPending: boolean;@@ -139,12 +129,9 @@ interface SyncedPersistenceState {/** Immutable owner captured when this synchronization lifetime was constructed. */owner: AccountScope;/**- * What the server said that the aggregate has not been told yet, drained by the next save.- *- * A push happens from a save *and* from a targeted flush, and only the save has somewhere to- * return an outcome to. Holding them here rather than in the caller's local arrays is what makes- * "the next save carries them" true rather than aspirational: a flush that forks a project or- * resolves a conflict cannot silently drop the answer.+ * What the server said that the aggregate has not been told yet, drained by the next save. A push+ * happens from a save *and* from a targeted flush, and only the save has somewhere to return an+ * outcome to — so a flush that forks a project cannot silently drop the answer.*/pendingBoardAssignments: ProjectBoardAssignment[];pendingConflicts: ProjectConflictResolution[];@@ -202,13 +189,9 @@ const getSerializedProjectDocument = (};/**- * Rehydrate a *server record*, which knows the project's real board.- *- * The document's own `projectBoardId` is a cache and can be stale — written by another install, or- * replaced by the migration when the board it named turned out to be ambiguous. Overwriting it- * here means every path that reads a project from the server agrees on one answer, and the next- * autosave writes the correction back. The saved destination is left alone: it is a deliberate- * choice, and `getGallerySelectedBoardId` resolves it against the boards that actually exist.+ * Rehydrate a *server record*, which knows the project's real board. The document's own+ * `projectBoardId` is a stale-able cache, so overwriting it here means every path that reads from+ * the server agrees on one answer. The saved destination is left alone — it is a deliberate choice.*/const deserializeProjectRecord = (record: ProjectRecordDTO): Project | null => {const project = deserializeProjectDocument(@@ -242,10 +225,8 @@ const getSyncMapStorageKey = (syncState: SyncedPersistenceState): string =>`${SYNC_MAP_BASE_KEY}${syncState.owner.storageSuffix}`;/**- * The revision map survives reloads so that, while offline, we can still tell- * "this local project was synced before but is gone from the server (deleted- * elsewhere — drop it)" apart from "this local project was created offline- * (push it)".+ * The revision map survives reloads so an offline runtime can tell "synced before, now gone from+ * the server — drop it" apart from "created offline — push it".*/const persistSyncMap = (syncState: SyncedPersistenceState): void => {assertOwner(syncState);@@ -329,11 +310,7 @@ const pushNewProject = async (syncState: SyncedPersistenceState, project: Projec/** Strip any number of stacked "(recovered)" suffixes left by older recoveries. */const getRecoveryBaseName = (name: string): string => name.replace(/(\s*\((?:r|R)ecovered\))+$/u, '').trim() || name;-/**- * Build the fork document for a conflicted project: lineage always points at- * the root original (a recovery of a recovery still keys to the first- * project), and the name never stacks suffixes.- */+/** Lineage points at the root original, so a recovery of a recovery still keys to the first. */export const createRecoveredDocument = (project: Project,document: Record<string, unknown>@@ -365,15 +342,11 @@ type ConflictOutcome =| { kind: 'failed' };/**- * A save lost the revision race. Forking is the last resort — it only happens- * when content actually diverged:+ * A save lost the revision race. Forking is the last resort — only when content actually diverged:*- * - server content == what we tried to push → adopt the revision, done- * - server content == the base this edit started from → revisions drifted- * without divergence (e.g. crash between an acknowledged PUT and the- * revision write); adopt the revision and retry the edit- * - anything else → the server version keeps the id, the local edits fork- * into a "(recovered)" project so nothing is lost+ * - server content == what we pushed → adopt the revision, done+ * - server content == this edit's base → revisions drifted without divergence; adopt and retry+ * - anything else → the server version keeps the id, the local edits fork into "(recovered)"*/const recoverConflictingProject = async (syncState: SyncedPersistenceState,@@ -446,11 +419,9 @@ type DeletionForkOutcome =| { kind: 'failed' };/**- * Rescue the local edits of a project the server no longer has.- *- * Deliberately a *fork*, not a re-create. Pushing the original id back would resurrect a project- * the user deleted — on every device, and here as a project whose board went with the deletion.- * The fork gets a fresh id, and with it a fresh board from the create response.+ * Rescue the local edits of a project the server no longer has. A *fork*, not a re-create: pushing+ * the original id back would resurrect a project the user deleted, on every device. The fork gets a+ * fresh id, and with it a fresh board from the create response.*/const forkDeletedProject = async (syncState: SyncedPersistenceState,@@ -952,16 +923,7 @@ export const createSyncedWorkbenchPersistence = (syncState.hasPending = false;});},- /**- * Remove the project from the server without letting a save race the removal.- *- * Queued rather than issued directly, which is the whole point: `markProjectDeleted` stops a- * push that has not started, but a `PUT` already in flight is past every check the engine has.- * That push comes back 404 once the DELETE commits, and the engine's answer to a 404 is to fork- * the local document into a *new* server project — resurrecting, as a copy, what the person- * just deleted, pointing at media the deletion already removed. Waiting for the queue removes- * the race rather than detecting it.- */+ /** Queued, not issued directly — see {@link OpenProjectHandle.deleteOnServer}. */deleteProjectOnServer(projectId): Promise<void> {return enqueueMutation(async () => {markDeleted(projectId);diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.tsindex 932a130f4c..82941369df 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts@@ -19,17 +19,10 @@ import { startProjectFileReport } from './projectFileToasts';/*** Picking, importing and exporting a project file, with the reporting attached.*- * Five surfaces offer these — Home, the Projects page, the in-editor Open- * dialog, the project switcher, and every project card — and each had written- * out the same twenty lines of scope capture, picker, try/catch and toast. They- * had already drifted: the import sites checked the account scope before- * showing an error and the export sites did not, so cancelling an export by- * signing out produced a toast written for a developer.- *- * Keeping the sequence in one place is what makes progress and partial-success- * reporting land on all five at once rather than on whichever was edited last.- * What differs between call sites is only what happens with the imported record,- * which is the callback.+ * Five surfaces offer these, and each had its own copy of the scope capture, picker, try/catch and+ * toast — which had already drifted. One sequence is what makes progress and partial-success+ * reporting land on all five at once. Only what happens with the imported record differs, and that+ * is the callback.*//** Runs the sequence, keeping the toast and the account scope in step. */