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.

fix(canvas): name unreadable layers and keep temporary fetch failures retryable

Josh Corbette1cedf98d8f0
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 055c6fc7a0..baca40d9f0 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -168,7 +168,7 @@ Right-click the canvas to open the menu of the selected layer, the same menu as
* **Save to Gallery** — **Save Canvas to Gallery** or **Save Frame to Gallery**.
* **Create From Frame** — copy what is inside the generation frame into a **New Global Reference Image**, **New Regional Reference Image**, **New Control Layer** or **New Raster Layer**.
-* **Crop all layers to frame** — crops every raster layer, control layer, inpaint mask and regional guidance layer to the generation frame, including hidden and disabled layers and layers inside groups, as one undoable step. Groups, layer order and visibility are unchanged. A layer entirely outside the frame is emptied rather than deleted. Locked layers, and layers in a locked group, are skipped, and so are layers whose image could not be read, for example because it was deleted from the Gallery; the other layers are still cropped. A brush stroke still being saved is saved first. A notice says how many layers were cropped, counting only the ones that changed, and how many locked or unreadable layers were left as they were. When every layer is locked, or there are no layers, the item is unavailable; highlighting it shows why.
+* **Crop all layers to frame** — crops every raster layer, control layer, inpaint mask and regional guidance layer to the generation frame, including hidden and disabled layers and layers inside groups, as one undoable step. Groups, layer order and visibility are unchanged. A layer entirely outside the frame is emptied rather than deleted. Locked layers, and layers in a locked group, are skipped, and so are layers whose image could not be read, for example because it was deleted from the Gallery; the other layers are still cropped. If an image cannot be fetched for now, for example while the server restarts, nothing is cropped and the notice asks you to try again. A brush stroke still being saved is saved first. A notice says how many layers were cropped, counting only the ones that changed, and how many locked layers were skipped; it names a layer that could not be read and counts any others. When every layer is locked, or there are no layers, the item is unavailable; highlighting it shows why.
With no layer selected, the menu has only the Canvas section.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 8de12bc2e3..2484376867 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3431,8 +3431,9 @@
"cropAllNoneCropped": "No layer was cropped",
"cropAllNothing": "Every layer already fits the frame",
"cropAllNothingUnlocked": "Every unlocked layer already fits the frame",
- "cropAllUnreadable_one": "{{count}} layer could not be read and was left as it is.",
- "cropAllUnreadable_other": "{{count}} layers could not be read and were left as they are.",
+ "cropAllUnreadable": "“{{name}}” could not be read and was left as it is.",
+ "cropAllUnreadableWithOthers_one": "“{{name}}” and {{count}} other layer could not be read and were left as they are.",
+ "cropAllUnreadableWithOthers_other": "“{{name}}” and {{count}} other layers could not be read and were left as they are.",
"croppedAllLayers_one": "Cropped {{count}} layer to the frame",
"croppedAllLayers_other": "Cropped {{count}} layers to the frame",
"croppedAllLayersSkipped_one": "{{count}} locked layer skipped.",
@@ -3452,7 +3453,7 @@
"saveToGallery": "Save to Gallery",
"saved": "Saved to gallery",
"stale": "The canvas changed while saving. Try again.",
- "unreadable": "A layer's image could not be read (it may have been deleted or damaged). Disable or delete that layer, then try again."
+ "unreadable": "“{{name}}” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then try again."
},
"controls": {
"clearCanvas": "Clear canvas",
@@ -3956,7 +3957,7 @@
"toggleVisibility": "Enable/disable",
"transform": "Transform",
"unsupported": "This action is not supported for this layer.",
- "unreadable": "A layer's image could not be read (it may have been deleted or damaged), so nothing was changed.",
+ "unreadable": "“{{name}}” could not be read (its image may have been deleted or damaged), so nothing was changed. Delete or replace that layer, then try again.",
"unlock": "Unlock layer",
"unlockSelected": "Unlock selected",
"group": "Group layers",
@@ -4362,7 +4363,7 @@
"exportNotReady": "Layers are still loading — try exporting again in a moment",
"exportOverBudget": "Not enough raster memory is available to export this PSD",
"exportStale": "The canvas changed during export — try again",
- "exportUnreadable": "A layer's image could not be read, so nothing was exported. Delete or replace that layer, then export again",
+ "exportUnreadable": "“{{name}}” could not be read, so nothing was exported. Delete or replace that layer, then export again",
"exportAborted": "PSD export was canceled",
"exportFailed": "PSD export failed",
"exportPsd": "Export to PSD",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index c742c9a9cb..7721b5c435 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -74,11 +74,11 @@ Current extracted ownership includes:
- `PaintLineEndController`: where the last brush or eraser stroke ended on each layer, followed through the layer's changes (see "Input ownership and frame scheduling").
- `InteractionController`: public tool commands and their disposal boundary.
- `LayerController`: guarded layer mutations and thumbnail capability ports.
-- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed (an image that is gone or does not decode) reports `unreadable`, never `not-ready`: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD) refuses with that reason instead of asking the user to retry. The rasterizer remembers the failure per cache entry, keyed by cache version, document generation and source, and a retry of the same source that fails again raises no second error notice. Two questions read that record. `hasFailed` (a failure is recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer `unreadable` for as long as it holds. `isBackingOff` (that failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A layer nobody redraws (off screen, disabled) is retried by a readiness gate that finds the backoff over, in the background while it still answers `unreadable`. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure.
+- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed because the source cannot be read reports a `LayerUnreadable` refusal (`layerExportGuards.ts`) carrying the layer's id and name, never `not-ready`: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD, composite export) refuses with it instead of asking the user to retry, and the message names the layer to disable, delete or replace. An operation reading several layers names the first that failed in its read order; crop all lists each one it skipped. Unreadable means the image resolver threw `CanvasImageMissingError` (the `ImageResolver` contract: the image is missing, or not readable by this user; the production resolver maps 403, 404 and 410 to it), the fetched image did not decode, or rendering threw. Any other resolver failure (network, server, an expired session) is wrapped as `ImageUnavailableError` and is transient: operations and readiness gates report `not-ready`, and crop all refuses the whole crop as `not-ready` instead of skipping the layer. The rasterizer remembers either failure per cache entry, keyed by cache version, document generation and source, with its kind, and a retry of the same source that fails again with the same kind raises no second error notice; a change of kind (a fetch outage that turns out to be a deleted image) is reported, with the `ImageUnavailableError` itself (naming the image, the resolver's error as its cause) for a transient one. Two questions read that record. `getFailure` (the kind recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer unreadable for as long as an `unreadable` failure holds, and `not-ready` for an `unavailable` one. `isBackingOff` (either failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A readiness gate asked about a layer also retries it in the background while it answers from the record (a layer off screen or disabled is never redrawn to do so): at once for an `unavailable` failure, so trying again after an outage ends fetches without waiting out the backoff, and only once the backoff is over for an `unreadable` one. A running job is joined, never duplicated. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure. Thumbnails show `error` for both kinds.
- `PsdExportController`: immutable PSD planning, snapshot capture, reservation, execution, cancellation.
- `StagedResultController`: guarded staged-candidate acceptance and its history entry.
- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush and eraser alike), keeping conversion plus pixels in one undoable transaction.
-- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an `unreadable` one, and one wholly outside the frame (`outside-frame`: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (`flushPendingPixels`, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as `stale`. It skips locked and `unreadable` leaves and counts each when its contract's content reaches past the frame (`skippedLocked`, `skippedUnreadable`), so the result can say what was left alone even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.
+- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an `unreadable` one, and one wholly outside the frame (`outside-frame`: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (`flushPendingPixels`, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as `stale`. It skips locked and unreadable leaves when their contract's content reaches past the frame, counting the locked ones (`skippedLocked`) and listing the unreadable ones in document order (`skippedUnreadable`), so the result can say what was left alone, by name, even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.
- `MaskResultController`, `FilterResultController`, `GeneratedResultController`: guarded application-result adoption through narrow host ports.
Controller-local tests instantiate these boundaries with fakes. Integration tests in `engine.test.ts` cover composition, document routing, cross-controller invariants.
@@ -87,7 +87,7 @@ Controller-local tests instantiate these boundaries with fakes. Integration test
`CanvasDocumentCapability.captureSnapshot()` returns `CanvasDocumentSnapshot` or `null`. Snapshot holds structured clone of exact `CanvasStateContractV3` and engine's `documentGeneration`. Engine privately ties it to the reducer canvas identity it was captured from, so caller cannot manufacture a current snapshot by copying fields.
-`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, copies their pixels into independent surfaces. Returns typed `ok`, `stale`, `aborted`, `not-ready`, `unreadable`, or `over-budget` result. Freshness checked before and after every async rasterization boundary and once after all copies are detached.
+`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, copies their pixels into independent surfaces. Returns typed `ok`, `stale`, `aborted`, `not-ready`, `over-budget`, or `LayerUnreadable` (naming the first layer that could not be read) result. Freshness checked before and after every async rasterization boundary and once after all copies are detached.
`ok` result holds a `CanvasRasterSnapshot`: cloned canvas contract, its document generation, map of detached layer surfaces, idempotent `release()`. Snapshot is caller-owned. Its surfaces do not read live caches and stay valid while engine cools down; cooldown releases generation-scoped reservations but does not invalidate detached snapshots. Caller must release snapshot in `finally`. Engine disposal releases any snapshots still outstanding.
@@ -212,7 +212,7 @@ Each leaf bakes its own stack exactly (spatial entries included), layer-local, b
Controller keeps 30,000-pixel side cap and also derives a pixel-area limit from currently available reserved bytes. Accounts for flattened composite plus each transformed layer surface, budgets eight bytes per required pixel, reserves full execution allocation before creating PSD surfaces. Final freshness check happens before that reservation; once execution starts it uses only frozen pixels. Capture and execution reservations release in `finally`; cancellation aborts before next allocation or side effect.
-Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `unreadable`, `over-budget`, `stale`, `aborted`, or an `AdjustmentRefusal`. Layers widget awaits the promise and maps every non-success result to a user-visible notice.
+Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-budget`, `stale`, `aborted`, a `LayerUnreadable`, or an `AdjustmentRefusal`. Layers widget awaits the promise and maps every non-success result to a user-visible notice.
## Input ownership and frame scheduling
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
index 918f7a619f..4264ca4c28 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
@@ -15,6 +15,7 @@ import type {
CommitMaskImageResult,
CommitMaskImageResultOptions,
} from '@workbench/canvas-engine/controllers/maskResultController';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { CanvasCompositeExecutorDeps } from '@workbench/canvas-engine/rasterTransactions';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
@@ -48,7 +49,8 @@ export interface CanvasApplicationHost {
options?: ExportLayerPixelsOptions
): Promise<
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal
>;
getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index c2bcebb9ea..68359e2cd4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -50,6 +50,7 @@ import type {
CanvasFontReplacementSummary,
CanvasFontReplacementTarget,
} from './fontReferences';
+import type { LayerUnreadable } from './layerExportGuards';
import type { CanvasLayerPreviewMutation, CanvasProjectMutation } from './mutationContracts';
import type { AdjustmentRefusal } from './render/exactAdjustments';
import type { Rect, ToolId, Vec2 } from './types';
@@ -266,11 +267,11 @@ export interface CanvasDocumentSnapshot {
export type PsdExportResult =
| AdjustmentRefusal
+ | LayerUnreadable
| 'exported'
| 'nothing'
| 'too-large'
| 'over-budget'
- | 'unreadable'
| SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'stale' | 'aborted'>;
export interface CanvasPsdExportCapability {
@@ -378,9 +379,9 @@ export type ExportBakedLayerBlobResult =
| SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'aborted'>
| 'disabled'
| 'empty'
- | 'over-budget'
- | 'unreadable';
+ | 'over-budget';
}
+ | LayerUnreadable
| AdjustmentRefusal;
export interface CanvasSelectionCapability {
@@ -553,12 +554,9 @@ export interface FilterPreviewInput {
export type DuplicateLayersResult =
| { readonly status: 'duplicated'; readonly duplicateIds: readonly string[]; readonly selectedLayerId: string }
| {
- readonly status:
- | SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'stale'>
- | 'nothing'
- | 'over-budget'
- | 'unreadable';
- };
+ readonly status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'stale'> | 'nothing' | 'over-budget';
+ }
+ | LayerUnreadable;
/**
* Layer pixel operations report a distinct outcome: refused before anything changed (`busy`, `not-ready`,
* `over-budget` when the edit could never be undone), nothing to do, or `failed` when the document refused it.
@@ -779,7 +777,7 @@ export {
TEXT_FONT_WEIGHTS,
} from './engineStores';
export type { LayerTransform } from './transform/transformMath';
-export type { ImageResolver } from './render/rasterizers';
+export { CanvasImageMissingError, type ImageResolver } from './render/rasterizers';
export type { Rect, SelectionOp, ToolId, Vec2 } from './types';
export { adjustmentsKey, buildCurveLut, isIdentityAdjustments } from './render/adjustments';
export { isAdjustmentRefusal, type AdjustmentRefusal, type AdjustmentRefusalReason } from './render/exactAdjustments';
@@ -894,7 +892,7 @@ export {
type CanvasNodeMove,
type InsertionAnchorCapture,
} from './document/insertionAnchors';
-export { isExportableRasterLayer } from './layerExportGuards';
+export { isExportableRasterLayer, isLayerUnreadable, type LayerUnreadable } from './layerExportGuards';
export {
getLayerThumbnailFallbackRenderState,
nextLayerThumbnailFallbackStage,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/bakedControlLayer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/bakedControlLayer.browser.test.ts
index 5b4d15cd5c..e06c8f5e8b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/bakedControlLayer.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/bakedControlLayer.browser.test.ts
@@ -107,7 +107,7 @@ const scene = (runSpatial?: SpatialRunner) => {
});
const exportBaked: CopyLayerControllerOptions['exportBaked'] = async (layerId) => {
const result = await exporter.baked(layerId, { includeDisabled: true });
- if (result.status === 'ok' || result.status === 'adjustment-refused') {
+ if (result.status === 'ok' || result.status === 'adjustment-refused' || result.status === 'unreadable') {
return result;
}
return { status: result.status === 'aborted' ? 'not-ready' : result.status };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
index f670115f66..0699255242 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
@@ -1,5 +1,6 @@
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -29,14 +30,15 @@ export type BooleanRasterResult =
| 'missing'
| 'unsupported'
| 'empty'
- | 'unreadable'
| 'failed'
| LayerEditRefusal
+ | LayerUnreadable
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export interface BooleanMergeControllerOptions {
@@ -124,7 +126,7 @@ export class BooleanMergeController {
return 'over-budget';
}
if (upperPixels.status === 'unreadable' || belowPixels.status === 'unreadable') {
- return 'unreadable';
+ return upperPixels.status === 'unreadable' ? upperPixels : (belowPixels as LayerUnreadable);
}
if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {
return 'not-ready';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
index 5049b01ce2..067d19e9ce 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
@@ -3,6 +3,7 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';
import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -25,7 +26,8 @@ import {
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
/** The stack a baked copy lands in: a raster paint layer, or a control layer with a default adapter. */
@@ -34,13 +36,9 @@ export type CopyLayerTarget = 'raster' | 'control';
export type CopyLayerResult =
| { status: 'copied'; layerId: string }
| {
- status:
- | LayerEditRefusal
- | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
- | 'empty'
- | 'unreadable'
- | 'failed';
+ status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed';
}
+ | LayerUnreadable
| AdjustmentRefusal;
export interface CopyLayerControllerOptions {
@@ -122,6 +120,9 @@ export class CopyLayerController {
? { layerId: layer.id, status: 'copied' }
: { status: 'not-ready' };
}
+ if (baked.status === 'unreadable') {
+ return baked;
+ }
if (baked.status !== 'ok') {
return { status: baked.status === 'disabled' ? 'not-ready' : baked.status };
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
index 82a8da9b2c..02f24721e2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
@@ -64,7 +64,7 @@ const createHarness = (
exportBaked: (layerId) => {
exported.push(layerId);
if (options.unreadable) {
- return Promise.resolve({ status: 'unreadable' as const });
+ return Promise.resolve({ layerId, layerName: 'Paint', status: 'unreadable' as const });
}
const entry = h.layers.get(layerId)!;
const current = getDocumentLayer(h.document(), layerId)!;
@@ -121,7 +121,11 @@ describe('CropLayerController', () => {
it('says a layer that could not be read is unreadable, not still loading', async () => {
const h = createHarness(undefined, { unreadable: true });
- await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'unreadable' });
+ await expect(h.controller.crop('paint')).resolves.toEqual({
+ layerId: 'paint',
+ layerName: 'Paint',
+ status: 'unreadable',
+ });
expect(h.dispatched).toEqual([]);
expect(h.history.canUndo()).toBe(false);
});
@@ -185,6 +189,8 @@ const createCropAllHarness = (
refusal?: AdjustmentRefusal;
/** Leaves added on top whose pixels cannot be read. */
unreadable?: readonly CanvasLayerContract[];
+ /** Leaves whose pixels are not ready (still loading, or their image could not be fetched for now). */
+ notReady?: readonly string[];
/** Settles pending paint uploads; resolves at once by default. */
flushPendingPixels?: () => Promise<void>;
} = {}
@@ -242,8 +248,12 @@ const createCropAllHarness = (
const read = exportOptions?.applyAdjustments === false ? `${layerId}:raw` : layerId;
exported.push(read);
options.onExport?.(layerId);
- if (options.unreadable?.some((leaf) => leaf.id === layerId)) {
- return Promise.resolve({ status: 'unreadable' as const });
+ const unreadable = options.unreadable?.find((leaf) => leaf.id === layerId);
+ if (unreadable) {
+ return Promise.resolve({ layerId, layerName: unreadable.name, status: 'unreadable' as const });
+ }
+ if (options.notReady?.includes(layerId)) {
+ return Promise.resolve({ status: 'not-ready' as const });
}
if (options.refusal?.ownerId === layerId && read === layerId) {
return Promise.resolve(options.refusal);
@@ -304,7 +314,7 @@ describe('CropLayerController: crop all layers', () => {
await expect(h.controller.cropAll()).resolves.toEqual({
cropped: 4,
skippedLocked: 2,
- skippedUnreadable: 0,
+ skippedUnreadable: [],
status: 'cropped',
});
expect(h.exported).toEqual(['mask', 'region', 'control', 'inside:raw', 'raster']);
@@ -319,7 +329,7 @@ describe('CropLayerController: crop all layers', () => {
await expect(h.controller.cropAll()).resolves.toEqual({
cropped: 4,
skippedLocked: 2,
- skippedUnreadable: 0,
+ skippedUnreadable: [],
status: 'cropped',
});
expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);
@@ -338,7 +348,7 @@ describe('CropLayerController: crop all layers', () => {
await expect(h.controller.cropAll()).resolves.toEqual({
cropped: 4,
skippedLocked: 2,
- skippedUnreadable: 0,
+ skippedUnreadable: [],
status: 'cropped',
});
@@ -397,27 +407,47 @@ describe('CropLayerController: crop all layers', () => {
expect(h.layers.get('raster')?.rect).toEqual(FRAME);
});
- it('skips leaves whose pixels cannot be read and crops the rest, counting those that reach past the frame', async () => {
+ it('skips leaves whose pixels cannot be read and crops the rest, naming those that reach past the frame', async () => {
/** An image layer whose decode failed; its contract still says where its content lies. */
- const unreadableImage = (id: string, x: number) =>
+ const unreadableImage = (id: string, name: string, x: number) =>
layerContract(id, 'raster', {
+ name,
source: { image: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'image' },
transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },
} as Partial<CanvasLayerContract>);
- const h = createCropAllHarness({ unreadable: [unreadableImage('gone', 15), unreadableImage('goneInside', 5)] });
+ const h = createCropAllHarness({
+ unreadable: [
+ unreadableImage('gone', 'Sky', 15),
+ unreadableImage('goneInside', 'Inside sky', 5),
+ unreadableImage('goneLeft', 'Hills', -5),
+ ],
+ });
await expect(h.controller.cropAll()).resolves.toEqual({
cropped: 4,
skippedLocked: 2,
- skippedUnreadable: 1,
+ skippedUnreadable: [
+ { layerId: 'gone', layerName: 'Sky', status: 'unreadable' },
+ { layerId: 'goneLeft', layerName: 'Hills', status: 'unreadable' },
+ ],
status: 'cropped',
});
- expect(h.exported).toEqual(['mask', 'region', 'control', 'gone', 'goneInside', 'inside', 'raster']);
+ expect(h.exported).toEqual(['mask', 'region', 'control', 'gone', 'goneInside', 'goneLeft', 'inside', 'raster']);
expect(getDocumentLayer(h.document(), 'gone')).toBe(getDocumentLayer(h.original, 'gone'));
expect(getDocumentLayer(h.document(), 'raster')).not.toBe(getDocumentLayer(h.original, 'raster'));
expect(h.history.entries().past).toEqual(['Crop all layers to frame']);
});
+ it('refuses as not ready, without skipping, when a leaf it must read is not ready', async () => {
+ const h = createCropAllHarness({ notReady: ['control'] });
+
+ await expect(h.controller.cropAll()).resolves.toEqual({ status: 'not-ready' });
+ expect(h.document()).toBe(h.original);
+ expect(h.dispatched).toEqual([]);
+ expect(h.history.canUndo()).toBe(false);
+ expect(h.reservedBytes()).toBe(0);
+ });
+
it('settles pending paint uploads before it reads any leaf', async () => {
let settle!: () => void;
const h = createCropAllHarness({
@@ -444,7 +474,7 @@ describe('CropLayerController: crop all layers', () => {
await expect(h.controller.cropAll()).resolves.toEqual({
skippedLocked: 2,
- skippedUnreadable: 0,
+ skippedUnreadable: [],
status: 'nothing',
});
expect(h.dispatched).toEqual([]);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
index 9540bd4a90..3e7a163663 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
@@ -5,6 +5,7 @@ import type {
CanvasLayerSourceContract,
} from '@workbench/canvas-engine/contracts';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -31,29 +32,38 @@ import {
/**
* `locked`: the layer or a group above it is locked. `outside-frame`: the layer lies wholly outside the frame, so the
- * crop would empty it (crop all does that; an explicit crop of one layer refuses). `unreadable`: its pixels could not
- * be read (an image that is gone or does not decode).
+ * crop would empty it (crop all does that; an explicit crop of one layer refuses). {@link LayerUnreadable}: its
+ * pixels could not be read (an image that is gone or does not decode).
*/
export type CropLayerResult =
| { status: 'cropped' }
- | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'outside-frame' | 'unreadable' | LayerEditRefusal }
+ | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'outside-frame' | LayerEditRefusal }
| { status: 'failed'; message: string }
+ | LayerUnreadable
| AdjustmentRefusal;
+/** What crop all left alone: how many locked leaves, and each unreadable one in document order. */
+interface CropAllSkipped {
+ readonly skippedLocked: number;
+ readonly skippedUnreadable: readonly LayerUnreadable[];
+}
+
/**
- * `skippedLocked` counts locked leaves (own or ancestor lock) and `skippedUnreadable` leaves whose pixels could not be
- * read, each only when its content reaches past the frame; both are left as they are. `nothing` when every other leaf
- * already fits; every refusal leaves document, pixels and history alone.
+ * `skippedLocked` counts locked leaves (own or ancestor lock) and `skippedUnreadable` lists leaves whose pixels could
+ * not be read, each only when its content reaches past the frame; both are left as they are. `nothing` when every
+ * other leaf already fits; every refusal leaves document, pixels and history alone. A leaf whose image could not be
+ * fetched for now refuses the whole crop as `not-ready`, since trying again can crop it too.
*/
export type CropAllLayersResult =
- | { status: 'cropped'; cropped: number; skippedLocked: number; skippedUnreadable: number }
- | { status: 'nothing'; skippedLocked: number; skippedUnreadable: number }
+ | ({ status: 'cropped'; cropped: number } & CropAllSkipped)
+ | ({ status: 'nothing' } & CropAllSkipped)
| { status: 'stale' | 'failed' | LayerEditRefusal }
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export interface CropLayerControllerOptions {
@@ -138,11 +148,7 @@ const cropPixels = (backend: RasterBackend, exported: RasterSurface, exportedRec
};
/** What crop all makes of one leaf's export. */
-type CropExport =
- | Extract<ExportResult, { status: 'ok' }>
- | { status: 'skip' }
- | { status: 'unreadable' }
- | CropAllLayersResult;
+type CropExport = Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | LayerUnreadable | CropAllLayersResult;
/** One leaf's crop: its contract and pixels before and after. */
interface LayerCrop {
@@ -181,7 +187,7 @@ export class CropLayerController {
}
try {
const exported = await this.deps.exportBaked(layerId);
- if (exported.status === 'adjustment-refused') {
+ if (exported.status === 'adjustment-refused' || exported.status === 'unreadable') {
return exported;
}
if (exported.status !== 'ok') {
@@ -287,7 +293,7 @@ export class CropLayerController {
}
const document = ctx.getDocument();
if (!document) {
- return { skippedLocked: 0, skippedUnreadable: 0, status: 'nothing' };
+ return { skippedLocked: 0, skippedUnreadable: [], status: 'nothing' };
}
const frame = roundOut(document.bbox);
/** Whether cropping would change `leaf`, judged from its contract: content reaching past the frame. */
@@ -296,7 +302,7 @@ export class CropLayerController {
return !isEmpty(content) && cropRectFor(transformBounds(leaf.worldTransform, content), frame) !== null;
};
let skippedLocked = 0;
- let skippedUnreadable = 0;
+ const skippedUnreadable: LayerUnreadable[] = [];
const candidates: SemanticLeaf[] = [];
for (const leaf of compileDocumentLeaves(document)) {
const eligibility = cropEligibility(leaf, this.deps.isSupportedSource);
@@ -318,7 +324,7 @@ export class CropLayerController {
if (exported.status === 'unreadable') {
// Waiting cannot make it readable; one such layer must not hold every other layer back.
if (reachesPastFrame(leaf)) {
- skippedUnreadable += 1;
+ skippedUnreadable.push(exported);
}
continue;
}
@@ -374,19 +380,16 @@ export class CropLayerController {
}
/**
- * A leaf's baked pixels for crop all, `skip` when it has nothing to crop, or `unreadable`. A leaf with its own adjustment stack is
- * first exported raw: adjustments never move pixels, so the raw rect is the baked one, and a leaf already inside the
- * frame never runs its stack (a spatial job that could refuse the whole crop). Its guard still joins the staleness
- * check, as every read leaf's does.
+ * A leaf's baked pixels for crop all, `skip` when it has nothing to crop, or its unreadable refusal. A leaf with its
+ * own adjustment stack is first exported raw: adjustments never move pixels, so the raw rect is the baked one, and a
+ * leaf already inside the frame never runs its stack (a spatial job that could refuse the whole crop). Its guard
+ * still joins the staleness check, as every read leaf's does.
*/
private async exportForCrop(layer: CanvasLayerContract, frame: Rect): Promise<CropExport> {
const settle = (exported: ExportResult): CropExport => {
- if (exported.status === 'ok' || exported.status === 'adjustment-refused') {
+ if (exported.status === 'ok' || exported.status === 'adjustment-refused' || exported.status === 'unreadable') {
return exported;
}
- if (exported.status === 'unreadable') {
- return { status: 'unreadable' };
- }
if (exported.status === 'missing') {
return { status: 'stale' };
}
@@ -410,7 +413,7 @@ export class CropLayerController {
private publishAll(
document: CanvasDocumentContractV3,
cropped: readonly CroppedLeaf[],
- skipped: { readonly skippedLocked: number; readonly skippedUnreadable: number }
+ skipped: CropAllSkipped
): CropAllLayersResult {
const { ctx } = this.deps;
const afterBytes = cropped.reduce((sum, leaf) => sum + rgbaBytes(leaf.pixels.rect), 0);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
index e9fb4399a8..3d65effaba 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
@@ -8,6 +8,7 @@ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/c
import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { CanvasTransactionOutcome, SubsetOf } from '@workbench/canvas-engine/editConcurrency';
import type { HeldAssetRefs } from '@workbench/canvas-engine/history/history';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
@@ -15,6 +16,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { getDocumentLayer, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
+import { isLayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type {
CanvasMutationContext,
@@ -35,14 +37,15 @@ export const rgbaBytes = (rect: Rect): number => Math.max(0, rect.width) * Math.
// ---- Publication outcomes ----------------------------------------------------------------------------------
/**
- * Whether a layer operation can read a layer's cache now: `not-ready` while its pixels load (waiting helps),
- * `unreadable` once rasterizing its current source failed (waiting does not; the operation refuses and says so).
+ * Whether a layer operation can read a layer's cache now: `not-ready` while its pixels load or cannot be fetched for
+ * now (waiting helps), {@link LayerUnreadable} once rasterizing its current source failed (waiting does not; the
+ * operation refuses and names the layer).
*/
-export type LayerCacheReadiness = 'ready' | 'not-ready' | 'unreadable';
+export type LayerCacheReadiness = 'ready' | 'not-ready' | LayerUnreadable;
-/** Layers read together: one that cannot be read refuses the set even while others still load. */
+/** Layers read together: the first that cannot be read refuses the set even while others still load. */
export const readinessOfAll = (readiness: readonly LayerCacheReadiness[]): LayerCacheReadiness =>
- readiness.includes('unreadable') ? 'unreadable' : readiness.includes('not-ready') ? 'not-ready' : 'ready';
+ readiness.find(isLayerUnreadable) ?? (readiness.includes('not-ready') ? 'not-ready' : 'ready');
/** A refused admission as callers report it; a gesture in progress reads as contention. */
export type LayerEditRefusal = SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'over-budget'>;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
index 07d99b3edc..227a368c37 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
@@ -15,6 +15,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';
+import { isLayerUnreadable, type LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import { isEmpty } from '@workbench/canvas-engine/math/rect';
import {
type AdjustmentRefusal,
@@ -51,20 +52,17 @@ import {
export type ExtractMaskedAreaResult =
| { status: 'extracted'; layerId: string }
| {
- status:
- | LayerEditRefusal
- | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
- | 'empty'
- | 'unreadable'
- | 'failed';
+ status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed';
}
+ | LayerUnreadable
| AdjustmentRefusal;
type OwnedExport = Extract<ExportResult, { status: 'ok' }>;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export interface ExtractMaskedAreaControllerOptions {
@@ -149,7 +147,7 @@ export class ExtractMaskedAreaController {
}
const readiness = readinessOfAll([mask, ...contributors].map((layer) => this.deps.cacheReadiness(layer, document)));
if (readiness !== 'ready') {
- return { status: readiness };
+ return readiness === 'not-ready' ? { status: readiness } : readiness;
}
const owned: Extract<ExportResult, { status: 'ok' }>[] = [];
const acquire = async (resultPromise: Promise<ExportResult>): Promise<ExportResult> => {
@@ -175,10 +173,15 @@ export class ExtractMaskedAreaController {
return { status: 'busy' };
}
const statuses = [maskPixels, ...contributorPixels].map((pixels) => pixels.status);
- for (const status of ['over-budget', 'unreadable', 'not-ready'] as const) {
- if (statuses.includes(status)) {
- return { status };
- }
+ if (statuses.includes('over-budget')) {
+ return { status: 'over-budget' };
+ }
+ const unreadable = [maskPixels, ...contributorPixels].find(isLayerUnreadable);
+ if (unreadable) {
+ return unreadable;
+ }
+ if (statuses.includes('not-ready')) {
+ return { status: 'not-ready' };
}
if (maskPixels.status !== 'ok' || statuses.some((status) => status !== 'ok')) {
return { status: 'empty' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
index c32e280f62..9493c6fdda 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
@@ -3,6 +3,7 @@ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/c
import type { CanvasCommandRefusal } from '@workbench/canvas-engine/document/commandRefusal';
import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { SubsetOf } from '@workbench/canvas-engine/editConcurrency';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
@@ -42,13 +43,14 @@ export type ConvertLayerToControlResult =
| 'converted'
| SubsetOf<CanvasCommandRefusal, 'missing' | 'locked' | 'unsupported'>
| LayerEditRefusal
- | 'unreadable'
| 'failed'
+ | LayerUnreadable
| AdjustmentRefusal;
type BakedExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export type DuplicateLayerRasterPlan =
@@ -65,7 +67,8 @@ export type DuplicateLayerRasterPlan =
type DuplicateRasterPreparationResult =
| { readonly status: 'ready'; readonly layer: CanvasLayerContract }
- | { readonly status: 'not-ready' | 'unreadable' | 'over-budget' };
+ | { readonly status: 'not-ready' | 'over-budget' }
+ | LayerUnreadable;
export interface LayerMutationControllerOptions {
readonly ctx: Pick<
@@ -170,6 +173,9 @@ export class LayerMutationController {
return { status: 'not-ready' };
}
const prepared = await o.prepareDuplicateRasterSource(source.id);
+ if (prepared.status === 'unreadable') {
+ return prepared;
+ }
if (prepared.status !== 'ready') {
return { status: prepared.status };
}
@@ -496,7 +502,7 @@ export class LayerMutationController {
return 'locked';
}
const baked = await o.exportBaked(current.id);
- if (baked.status === 'adjustment-refused') {
+ if (baked.status === 'adjustment-refused' || baked.status === 'unreadable') {
return baked;
}
if (baked.status === 'empty') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
index 1d65edcbcd..90d5ea9908 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
@@ -30,6 +30,7 @@ import {
inpaintMaskMergeEligibility,
} from '@workbench/canvas-engine/document/mergeVisible';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
+import { isLayerUnreadable, type LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import {
applyAdjustments,
@@ -69,8 +70,14 @@ import {
type LayerPixels,
} from './editSteps';
-/** `unreadable`: a contributor's pixels could not be read (its image is gone or does not decode). */
-export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'unreadable' | 'failed' | AdjustmentRefusal;
+/** {@link LayerUnreadable}: the first contributor whose pixels could not be read (its image is gone or does not decode). */
+export type MergeVisibleResult =
+ | 'merged'
+ | LayerEditRefusal
+ | 'nothing'
+ | 'failed'
+ | LayerUnreadable
+ | AdjustmentRefusal;
/**
* Every refusal leaves document, pixels and history alone. `settings-differ`: the masks are otherwise eligible, but
@@ -78,7 +85,8 @@ export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'unre
*/
export type MergeInpaintMasksResult =
| { status: 'merged'; layerId: string }
- | { status: 'ineligible' | 'settings-differ' | 'missing' | 'unreadable' | 'failed' | LayerEditRefusal }
+ | { status: 'ineligible' | 'settings-differ' | 'missing' | 'failed' | LayerEditRefusal }
+ | LayerUnreadable
| AdjustmentRefusal;
/**
@@ -98,7 +106,8 @@ interface SelectedMergeSpec {
type SelectedMergeResult =
| { status: 'merged'; layerId: string }
- | { status: Exclude<MergeVisibleResult, 'merged' | AdjustmentRefusal> }
+ | { status: Exclude<MergeVisibleResult, 'merged' | LayerUnreadable | AdjustmentRefusal> }
+ | LayerUnreadable
| AdjustmentRefusal;
const IDENTITY_TRANSFORM = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
@@ -131,13 +140,14 @@ export type MergeDownResult =
| 'merged'
| SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
| LayerEditRefusal
- | 'unreadable'
| 'failed'
+ | LayerUnreadable
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export interface MergeLayerControllerOptions {
@@ -424,8 +434,9 @@ export class MergeLayerController {
if (exports.some((result) => result.status === 'over-budget')) {
return 'over-budget';
}
- if (exports.some((result) => result.status === 'unreadable')) {
- return 'unreadable';
+ const unreadable = exports.find(isLayerUnreadable);
+ if (unreadable) {
+ return unreadable;
}
if (exports.some((result) => result.status !== 'ok')) {
return 'not-ready';
@@ -576,7 +587,7 @@ export class MergeLayerController {
label: 'Merge selected layers',
stack: 'raster',
});
- return isAdjustmentRefusal(result) ? result : result.status;
+ return isAdjustmentRefusal(result) || isLayerUnreadable(result) ? result : result.status;
}
/** Unions the coverage of selected inpaint masks, anywhere in the stack, into one new mask above the topmost. */
@@ -604,7 +615,7 @@ export class MergeLayerController {
label: 'Merge masks',
stack: 'inpaint_mask',
});
- if (result.status === 'merged' || isAdjustmentRefusal(result)) {
+ if (result.status === 'merged' || isAdjustmentRefusal(result) || isLayerUnreadable(result)) {
return result;
}
return { status: result.status === 'nothing' ? 'ineligible' : result.status };
@@ -654,8 +665,9 @@ export class MergeLayerController {
if (exports.some((result) => result.status === 'over-budget')) {
return { status: 'over-budget' };
}
- if (exports.some((result) => result.status === 'unreadable')) {
- return { status: 'unreadable' };
+ const unreadable = exports.find(isLayerUnreadable);
+ if (unreadable) {
+ return unreadable;
}
if (exports.some((result) => result.status !== 'ok')) {
return { status: 'not-ready' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
index 0afd797aab..9e8e98e260 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
@@ -105,6 +105,9 @@ export class PsdExportController {
layers.map((layer) => layer.id),
{ includeDisabled: true, signal: abortController.signal }
);
+ if (capture.status === 'unreadable') {
+ return capture;
+ }
if (capture.status !== 'ok') {
return capture.status;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts
index 512fa452b0..db14be5bee 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts
@@ -20,7 +20,7 @@ export interface RasterizationJob {
version: number;
documentGeneration: number;
source: CanvasLayerSourceContract;
- promise: Promise<'published' | 'stale' | 'error' | 'aborted'>;
+ promise: Promise<'published' | 'stale' | 'error' | 'unavailable' | 'aborted'>;
}
import {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
index cc2e055383..877832bd1d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
@@ -10,6 +10,7 @@ import type {
CanvasLayerContract,
CanvasLayerSourceContract,
} from '@workbench/canvas-engine/contracts';
+import type { LayerRasterizationOutcome } from '@workbench/canvas-engine/layerRasterizer';
import type { RasterReadLease } from '@workbench/canvas-engine/rasterTransactions';
import type { CanvasTextSource } from '@workbench/canvas-engine/render/fontLoader';
import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
@@ -17,6 +18,7 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rend
import { lookupDocumentLayer, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
+import { layerUnreadable, type LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
import { hasSpatialAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
@@ -28,15 +30,16 @@ import {
} from '@workbench/canvas-engine/render/exactAdjustments';
/**
- * `not-ready`: the pixels are still loading or moved while they were read, so trying again can succeed. `unreadable`:
- * rasterizing the layer's current source failed (an image that is gone or does not decode), so trying again cannot
- * succeed until the source changes.
+ * `not-ready`: the pixels are still loading, moved while they were read, or their image could not be fetched for now,
+ * so trying again can succeed. {@link LayerUnreadable}: rasterizing the layer's current source failed (an image that is
+ * gone or does not decode), so trying again cannot succeed until the source changes.
*/
export type ExportLayerPixelsResult =
| ({ status: 'ok' } & RasterReadLease)
| {
- status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' | 'aborted';
+ status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted';
}
+ | LayerUnreadable
| AdjustmentRefusal;
export interface RasterExportControllerOptions {
@@ -47,7 +50,7 @@ export interface RasterExportControllerOptions {
layer: CanvasLayerContract,
document: CanvasDocumentContractV3,
signal?: AbortSignal
- ) => Promise<'published' | 'stale' | 'error' | 'aborted'>;
+ ) => Promise<LayerRasterizationOutcome>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
readonly isRasterizing: (layer: CanvasLayerContract) => boolean;
readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;
@@ -212,8 +215,11 @@ export class RasterExportController {
let leased = false;
try {
const rasterized = await this.options.getOrStartRasterization(layer, document, options.signal);
+ if (rasterized === 'error') {
+ return layerUnreadable(this.options.getDocument() ?? document, layerId);
+ }
if (rasterized !== 'published') {
- return { status: rasterized === 'aborted' ? 'aborted' : rasterized === 'error' ? 'unreadable' : 'not-ready' };
+ return { status: rasterized === 'aborted' ? 'aborted' : 'not-ready' };
}
const currentDocument = this.options.getDocument();
const currentLayer = currentDocument ? lookupDocumentLayer(currentDocument, layerId) : null;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 0fb3632177..37d37c391e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -61,6 +61,7 @@ import { createBitmapStore } from './document/bitmapStore';
import { mergeDownMatrix } from './document/mergeDown';
import { createCanvasEngine as createCoreCanvasEngine } from './engine';
import { RASTERIZATION_RETRY_BASE_MS } from './layerRasterizer';
+import { CanvasImageMissingError } from './render/rasterizers/imageRasterizer';
interface EngineStore {
dispatch(action: EngineTestAction): void;
@@ -813,7 +814,7 @@ describe('createCanvasEngine', () => {
}
});
- it('keeps Merge down unreadable past the backoff for a layer nobody redraws, and merges once its image loads', async () => {
+ it('answers Merge down not ready while an image cannot be fetched, retrying it on every ask, and merges once it loads', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('upper'), rasterLayer('flaky')]) };
@@ -822,7 +823,127 @@ describe('createCanvasEngine', () => {
const imageResolver = vi.fn((imageName: string) =>
imageName !== 'flaky' || available
? Promise.resolve(new Blob())
- : Promise.reject(new Error('backend restarting'))
+ : Promise.reject(new Error('Failed to load canvas image "flaky" (503)'))
+ );
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver,
+ projectId,
+ reportError: vi.fn(),
+ store,
+ });
+ const settle = async () => {
+ for (let tick = 0; tick < 50; tick += 1) {
+ await Promise.resolve();
+ }
+ };
+ const flakyFetches = () => imageResolver.mock.calls.filter(([name]) => name === 'flaky').length;
+ expect((await engine.exports.exportLayerPixels('upper')).status).toBe('ok');
+ expect(await engine.exports.exportLayerPixels('flaky')).toEqual({ status: 'not-ready' });
+ expect(flakyFetches()).toBe(1);
+ // Asking again fetches at once, inside the backoff; a second ask joins that fetch rather than starting another.
+ const asks = [engine.layers.mergeLayerDown('upper'), engine.layers.mergeLayerDown('upper')];
+ expect(await Promise.all(asks)).toEqual(['not-ready', 'not-ready']);
+ await settle();
+ expect(flakyFetches()).toBe(2);
+
+ // The server recovers; the next ask, still inside the backoff, fetches and the one after merges.
+ available = true;
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('not-ready');
+ await settle();
+ expect(flakyFetches()).toBe(3);
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('merged');
+ engine.lifecycle.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('crops all at once when asked again after a fetch outage ends, without waiting out the backoff', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const document = {
+ ...makeDoc(),
+ bbox: { height: 8, width: 8, x: 0, y: 0 },
+ stacks: stacksFrom([rasterLayer('flaky'), rasterLayer('a')]),
+ };
+ const { projectId, store } = createReducerBackedStore(document);
+ let available = false;
+ const imageResolver = vi.fn((imageName: string) =>
+ imageName !== 'flaky' || available
+ ? Promise.resolve(new Blob())
+ : Promise.reject(new Error('Failed to load canvas image "flaky" (503)'))
+ );
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver,
+ projectId,
+ reportError: vi.fn(),
+ store,
+ });
+ const flakyFetches = () => imageResolver.mock.calls.filter(([name]) => name === 'flaky').length;
+
+ expect(await engine.layers.cropAllLayersToBbox()).toEqual({ status: 'not-ready' });
+ expect(getDocumentLayer(engine.document.getDocument()!, 'a')).toMatchObject({ source: { type: 'image' } });
+ expect(flakyFetches()).toBe(1);
+
+ available = true;
+ expect(await engine.layers.cropAllLayersToBbox()).toEqual({
+ cropped: 2,
+ skippedLocked: 0,
+ skippedUnreadable: [],
+ status: 'cropped',
+ });
+ expect(flakyFetches()).toBe(2);
+ engine.lifecycle.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('names the topmost of two unreadable layers when Merge selected refuses', async () => {
+ const document = {
+ ...makeDoc(),
+ stacks: stacksFrom([
+ { ...rasterLayer('upper'), name: 'Sky' },
+ { ...rasterLayer('below'), name: 'Hills' },
+ ]),
+ };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: (imageName) => Promise.reject(new CanvasImageMissingError(imageName)),
+ projectId,
+ reportError: vi.fn(),
+ store,
+ });
+
+ // Contributors are read in document order, topmost first, and the first that cannot be read is named.
+ expect(await engine.layers.mergeSelectedRasterLayers(['below', 'upper'])).toEqual({
+ layerId: 'upper',
+ layerName: 'Sky',
+ status: 'unreadable',
+ });
+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['upper', 'below']);
+ engine.lifecycle.dispose();
+ });
+
+ it('keeps Merge down unreadable past the backoff for a layer nobody redraws, and merges once its image loads', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const document = {
+ ...makeDoc(),
+ stacks: stacksFrom([rasterLayer('upper'), { ...rasterLayer('flaky'), name: 'Sky' }]),
+ };
+ const { projectId, store } = createReducerBackedStore(document);
+ let available = false;
+ const imageResolver = vi.fn((imageName: string) =>
+ imageName !== 'flaky' || available
+ ? Promise.resolve(new Blob())
+ : Promise.reject(new CanvasImageMissingError(imageName))
);
const reportError = vi.fn();
const engine = createCanvasEngine({
@@ -838,21 +959,23 @@ describe('createCanvasEngine', () => {
await Promise.resolve();
}
};
+ // The refusal names the layer below, which is the one that cannot be read.
+ const unreadable = { layerId: 'flaky', layerName: 'Sky', status: 'unreadable' };
// No surface is attached, so nothing redraws either layer.
expect((await engine.exports.exportLayerPixels('upper')).status).toBe('ok');
- expect((await engine.exports.exportLayerPixels('flaky')).status).toBe('unreadable');
- expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+ expect(await engine.exports.exportLayerPixels('flaky')).toEqual(unreadable);
+ expect(await engine.layers.mergeLayerDown('upper')).toEqual(unreadable);
vi.advanceTimersByTime(RASTERIZATION_RETRY_BASE_MS);
// Past the backoff it still cannot be read, and asking tries the image again in the background.
- expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+ expect(await engine.layers.mergeLayerDown('upper')).toEqual(unreadable);
await settle();
expect(imageResolver.mock.calls.filter(([name]) => name === 'flaky')).toHaveLength(2);
expect(reportError.mock.calls).toHaveLength(1);
available = true;
vi.advanceTimersByTime(RASTERIZATION_RETRY_BASE_MS * 2);
- expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+ expect(await engine.layers.mergeLayerDown('upper')).toEqual(unreadable);
await settle();
expect(await engine.layers.mergeLayerDown('upper')).toBe('merged');
engine.lifecycle.dispose();
@@ -1099,7 +1222,7 @@ describe('createCanvasEngine', () => {
const { store } = createReactiveStore(makeDoc());
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
- imageResolver: () => Promise.reject(new Error('decode unavailable')),
+ imageResolver: (imageName) => Promise.reject(new CanvasImageMissingError(imageName)),
projectId: 'p1',
reportError: vi.fn(),
store,
@@ -1107,6 +1230,8 @@ describe('createCanvasEngine', () => {
const documentSnapshot = engine.document.captureSnapshot();
await expect(engine.exports.captureRasterSnapshot(documentSnapshot!, ['a'])).resolves.toEqual({
+ layerId: 'a',
+ layerName: 'a',
status: 'unreadable',
});
engine.lifecycle.dispose();
@@ -1345,22 +1470,44 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
- it('refuses a composite export with a layer whose image cannot be read as unreadable', async () => {
- const { store } = createReactiveStore(makeDoc());
+ it('refuses a composite export with a layer whose image is gone as unreadable, naming the layer', async () => {
+ const { store } = createReactiveStore({
+ ...makeDoc(),
+ stacks: stacksFrom([{ ...rasterLayer('a'), name: 'Sky' }, rasterLayer('b')]),
+ });
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
- imageResolver: () => Promise.reject(new Error('image deleted')),
+ imageResolver: (imageName) =>
+ imageName === 'a' ? Promise.reject(new CanvasImageMissingError(imageName)) : Promise.resolve(new Blob()),
projectId: 'p1',
reportError: vi.fn(),
store,
});
await expect(engine.exports.exportRasterComposite({ bounds: 'content' })).resolves.toEqual({
+ layerId: 'a',
+ layerName: 'Sky',
status: 'unreadable',
});
engine.lifecycle.dispose();
});
+ it('refuses a composite export as not ready, never unreadable, while a layer image cannot be fetched', async () => {
+ const { store } = createReactiveStore(makeDoc());
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.reject(new Error('Failed to load canvas image "a" (503)')),
+ projectId: 'p1',
+ reportError: vi.fn(),
+ store,
+ });
+
+ await expect(engine.exports.exportRasterComposite({ bounds: 'content' })).resolves.toEqual({
+ status: 'not-ready',
+ });
+ engine.lifecycle.dispose();
+ });
+
it('uploads per-generation composites through the intermediate seam, not the durable one', async () => {
// Generation composites have no document references and must be reclaimable; only layer-owned pixels require
// durable uploads.
@@ -1724,7 +1871,11 @@ describe('createCanvasEngine', () => {
store,
});
- expect(await engine.exports.exportLayerPixels('shape')).toEqual({ status: 'unreadable' });
+ expect(await engine.exports.exportLayerPixels('shape')).toEqual({
+ layerId: 'shape',
+ layerName: 'shape',
+ status: 'unreadable',
+ });
expect((await engine.exports.exportLayerPixels('shape')).status).toBe('ok');
engine.lifecycle.dispose();
});
@@ -2362,7 +2513,7 @@ describe('createCanvasEngine', () => {
expect(await engine.layers.cropAllLayersToBbox()).toEqual({
cropped: 3,
skippedLocked: 1,
- skippedUnreadable: 0,
+ skippedUnreadable: [],
status: 'cropped',
});
const cropped = structuredClone(engine.document.getDocument()!);
@@ -2395,17 +2546,18 @@ describe('createCanvasEngine', () => {
backend: createTestStubRasterBackend(),
bitmapStore: createSpyBitmapStore(),
imageResolver: (imageName) =>
- imageName === 'broken' ? Promise.reject(new Error('image deleted')) : Promise.resolve(new Blob()),
+ imageName === 'broken' ? Promise.reject(new CanvasImageMissingError(imageName)) : Promise.resolve(new Blob()),
projectId,
reportError,
store,
});
const broken = getDocumentLayer(engine.document.getDocument()!, 'broken');
+ const skippedUnreadable = [{ layerId: 'broken', layerName: 'broken', status: 'unreadable' }];
expect(await engine.layers.cropAllLayersToBbox()).toEqual({
cropped: 1,
skippedLocked: 0,
- skippedUnreadable: 1,
+ skippedUnreadable,
status: 'cropped',
});
expect(getDocumentLayer(engine.document.getDocument()!, 'broken')).toBe(broken);
@@ -2413,7 +2565,7 @@ describe('createCanvasEngine', () => {
// Asking again reads the image again, but the same failure raises no second notice.
expect(await engine.layers.cropAllLayersToBbox()).toEqual({
skippedLocked: 0,
- skippedUnreadable: 1,
+ skippedUnreadable,
status: 'nothing',
});
const readFailures = reportError.mock.calls.filter(
@@ -2464,7 +2616,7 @@ describe('createCanvasEngine', () => {
const { projectId, store } = createReducerBackedStore(document);
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
- imageResolver: () => Promise.reject(new Error('decode failed')),
+ imageResolver: (imageName) => Promise.reject(new CanvasImageMissingError(imageName)),
projectId,
store,
});
@@ -2472,7 +2624,11 @@ describe('createCanvasEngine', () => {
expect(await engine.layers.cropLayerToBbox('missing')).toEqual({ status: 'missing' });
expect(await engine.layers.cropLayerToBbox('locked')).toEqual({ status: 'locked' });
expect(await engine.layers.cropLayerToBbox('polygon')).toEqual({ status: 'unsupported' });
- expect(await engine.layers.cropLayerToBbox('unreadable')).toEqual({ status: 'unreadable' });
+ expect(await engine.layers.cropLayerToBbox('unreadable')).toEqual({
+ layerId: 'unreadable',
+ layerName: 'unreadable',
+ status: 'unreadable',
+ });
engine.lifecycle.dispose();
});
@@ -5738,7 +5894,7 @@ describe('requestLayerThumbnail', () => {
expect.objectContaining({
area: 'canvas-engine',
context: expect.objectContaining({
- error: expect.objectContaining({ message: 'decode failed' }),
+ error: expect.objectContaining({ message: 'Canvas image "a" could not be fetched.' }),
layerId: 'a',
}),
message: 'Layer thumbnail rasterization failed',
@@ -7936,7 +8092,7 @@ describe('structural raster publication failure atomicity', () => {
}
slowImage.resolve(new Blob());
- await expect(crop).resolves.toEqual({ cropped: 2, skippedLocked: 0, skippedUnreadable: 0, status: 'cropped' });
+ await expect(crop).resolves.toEqual({ cropped: 2, skippedLocked: 0, skippedUnreadable: [], status: 'cropped' });
expect(engine.history.getEntries().past).toEqual(['Crop all layers to frame']);
engine.lifecycle.dispose();
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5b5772edd8..98bc5430c2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -170,6 +170,7 @@ import { colorLoupePixels, renderOverlay } from '@workbench/canvas-engine/render
import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';
import { createDomRasterBackend, type RasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';
import {
+ RasterCompositeNotReadyError,
RasterCompositeOverBudgetError,
RasterCompositeUnreadableError,
} from '@workbench/canvas-engine/render/rasterComposite';
@@ -196,6 +197,7 @@ import { FULL_DAMAGE } from '@workbench/canvas-engine/types';
import { createViewport, type Viewport } from '@workbench/canvas-engine/viewport';
import type { ImagePatchApply } from './history/imagePatch';
+import type { LayerUnreadable } from './layerExportGuards';
import type { CanvasProjectMutation } from './mutationContracts';
import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';
@@ -204,7 +206,7 @@ import { createDocumentMirror, type DocumentMirror } from './document/documentMi
import { decideLayerChange, nextThumbnailDisplayToken } from './document/layerChangeDecision';
import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';
import { collectCanvasFontReferences, replaceCanvasFontReferences } from './fontReferences';
-import { createLayerExportGuards, isSupportedExportSource } from './layerExportGuards';
+import { createLayerExportGuards, isSupportedExportSource, layerUnreadable } from './layerExportGuards';
import { createLayerRasterizer } from './layerRasterizer';
import { createPreviewPublisher } from './previewPublisher';
import { createRasterSnapshotCapture } from './rasterSnapshotCapture';
@@ -1267,7 +1269,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const {
dispose: disposeLayerRasterizer,
getOrStartLayerRasterization,
- hasFailed: hasFailedRasterization,
+ getFailure: getRasterizationFailure,
isBackingOff: isRasterizationBackingOff,
} = createLayerRasterizer({
createSurface: (width, height) => backend.createSurface(width, height),
@@ -1369,11 +1371,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const rasterizeLayerPixels = rasterExportController.rasterize.bind(rasterExportController);
const prepareLayerRasterCache = async (layerId: string) => {
const result = await rasterizeLayerPixels(layerId, { includeDisabled: true });
+ if (result.status === 'unreadable') {
+ return result;
+ }
if (result.status !== 'ok') {
- return {
- status:
- result.status === 'over-budget' || result.status === 'unreadable' ? result.status : ('not-ready' as const),
- };
+ return { status: result.status === 'over-budget' ? result.status : ('not-ready' as const) };
}
const layer = result.guard.layer;
result.release();
@@ -1395,13 +1397,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const exportBakedLayerBlob = rasterExportController.blob.bind(rasterExportController);
type StructuralExportLayerPixelsResult =
| Extract<ExportLayerPixelsResult, { status: 'ok' }>
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
const normalizeStructuralExport = async (
result: Promise<ExportLayerPixelsResult>
): Promise<StructuralExportLayerPixelsResult> => {
const resolved = await result;
- if (resolved.status === 'ok' || resolved.status === 'adjustment-refused') {
+ if (resolved.status === 'ok' || resolved.status === 'adjustment-refused' || resolved.status === 'unreadable') {
return resolved;
}
return { status: resolved.status === 'aborted' ? 'not-ready' : resolved.status };
@@ -1419,7 +1422,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
document: CanvasDocumentContractV3
): Promise<'published' | 'stale' | 'error'> => {
const result = await getOrStartLayerRasterization(layer, document);
- return result === 'aborted' ? 'stale' : result;
+ return result === 'aborted' ? 'stale' : result === 'unavailable' ? 'error' : result;
};
const cropLayerToBbox = (layerId: string): Promise<CropLayerResult> => layerController.crop.crop(layerId);
@@ -1441,7 +1444,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
throw new RasterCompositeOverBudgetError();
}
if (result.status === 'unreadable') {
- throw new RasterCompositeUnreadableError(layerId);
+ throw new RasterCompositeUnreadableError(result);
+ }
+ if (result.status === 'not-ready') {
+ throw new RasterCompositeNotReadyError(layerId);
}
throw new Error(`Cannot rasterize layer ${layerId} for export: ${result.status}.`);
};
@@ -2162,21 +2168,25 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return !!entry && !entry.stale && !isCurrentRasterizationJob(layer);
};
/**
- * `unreadable` while a failure is recorded for the layer's current source. Once its backoff has ended this also
- * tries the image again in the background (a layer off screen or disabled is never redrawn to do so), so an image
- * that became available recovers; a retry that fails again only restarts the backoff.
+ * Unreadable while an `unreadable` failure is recorded for the layer's current source, `not-ready` while it loads or
+ * its image could not be fetched for now. The image is tried again in the background (a layer off screen or disabled
+ * is never redrawn to do so), so one that became available recovers: at once after an `unavailable` failure, since
+ * the user asking again is the moment a recovered server should be noticed, and only once the backoff has ended
+ * after an `unreadable` one. A retry that fails again only restarts the backoff; a running job is joined, not
+ * duplicated.
*/
const layerCacheReadinessForOp = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): LayerCacheReadiness => {
if (isLayerCacheReadyForOp(layer, doc)) {
return 'ready';
}
- if (isCurrentRasterizationJob(layer) || !hasFailedRasterization(layer)) {
+ const failure = isCurrentRasterizationJob(layer) ? null : getRasterizationFailure(layer);
+ if (!failure) {
return 'not-ready';
}
- if (!isRasterizationBackingOff(layer)) {
+ if (failure === 'unavailable' || !isRasterizationBackingOff(layer)) {
scheduleLayerRasterization([layer.id]);
}
- return 'unreadable';
+ return failure === 'unreadable' ? layerUnreadable(doc, layer.id) : 'not-ready';
};
const prepareGeneratedPaintCache = (layerId: string, rect: Rect, pixels: RasterSurface) =>
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
index 4fd3e1d96b..9d83f1deda 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
@@ -1,4 +1,5 @@
import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -12,6 +13,7 @@ import {
compositeScratchPixels,
getBaseRasterContentBounds,
planBaseRasterComposite,
+ RasterCompositeNotReadyError,
RasterCompositeOverBudgetError,
RasterCompositeUnreadableError,
renderRasterComposite,
@@ -22,7 +24,8 @@ export type RasterCompositeExportRequest = { bounds: 'content' } | { bounds: 're
export type RasterCompositeExportResult =
| { status: 'ok'; blob: Blob; rect: Rect }
- | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export interface RasterCompositeExportSnapshot {
@@ -77,7 +80,7 @@ export const exportRasterComposite = async (
return { status: 'over-budget' };
}
if (error instanceof RasterCompositeUnreadableError) {
- return { status: 'unreadable' };
+ return error.refusal;
}
if (error instanceof AdjustmentRefusedError) {
return adjustmentRefusal(document, error.ownerId, error.reason);
@@ -86,6 +89,9 @@ export const exportRasterComposite = async (
if (!deps.isSnapshotCurrent(snapshot) || (error instanceof DOMException && error.name === 'AbortError')) {
return { status: 'stale' };
}
+ if (error instanceof RasterCompositeNotReadyError) {
+ return { status: 'not-ready' };
+ }
throw error;
}
if (!deps.isSnapshotCurrent(snapshot)) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts
index 15cc87ccdf..3c2f59d542 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerExportGuards.ts
@@ -8,7 +8,7 @@ import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rast
import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import { areJsonValuesStructurallyEqual } from '@platform/core/json';
-import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
+import { getDocumentLayer, getDocumentNode } from '@workbench/canvas-engine/document/documentIndex';
import {
getSourceContentRect,
isEmptyPolygonShape,
@@ -16,6 +16,28 @@ import {
} from '@workbench/canvas-engine/document/sources';
import { isEmpty } from '@workbench/canvas-engine/math/rect';
+/**
+ * An operation refused because one layer's pixels could not be read: its image is gone or does not decode. Waiting
+ * cannot fix it, so the message names the layer for the user to disable, delete or replace.
+ */
+export interface LayerUnreadable {
+ readonly status: 'unreadable';
+ readonly layerId: string;
+ /** The layer's name, or its id when it has none or is gone. */
+ readonly layerName: string;
+}
+
+/** The refusal for `layerId`, named from `document`. */
+export const layerUnreadable = (document: CanvasDocumentContractV3 | null, layerId: string): LayerUnreadable => ({
+ layerId,
+ layerName: getDocumentNode(document, layerId)?.name || layerId,
+ status: 'unreadable',
+});
+
+/** Type guard for results that mix string statuses with a {@link LayerUnreadable}. */
+export const isLayerUnreadable = (value: unknown): value is LayerUnreadable =>
+ typeof value === 'object' && value !== null && (value as { status?: unknown }).status === 'unreadable';
+
/** A pointless polygon shape has no raster, so it can never back an export. */
export const isSupportedExportSource = (source: CanvasLayerSourceContract): boolean =>
source.type !== 'shape' || !isEmptyPolygonShape(source);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
index 415f0c3459..25859d1257 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
@@ -4,6 +4,7 @@ import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { ImageUnavailableError } from '@workbench/canvas-engine/render/rasterizers/imageRasterizer';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createLayerRasterizer, type CreateLayerRasterizerDeps, RASTERIZATION_RETRY_BASE_MS } from './layerRasterizer';
@@ -288,12 +289,12 @@ describe('failure', () => {
await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
expect(harness.rasterize).toHaveBeenCalledTimes(2);
expect(harness.spies.reportError).toHaveBeenCalledOnce();
- expect(rasterizer.hasFailed(layer)).toBe(true);
+ expect(rasterizer.getFailure(layer)).toBe('unreadable');
// Another image is another failure, worth its own notice.
const replaced = rasterLayer({ source: { image: { height: 4, imageName: 'b.png', width: 4 }, type: 'image' } });
harness.document.value = documentOf([replaced]);
- expect(rasterizer.hasFailed(replaced)).toBe(false);
+ expect(rasterizer.getFailure(replaced)).toBeNull();
await expect(rasterizer.getOrStartLayerRasterization(replaced, harness.document.value)).resolves.toBe('error');
expect(harness.spies.reportError).toHaveBeenCalledTimes(2);
});
@@ -316,7 +317,7 @@ describe('failure', () => {
timers.at(-1)!.callback();
// The backoff's end lets the display try again, and says so; the failure itself is still on record.
expect(rasterizer.isBackingOff(layer)).toBe(false);
- expect(rasterizer.hasFailed(layer)).toBe(true);
+ expect(rasterizer.getFailure(layer)).toBe('unreadable');
expect(harness.spies.invalidateLayerRender).toHaveBeenCalledWith('layer-1');
await rasterizer.getOrStartLayerRasterization(layer, harness.document.value);
@@ -327,6 +328,48 @@ describe('failure', () => {
expect(harness.spies.reportError).toHaveBeenCalledOnce();
});
+ it('records an image that could not be fetched as unavailable: backed off, reported once per kind', async () => {
+ const timers: { callback: () => void; delayMs: number }[] = [];
+ const rasterizer = createLayerRasterizer({
+ ...harness.deps,
+ setTimer: (callback, delayMs) => {
+ timers.push({ callback, delayMs });
+ return () => undefined;
+ },
+ });
+ (harness.entry as { stale: boolean }).stale = true;
+ const outage = new ImageUnavailableError('a.png', { cause: new Error('503') });
+ harness.rasterize.mockRejectedValue(outage);
+ const layer = rasterLayer();
+
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('unavailable');
+ expect(harness.spies.setStatus).toHaveBeenCalledWith('layer-1', 'error');
+ expect(rasterizer.getFailure(layer)).toBe('unavailable');
+ expect(rasterizer.isBackingOff(layer)).toBe(true);
+
+ timers.at(-1)!.callback();
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('unavailable');
+ expect(timers.map(({ delayMs }) => delayMs)).toEqual([
+ RASTERIZATION_RETRY_BASE_MS,
+ RASTERIZATION_RETRY_BASE_MS * 2,
+ ]);
+ // The notice carries the wrapper, which names the image, with the resolver's error as its cause.
+ expect(harness.spies.reportError.mock.calls).toEqual([['Layer thumbnail rasterization failed', 'layer-1', outage]]);
+
+ // Once the image is gone for good, the same key reads as unreadable, and that new kind is reported.
+ const gone = new Error('decode failed');
+ harness.rasterize.mockRejectedValue(gone);
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
+ expect(rasterizer.getFailure(layer)).toBe('unreadable');
+ expect(harness.spies.reportError.mock.calls.at(-1)).toEqual([
+ 'Layer thumbnail rasterization failed',
+ 'layer-1',
+ gone,
+ ]);
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
+ expect(harness.spies.reportError).toHaveBeenCalledTimes(2);
+ });
+
it('forgets a failure once a retry publishes', async () => {
const rasterizer = createLayerRasterizer(harness.deps);
(harness.entry as { stale: boolean }).stale = true;
@@ -335,7 +378,7 @@ describe('failure', () => {
await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('published');
- expect(rasterizer.hasFailed(layer)).toBe(false);
+ expect(rasterizer.getFailure(layer)).toBeNull();
});
it('still reports error when diagnostics itself throws', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
index 121ff1a252..bf9bb1a916 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
@@ -13,9 +13,14 @@ import { areJsonValuesStructurallyEqual } from '@platform/core/json';
import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';
+import { ImageUnavailableError } from '@workbench/canvas-engine/render/rasterizers/imageRasterizer';
-/** How a rasterization ended: pixels landed, the world moved, it threw, or it was cancelled. */
-export type LayerRasterizationOutcome = 'published' | 'stale' | 'error' | 'aborted';
+/**
+ * How a rasterization ended: pixels landed, the world moved, it was cancelled, or it failed. `error`: the source cannot
+ * be read (its image is missing or does not decode, or rendering threw), so it fails again until it changes.
+ * `unavailable`: its image could not be fetched for now, so a later try may succeed.
+ */
+export type LayerRasterizationOutcome = 'published' | 'stale' | 'error' | 'unavailable' | 'aborted';
/** The registry of in-flight rasterizations, keyed by layer. */
export interface RasterizationJobRegistry {
@@ -66,12 +71,13 @@ export interface LayerRasterizer {
signal?: AbortSignal
): Promise<LayerRasterizationOutcome>;
/**
- * Whether the last rasterization of `layer`'s current source, cache version and document generation failed, so its
- * stale cache cannot become ready by waiting. A success or any change to the layer clears it.
+ * How the last rasterization of `layer`'s current source, cache version and document generation failed, or null:
+ * `unreadable` when its stale cache cannot become ready by waiting, `unavailable` when its image could not be
+ * fetched for now. A success or any change to the layer clears it.
*/
- hasFailed(layer: CanvasLayerContract): boolean;
+ getFailure(layer: CanvasLayerContract): RasterizationFailureKind | null;
/**
- * Whether {@link hasFailed} and the failure's retry backoff is still running. The backoff starts at
+ * Whether a failure of either kind is recorded and its retry backoff is still running. The backoff starts at
* {@link RASTERIZATION_RETRY_BASE_MS} and doubles per repeated failure up to {@link RASTERIZATION_RETRY_MAX_MS}; its
* end invalidates the layer's render, so a displayed layer retries on its own.
*/
@@ -80,8 +86,11 @@ export interface LayerRasterizer {
dispose(): void;
}
-/** What a failed rasterization read; a later failure of the same key is the same failure. */
+export type RasterizationFailureKind = 'unreadable' | 'unavailable';
+
+/** What a failed rasterization read; a later failure of the same key continues its backoff, whatever its kind. */
interface RasterizationFailure {
+ readonly kind: RasterizationFailureKind;
readonly version: number;
readonly documentGeneration: number;
readonly source: CanvasLayerSourceContract;
@@ -247,14 +256,22 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
return 'stale';
}
deps.thumbnails.setStatus(layer.id, 'error');
- // Retrying the same source fails the same way; only its first failure is worth a notice.
+ const kind: RasterizationFailureKind = error instanceof ImageUnavailableError ? 'unavailable' : 'unreadable';
+ // Retrying the same source fails the same way; only its first failure of each kind is worth a notice.
const failedEntry = layerCache.peek(layer.id);
const previous = failedEntry ? failures.get(failedEntry) : undefined;
const repeated = !!failedEntry && isSameFailure(previous, version, documentGeneration, source);
endBackoff(previous);
if (failedEntry && !deps.isDisposed()) {
const attempts = repeated ? previous!.attempts + 1 : 1;
- const failure: RasterizationFailure = { attempts, cancelRetry: null, documentGeneration, source, version };
+ const failure: RasterizationFailure = {
+ attempts,
+ cancelRetry: null,
+ documentGeneration,
+ kind,
+ source,
+ version,
+ };
failure.cancelRetry = setTimer(
() => {
failure.cancelRetry = null;
@@ -266,14 +283,14 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
backoffs.add(failure);
failures.set(failedEntry, failure);
}
- if (!repeated) {
+ if (!repeated || previous!.kind !== kind) {
try {
deps.reportError('Layer thumbnail rasterization failed', layer.id, error);
} catch {
// Diagnostics must not turn a handled thumbnail failure into a rejection.
}
}
- return 'error';
+ return kind === 'unavailable' ? 'unavailable' : 'error';
} finally {
signal?.removeEventListener('abort', abort);
jobs.finish(layer.id, job);
@@ -291,7 +308,8 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
? failure
: undefined;
};
- const hasFailed = (layer: CanvasLayerContract): boolean => !!currentFailure(layer);
+ const getFailure = (layer: CanvasLayerContract): RasterizationFailureKind | null =>
+ currentFailure(layer)?.kind ?? null;
const isBackingOff = (layer: CanvasLayerContract): boolean => !!currentFailure(layer)?.cancelRetry;
const dispose = (): void => {
@@ -300,5 +318,5 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
}
};
- return { dispose, getOrStartLayerRasterization, hasFailed, isBackingOff };
+ return { dispose, getFailure, getOrStartLayerRasterization, isBackingOff };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index edd517ce4c..a1c156cc82 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -151,14 +151,13 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
emptyLayerIds.add(layerId);
continue;
}
+ if (liveResult.status === 'unreadable') {
+ return liveResult;
+ }
if (liveResult.status !== 'ok') {
return {
status:
- liveResult.status === 'aborted' ||
- liveResult.status === 'over-budget' ||
- liveResult.status === 'unreadable'
- ? liveResult.status
- : 'not-ready',
+ liveResult.status === 'aborted' || liveResult.status === 'over-budget' ? liveResult.status : 'not-ready',
};
}
const live = liveResult;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
index fc18d1ebbc..ca65d614f7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
@@ -1,5 +1,6 @@
import type { LayerExportGuard } from './capabilities';
import type { CanvasStateContractV3 } from './contracts';
+import type { LayerUnreadable } from './layerExportGuards';
import type { SpatialRunner } from './render/exactAdjustments';
import type { RasterSurface } from './render/raster';
import type { Rect } from './types';
@@ -29,10 +30,11 @@ export interface CanvasRasterSnapshot {
release(): void;
}
-/** `unreadable`: a required layer's pixels could not be read (its image is gone or does not decode). */
+/** {@link LayerUnreadable}: a required layer's pixels could not be read (its image is gone or does not decode). */
export type CaptureRasterSnapshotResult =
| { status: 'ok'; snapshot: CanvasRasterSnapshot }
- | { status: 'stale' | 'aborted' | 'not-ready' | 'unreadable' | 'over-budget' };
+ | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable;
export interface CanvasCompositeExecutorDeps {
backend: {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/exactAdjustments.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/exactAdjustments.ts
index b9159546c4..98ad72e93d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/exactAdjustments.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/exactAdjustments.ts
@@ -14,7 +14,7 @@ import type {
} from '@workbench/canvas-engine/render/spatial/spatialAdjustmentService';
import type { Rect } from '@workbench/canvas-engine/types';
-import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
+import { getDocumentNode } from '@workbench/canvas-engine/document/documentIndex';
import {
type AdjustablePixels,
type AdjustmentOrigin,
@@ -68,7 +68,7 @@ export const adjustmentRefusal = (
reason: AdjustmentRefusalReason
): AdjustmentRefusal => ({
ownerId,
- ownerName: (document && getDocumentIndex(document).byId.get(ownerId)?.node.name) || ownerId,
+ ownerName: getDocumentNode(document, ownerId)?.name || ownerId,
reason,
status: 'adjustment-refused',
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
index 38e7823925..04ec02db4b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -7,6 +7,7 @@ import type {
CanvasRasterLayerContractV2,
} from '@workbench/canvas-engine/contracts';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
+import type { LayerUnreadable } from '@workbench/canvas-engine/layerExportGuards';
import type { GroupCompositeScope } from '@workbench/canvas-engine/render/groupCompositeScopes';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
@@ -108,14 +109,25 @@ export class RasterCompositeOverBudgetError extends Error {
}
}
-/** Thrown when a contributor's pixels cannot be read (its image is gone or does not decode); export maps it to `unreadable`. */
+/**
+ * Thrown when a contributor's pixels cannot be read (its image is gone or does not decode); export reports its
+ * `unreadable` refusal, which names the layer.
+ */
export class RasterCompositeUnreadableError extends Error {
- constructor(readonly layerId: string) {
- super(`The pixels of layer ${layerId} could not be read.`);
+ constructor(readonly refusal: LayerUnreadable) {
+ super(`The pixels of layer ${refusal.layerId} could not be read.`);
this.name = 'RasterCompositeUnreadableError';
}
}
+/** Thrown when a contributor's pixels are still loading or could not be fetched for now; export maps it to `not-ready`. */
+export class RasterCompositeNotReadyError extends Error {
+ constructor(readonly layerId: string) {
+ super(`The pixels of layer ${layerId} are not ready.`);
+ this.name = 'RasterCompositeNotReadyError';
+ }
+}
+
const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>
surface.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts
index 8b0dbe0d46..5e80ed9b7d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/imageRasterizer.ts
@@ -6,14 +6,50 @@ import { createDecodedBitmapPool } from '@workbench/canvas-engine/render/decoded
import type { RasterizeDeps, RasterizeResult } from './types';
-/** Acquires a short-lived decoded bitmap lease, coalescing concurrent decodes by image name. */
+/**
+ * Thrown by an `ImageResolver` for an image that is missing (deleted, or never stored) or not readable by this user;
+ * either lasts, so the layer reads as unreadable.
+ */
+export class CanvasImageMissingError extends Error {
+ constructor(readonly imageName: string) {
+ super(`Canvas image "${imageName}" is missing or not readable.`);
+ this.name = 'CanvasImageMissingError';
+ }
+}
+
+/**
+ * The resolver could not fetch an image that may still be readable (network, server, an expired session): a
+ * rasterization that fails with it can succeed later, unlike a missing image or one that does not decode.
+ */
+export class ImageUnavailableError extends Error {
+ constructor(
+ readonly imageName: string,
+ options: { cause: unknown }
+ ) {
+ super(`Canvas image "${imageName}" could not be fetched.`, options);
+ this.name = 'ImageUnavailableError';
+ }
+}
+
+/**
+ * Acquires a short-lived decoded bitmap lease, coalescing concurrent decodes by image name. A resolver failure other
+ * than {@link CanvasImageMissingError} or cancellation rejects as {@link ImageUnavailableError}.
+ */
export const resolveBitmap = async (image: CanvasImageRef, deps: RasterizeDeps): Promise<DecodedBitmapLease> => {
deps.signal?.throwIfAborted();
const pool = deps.bitmapPool ?? createDecodedBitmapPool();
const lease = await pool.acquire(
image.imageName,
async (decodeSignal) => {
- const blob = await deps.resolver(image.imageName, decodeSignal);
+ let blob: Blob;
+ try {
+ blob = await deps.resolver(image.imageName, decodeSignal);
+ } catch (error) {
+ if (error instanceof CanvasImageMissingError || decodeSignal?.aborted) {
+ throw error;
+ }
+ throw new ImageUnavailableError(image.imageName, { cause: error });
+ }
decodeSignal?.throwIfAborted();
const bitmap = await deps.backend.createImageBitmap(blob);
if (decodeSignal?.aborted) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts
index fe0c772520..d106eca059 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/index.ts
@@ -13,7 +13,7 @@ import { rasterizeTextSource } from './textRasterizer';
export type { ImageResolver, RasterizeDeps, RasterizeResult } from './types';
export { rasterizeGradientSource } from './gradientRasterizer';
-export { rasterizeImageSource } from './imageRasterizer';
+export { CanvasImageMissingError, rasterizeImageSource } from './imageRasterizer';
export { rasterizePaintSource } from './paintRasterizer';
export { rasterizeShapeSource } from './shapeRasterizer';
export { rasterizeTextSource, textFontString, textFontVariationSettings } from './textRasterizer';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts
index 5f401f14b6..c176c36de6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/rasterizeSource.test.ts
@@ -8,6 +8,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { ImageResolver, RasterizeDeps } from './types';
+import { CanvasImageMissingError, ImageUnavailableError } from './imageRasterizer';
import { rasterizeSource } from './index';
const imageRef = (imageName: string, width = 32, height = 16): CanvasImageRef => ({ height, imageName, width });
@@ -35,6 +36,30 @@ const makeDeps = (resolver: ImageResolver, backend: RasterBackend): RasterizeDep
store: createLayerCacheStore(backend),
});
+describe('rasterizeSource — image resolution failures', () => {
+ const rasterizeWith = (resolver: ImageResolver, backend = createSpyBackend().backend) =>
+ rasterizeSource({ image: imageRef('cat'), type: 'image' }, makeDeps(resolver, backend));
+
+ it('passes a missing image on as missing, so the layer reads as unreadable', async () => {
+ const missing = new CanvasImageMissingError('cat');
+ await expect(rasterizeWith(() => Promise.reject(missing))).rejects.toBe(missing);
+ });
+
+ it('wraps any other resolver failure as unavailable, keeping the cause', async () => {
+ const outage = new Error('Failed to load canvas image "cat" (503)');
+ const rejection = rasterizeWith(() => Promise.reject(outage));
+ await expect(rejection).rejects.toBeInstanceOf(ImageUnavailableError);
+ await expect(rejection).rejects.toMatchObject({ cause: outage, imageName: 'cat' });
+ });
+
+ it('leaves an image that was fetched but does not decode as a plain failure', async () => {
+ const { backend } = createSpyBackend();
+ const corrupt = new Error('decode failed');
+ backend.createImageBitmap = vi.fn(() => Promise.reject(corrupt));
+ await expect(rasterizeWith(() => Promise.resolve(new Blob()), backend)).rejects.toBe(corrupt);
+ });
+});
+
describe('rasterizeSource — image', () => {
it('gives the shared image resolver a cancellable pool-owned signal', async () => {
const { backend } = createSpyBackend();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts
index 8bddb1647e..344d3e4070 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/types.ts
@@ -4,7 +4,12 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
-/** Resolves persisted image names to decode blobs; application networking stays behind this injectable seam. */
+/**
+ * Resolves persisted image names to decode blobs; application networking stays behind this injectable seam. A resolver
+ * throws {@link CanvasImageMissingError} when the image is missing or not readable by this user, so the layer reads
+ * as unreadable until its source changes. Any other failure (network, server, an expired session) is taken as
+ * transient: operations report `not-ready`, and asking again or the display after its backoff tries again.
+ */
export type ImageResolver = (imageName: string, signal?: AbortSignal) => Promise<Blob>;
/** A text source whose family may be replaced by an injected custom-font alias. */
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
index 1994a1784e..28def4a45b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
@@ -1,5 +1,5 @@
import type { GalleryImage } from '@features/gallery';
-import type { AdjustmentRefusal, CanvasLayerCapability } from '@workbench/canvas-engine/api';
+import type { AdjustmentRefusal, CanvasLayerCapability, LayerUnreadable } from '@workbench/canvas-engine/api';
import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project } from '@workbench/projectContracts';
@@ -28,7 +28,8 @@ export type CreateFromBboxDestination = 'global-reference' | CreateFromBboxLayer
export type CreateFromBboxResult =
| { status: 'created'; destination: CreateFromBboxLayerDestination; layerIds: string[] }
| { status: 'uploaded'; image: CanvasImageUploadResult }
- | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal
| { status: 'blocked' | 'stale-document' | 'stale-project' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
index a366bde858..3aa7cc130a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
@@ -20,7 +20,6 @@ describe('getCreateFromBboxNotice', () => {
['stale', 'info', 'widgets.canvas.contextMenu.stale'],
['not-ready', 'info', 'widgets.canvas.contextMenu.notReady'],
['over-budget', 'info', 'widgets.canvas.contextMenu.notReady'],
- ['unreadable', 'error', 'widgets.canvas.contextMenu.unreadable'],
['blocked', 'info', 'widgets.canvas.import.blocked'],
['stale-document', 'error', 'widgets.canvas.import.staleDocument'],
['stale-project', 'error', 'widgets.canvas.import.staleProject'],
@@ -28,6 +27,14 @@ describe('getCreateFromBboxNotice', () => {
expect(getCreateFromBboxNotice({ status })).toEqual({ kind, titleKey });
});
+ it('names the layer that could not be read', () => {
+ expect(getCreateFromBboxNotice({ layerId: 'layer-7', layerName: 'Sky', status: 'unreadable' })).toEqual({
+ kind: 'error',
+ options: { name: 'Sky' },
+ titleKey: 'widgets.canvas.contextMenu.unreadable',
+ });
+ });
+
it('passes an adjustment refusal on as an error for the view to word', () => {
const refusal = { ownerId: 'g', ownerName: 'Sky', reason: 'too-large', status: 'adjustment-refused' } as const;
expect(getCreateFromBboxNotice(refusal)).toEqual({ kind: 'error', refusal });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
index 4dd3fcc339..a465f14dd5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
@@ -16,8 +16,8 @@ export type CreateFromBboxNotice =
| 'widgets.canvas.contextMenu.notReady'
| 'widgets.canvas.contextMenu.stale'
| 'widgets.canvas.contextMenu.unreadable';
- /** `destination` is itself a translation key naming the created entity. */
- options?: CanvasImportNotice['options'] | { destination: string };
+ /** `destination` is itself a translation key naming the created entity; `name` names an unreadable layer. */
+ options?: CanvasImportNotice['options'] | { destination: string } | { name: string };
}
| { kind: 'error'; refusal: AdjustmentRefusal };
@@ -49,7 +49,7 @@ export const getCreateFromBboxNotice = (
case 'over-budget':
return { kind: 'info', titleKey: 'widgets.canvas.contextMenu.notReady' };
case 'unreadable':
- return { kind: 'error', titleKey: 'widgets.canvas.contextMenu.unreadable' };
+ return { kind: 'error', options: { name: result.layerName }, titleKey: 'widgets.canvas.contextMenu.unreadable' };
case 'adjustment-refused':
return { kind: 'error', refusal: result };
case 'blocked':
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
index ef50c45d51..1b3869b1c0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
@@ -1,5 +1,6 @@
import type {
AdjustmentRefusal,
+ LayerUnreadable,
CanvasDocumentCapability,
CanvasExportCapability,
CanvasLifecycleCapability,
@@ -10,7 +11,8 @@ export type CanvasCompositeRegion = 'canvas' | 'bbox';
export type ExportCanvasCompositeResult =
| { status: 'ok'; blob: Blob; rect: Rect }
- | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
export type CanvasCompositeExportEngine = {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index 229fdf9021..124db03dab 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -10,6 +10,7 @@ import type {
CanvasDocumentSnapshot,
CanvasRegionalGuidanceLayerContract,
CanvasStateContractV3,
+ LayerUnreadable,
} from '@workbench/canvas-engine/api';
import type { CaptureRasterSnapshotResult } from '@workbench/canvas-engine/rasterTransactions';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -128,7 +129,8 @@ export interface GenerationComposites {
export type ComposeForGenerationResult =
| { status: 'ok'; composites: GenerationComposites; dedupeCommit: GenerationCompositeDedupeCommit }
- | { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
index ee3049534a..11b12cc1f1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
@@ -1,4 +1,4 @@
-import type { AdjustmentRefusal } from '@workbench/canvas-engine/api';
+import type { AdjustmentRefusal, LayerUnreadable } from '@workbench/canvas-engine/api';
import type { Rect } from '@workbench/canvas-engine/types';
import type { Project } from '@workbench/projectContracts';
@@ -28,7 +28,8 @@ export type CanvasGallerySaveRegion = CanvasCompositeRegion;
export type SaveCanvasToGalleryResult =
/** `boardId` is where the image went: a board id, or `none` for Uncategorized. */
| { status: 'saved'; boardId: string; imageName: string }
- | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | LayerUnreadable
| AdjustmentRefusal;
const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, unknown> => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
index 6f9778f95f..7aceda1c6c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.test.ts
@@ -1,6 +1,7 @@
import type { CanvasEngine } from '@workbench/canvas-engine/api';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CanvasImageMissingError } from '@workbench/canvas-engine/api';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const registry = vi.hoisted(() => ({
acquire: vi.fn(),
@@ -12,7 +13,7 @@ vi.mock('./engineRegistry', () => ({
releaseEngine: registry.release,
}));
-import { createCanvasEngineResource } from './useCanvasEngine';
+import { createCanvasEngineResource, createImageResolver } from './useCanvasEngine';
describe('Canvas engine React resource', () => {
beforeEach(() => {
@@ -57,3 +58,36 @@ describe('Canvas engine React resource', () => {
expect(registry.release).toHaveBeenCalledTimes(2);
});
});
+
+describe('Canvas image resolver', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const resolveWith = (respond: () => Promise<Response>) => {
+ vi.stubGlobal('fetch', vi.fn(respond));
+ return createImageResolver()('cat.png');
+ };
+
+ it('returns the image body', async () => {
+ const blob = await resolveWith(() => Promise.resolve(new Response('pixels', { status: 200 })));
+ await expect(blob.text()).resolves.toBe('pixels');
+ });
+
+ it.each([403, 404, 410])('says a %i image is missing or not readable', async (status) => {
+ const rejection = resolveWith(() => Promise.resolve(new Response(null, { status })));
+ await expect(rejection).rejects.toBeInstanceOf(CanvasImageMissingError);
+ await expect(rejection).rejects.toMatchObject({ imageName: 'cat.png' });
+ });
+
+ it.each([401, 429, 500, 503])('fails a %i as a plain error, which may pass', async (status) => {
+ const rejection = resolveWith(() => Promise.resolve(new Response(null, { status })));
+ await expect(rejection).rejects.toThrow(`(${status})`);
+ await expect(rejection).rejects.not.toBeInstanceOf(CanvasImageMissingError);
+ });
+
+ it('passes a network error on as it is', async () => {
+ const offline = new TypeError('Failed to fetch');
+ await expect(resolveWith(() => Promise.reject(offline))).rejects.toBe(offline);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
index 5078e3f02f..66aa914a57 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
@@ -3,6 +3,7 @@ import type { CanvasEngine, ImageResolver } from '@workbench/canvas-engine/api';
import { useFontRuntime } from '@features/fonts/react';
import { galleryImageUrls } from '@features/gallery/utility';
import { getModelsSnapshot } from '@features/models';
+import { CanvasImageMissingError } from '@workbench/canvas-engine/api';
import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
import { getWorkbenchPreferences } from '@workbench/settings/store';
@@ -28,9 +29,16 @@ export interface CanvasEngineResource {
subscribe(listener: () => void): () => void;
}
-/** Fetches a persisted image asset to a Blob for the engine rasterizers. */
-const createImageResolver = (): ImageResolver => async (imageName, signal) => {
+/**
+ * Fetches a persisted image asset to a Blob for the engine rasterizers. 404 and 410 say the image does not exist and
+ * 403 that this user may not read it (access to its board was lost), which lasts too. A network error, an expired
+ * session (401) or any other status may pass, so the engine treats it as transient.
+ */
+export const createImageResolver = (): ImageResolver => async (imageName, signal) => {
const response = await fetch(galleryImageUrls.full(imageName), { signal });
+ if (response.status === 403 || response.status === 404 || response.status === 410) {
+ throw new CanvasImageMissingError(imageName);
+ }
if (!response.ok) {
throw new Error(`Failed to load canvas image "${imageName}" (${response.status})`);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
index 1869b2c3f3..0540f789f0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
@@ -130,39 +130,49 @@ describe('cropAllLayersToFrame', () => {
};
};
+ const unreadable = (layerName: string) => ({
+ layerId: layerName.toLowerCase(),
+ layerName,
+ status: 'unreadable' as const,
+ });
+
it.each([
- [{ cropped: 1, skippedLocked: 0, skippedUnreadable: 0 }, ['Cropped 1 layer to the frame', undefined]],
+ [{ cropped: 1, skippedLocked: 0, skippedUnreadable: [] }, ['Cropped 1 layer to the frame', undefined]],
[
- { cropped: 4, skippedLocked: 1, skippedUnreadable: 0 },
+ { cropped: 4, skippedLocked: 1, skippedUnreadable: [] },
['Cropped 4 layers to the frame', '1 locked layer skipped.'],
],
[
- { cropped: 2, skippedLocked: 3, skippedUnreadable: 0 },
+ { cropped: 2, skippedLocked: 3, skippedUnreadable: [] },
['Cropped 2 layers to the frame', '3 locked layers skipped.'],
],
[
- { cropped: 2, skippedLocked: 1, skippedUnreadable: 2 },
+ { cropped: 2, skippedLocked: 1, skippedUnreadable: [unreadable('Sky'), unreadable('Hills')] },
[
'Cropped 2 layers to the frame',
- '1 locked layer skipped. 2 layers could not be read and were left as they are.',
+ '1 locked layer skipped. “Sky” and 1 other layer could not be read and were left as they are.',
],
],
+ [
+ { cropped: 1, skippedLocked: 0, skippedUnreadable: [unreadable('Sky'), unreadable('Hills'), unreadable('Sea')] },
+ ['Cropped 1 layer to the frame', '“Sky” and 2 other layers could not be read and were left as they are.'],
+ ],
])('reports %o as cropped, with the layers it left as they were', async (counts, expected) => {
expect(await notices({ status: 'cropped', ...counts })).toEqual({ error: [], info: [], success: [expected] });
});
it('says nothing needed cropping, and that only unlocked layers were checked when some were skipped', async () => {
- expect((await notices({ skippedLocked: 0, skippedUnreadable: 0, status: 'nothing' })).info).toEqual([
+ expect((await notices({ skippedLocked: 0, skippedUnreadable: [], status: 'nothing' })).info).toEqual([
['Every layer already fits the frame', undefined],
]);
- expect((await notices({ skippedLocked: 2, skippedUnreadable: 0, status: 'nothing' })).info).toEqual([
+ expect((await notices({ skippedLocked: 2, skippedUnreadable: [], status: 'nothing' })).info).toEqual([
['Every unlocked layer already fits the frame', '2 locked layers skipped.'],
]);
});
it('reports a crop that left only unreadable layers uncropped as a failure, never as still loading', async () => {
- expect(await notices({ skippedLocked: 0, skippedUnreadable: 1, status: 'nothing' })).toEqual({
- error: [['No layer was cropped', '1 layer could not be read and was left as it is.']],
+ expect(await notices({ skippedLocked: 0, skippedUnreadable: [unreadable('Sky')], status: 'nothing' })).toEqual({
+ error: [['No layer was cropped', '“Sky” could not be read and was left as it is.']],
info: [],
success: [],
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
index bdc3eb7c01..97ce90ff6d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
@@ -75,8 +75,8 @@ export const getCropAllUnavailableReasonKey = (document: CanvasDocumentContractV
/**
* Crops every unlocked layer to the frame as one undo step and says what happened: how many layers it cropped, how
- * many locked or unreadable ones it left as they were, or that nothing needed cropping. The canvas menu and the
- * command share it.
+ * many locked ones it skipped, which layer could not be read (named, with a count of any others), or that nothing
+ * needed cropping. The canvas menu and the command share it.
*/
export const cropAllLayersToFrame = async (
layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>,
@@ -94,16 +94,24 @@ export const cropAllLayersToFrame = async (
case 'cropped':
case 'nothing': {
const { skippedLocked, skippedUnreadable } = result;
+ const [firstUnreadable] = skippedUnreadable;
const skipped =
[
skippedLocked > 0 ? t('widgets.canvas.contextMenu.croppedAllLayersSkipped', { count: skippedLocked }) : '',
- skippedUnreadable > 0 ? t('widgets.canvas.contextMenu.cropAllUnreadable', { count: skippedUnreadable }) : '',
+ !firstUnreadable
+ ? ''
+ : skippedUnreadable.length === 1
+ ? t('widgets.canvas.contextMenu.cropAllUnreadable', { name: firstUnreadable.layerName })
+ : t('widgets.canvas.contextMenu.cropAllUnreadableWithOthers', {
+ count: skippedUnreadable.length - 1,
+ name: firstUnreadable.layerName,
+ }),
]
.filter(Boolean)
.join(' ') || undefined;
if (result.status === 'cropped') {
notify.success(t('widgets.canvas.contextMenu.croppedAllLayers', { count: result.cropped }), skipped);
- } else if (skippedUnreadable > 0) {
+ } else if (firstUnreadable) {
// Those layers needed cropping and could not be read: nothing the user asked for happened.
notify.error(t('widgets.canvas.contextMenu.cropAllNoneCropped'), skipped);
} else {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 1664cf798a..2ad7c516f5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -1,5 +1,6 @@
import type {
AdjustmentRefusal,
+ LayerUnreadable,
CanvasDocumentContractV3,
CanvasEngine,
LayerStackMoveKind,
@@ -152,7 +153,7 @@ export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'eng
readonly notifyLayerDuplicateFailed: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;
- readonly reportLayerOperation: (refusal: LayerOperationRefusal | AdjustmentRefusal) => void;
+ readonly reportLayerOperation: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void;
readonly t: (key: string) => string;
}
@@ -313,7 +314,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
ctx.notifyLayerDuplicateFailed();
return;
}
- ctx.reportLayerOperation(result.status);
+ ctx.reportLayerOperation(result.status === 'unreadable' ? result : result.status);
})
.catch(() => {
// The engine keeps rejected transactions atomic; route both rejection
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index c13a1a6bbc..b66f45a372 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -703,6 +703,22 @@ describe('runCanvasInvocation', () => {
]);
});
+ it.each([
+ [
+ { layerId: 'layer-7', layerName: 'Sky', status: 'unreadable' } as const,
+ '“Sky” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again.',
+ ],
+ [{ status: 'not-ready' } as const, 'Some layers are still loading. Wait a moment, then invoke again.'],
+ ])('explains a %o capture and dispatches nothing', async (result, message) => {
+ const harness = makeHarness();
+ harness.deps.composeForGeneration = () => Promise.resolve(result);
+
+ await runCanvasInvocation(harness.deps);
+
+ expect(harness.submittedGraphs()).toHaveLength(0);
+ expect(harness.notices().map((notice) => notice.message)).toEqual([message]);
+ });
+
it('uses the frozen canvas and detached pixels after edits at composite, upload, and queue-dispatch boundaries', async () => {
let liveDocument = makeDoc([rasterLayer('frozen-layer')], 96);
liveDocument.bbox = { height: 64, width: 64, x: 7, y: 11 };
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 3dd32eae35..003531768a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -361,8 +361,10 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
: composed.status === 'adjustment-refused'
? ADJUSTMENT_REFUSAL_NOTICES[composed.reason](composed.ownerName)
: composed.status === 'unreadable'
- ? "A layer's image could not be read (it may have been deleted or damaged). Disable or delete that layer, then invoke again."
- : `The canvas could not be captured for generation (${composed.status}).`
+ ? `“${composed.layerName}” could not be read (its image may have been deleted or damaged). Disable or delete that layer, then invoke again.`
+ : composed.status === 'not-ready'
+ ? 'Some layers are still loading. Wait a moment, then invoke again.'
+ : `The canvas could not be captured for generation (${composed.status}).`
);
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
index 7aa1085a4a..ca402a1aa8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
@@ -48,7 +48,8 @@ vi.mock('@features/gallery/queries', async (importOriginal) => ({
}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string, options?: { board?: string }) => (options?.board ? `${key}: ${options.board}` : key),
+ t: (key: string, options?: { board?: string; name?: string }) =>
+ options?.board || options?.name ? `${key}: ${options.board ?? options.name}` : key,
}),
}));
@@ -138,14 +139,14 @@ describe('useCanvasGallerySave across surfaces', () => {
await act(() => menu.current!.save('canvas'));
expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(2);
});
- it('says a layer could not be read rather than that the canvas is still preparing', async () => {
- mocks.saveCanvasToGallery.mockResolvedValueOnce({ status: 'unreadable' });
+ it('names the layer that could not be read rather than saying the canvas is still preparing', async () => {
+ mocks.saveCanvasToGallery.mockResolvedValueOnce({ layerId: 'layer-7', layerName: 'Sky', status: 'unreadable' });
await act(() => header.current!.save('canvas'));
expect(mocks.notifyError).toHaveBeenCalledWith(
'widgets.canvas.contextMenu.saveError',
- 'widgets.canvas.contextMenu.unreadable'
+ 'widgets.canvas.contextMenu.unreadable: Sky'
);
expect(mocks.notifyInfo).not.toHaveBeenCalled();
expect(mocks.reportError).not.toHaveBeenCalled();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index b0f5acb1ec..dec73a2efa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -91,7 +91,10 @@ export const useCanvasGallerySave = (
} else if (result.status === 'adjustment-refused') {
notify.error(t('widgets.canvas.contextMenu.saveError'), describeAdjustmentRefusal(result, t));
} else if (result.status === 'unreadable') {
- notify.error(t('widgets.canvas.contextMenu.saveError'), t('widgets.canvas.contextMenu.unreadable'));
+ notify.error(
+ t('widgets.canvas.contextMenu.saveError'),
+ t('widgets.canvas.contextMenu.unreadable', { name: result.layerName })
+ );
} else {
notify.info(t('widgets.canvas.contextMenu.notReady'));
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
index 09d2fe82ee..8e3f6b421a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
@@ -8,6 +8,7 @@ import type {
CanvasLayerPreviewMutation,
CanvasDocumentModel,
DocumentRefusal,
+ LayerUnreadable,
MaskEditResult,
PrepareEditResult,
StructuralCommitResult,
@@ -29,7 +30,6 @@ export type LayerOperationRefusal =
| 'not-ready'
| 'over-budget'
| 'stale'
- | 'unreadable'
| 'unsupported';
const LAYER_OPERATION_KEYS: Record<LayerOperationRefusal, string> = {
@@ -41,7 +41,6 @@ const LAYER_OPERATION_KEYS: Record<LayerOperationRefusal, string> = {
'not-ready': 'widgets.layers.actions.notReady',
'over-budget': 'widgets.layers.actions.overBudget',
stale: 'widgets.layers.actions.stale',
- unreadable: 'widgets.layers.actions.unreadable',
unsupported: 'widgets.layers.actions.unsupported',
};
@@ -55,15 +54,21 @@ const ADJUSTMENT_REFUSAL_KEYS: Record<AdjustmentRefusalReason, string> = {
export const describeAdjustmentRefusal = (refusal: AdjustmentRefusal, t: TFunction): string =>
t(ADJUSTMENT_REFUSAL_KEYS[refusal.reason], { name: refusal.ownerName });
+/** Words a refusal that names its layer: an image that could not be read, or adjustments that could not run. */
+export const describeNamedRefusal = (refusal: AdjustmentRefusal | LayerUnreadable, t: TFunction): string =>
+ refusal.status === 'unreadable'
+ ? t('widgets.layers.actions.unreadable', { name: refusal.layerName })
+ : describeAdjustmentRefusal(refusal, t);
+
/** Explains a refused layer pixel operation; nothing changed in the document, pixels or history. */
export const reportLayerOperation = (
- refusal: LayerOperationRefusal | AdjustmentRefusal,
+ refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable,
reportError: (title: string, message: string) => void,
t: TFunction
): void =>
reportError(
t('widgets.layers.actions.actionFailed'),
- typeof refusal === 'string' ? t(LAYER_OPERATION_KEYS[refusal]) : describeAdjustmentRefusal(refusal, t)
+ typeof refusal === 'string' ? t(LAYER_OPERATION_KEYS[refusal]) : describeNamedRefusal(refusal, t)
);
/** Explains a refused mask clear or invert; `busy` and a mask with nothing to change stay silent. */
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
index 98d3be391c..f427b99924 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
@@ -7,7 +7,7 @@ import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
import { ChakraProvider } from '@chakra-ui/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
-import { getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { CanvasImageMissingError, getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';
import {
groupContract,
layerContract,
@@ -83,7 +83,7 @@ const maskLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): Ca
/**
* Renders the Layers panel's layer menu over a real engine for `nodes`, with `selectedIds` selected in the panel (the
- * first as primary), returning a way to open it on a layer. Images named in `unreadable` fail to load.
+ * first as primary), returning a way to open it on a layer. Images named in `unreadable` no longer exist.
*/
const renderMenu = async (
nodes: CanvasNodeContract[],
@@ -110,7 +110,7 @@ const renderMenu = async (
const engine = createCanvasEngine({
ensureProjectOnServer: () => Promise.resolve(),
imageResolver: (imageName) =>
- unreadable.includes(imageName) ? Promise.reject(new Error('image deleted')) : Promise.resolve(pixels),
+ unreadable.includes(imageName) ? Promise.reject(new CanvasImageMissingError(imageName)) : Promise.resolve(pixels),
mutationPort: createCanvasProjectMutationPort(store, projectId),
projectId,
reportError: () => undefined,
@@ -196,10 +196,10 @@ describe('Layers context menu over a real engine', () => {
['Crop layer to frame', ['gone'], []],
['Merge selected layers', ['gone', 'kept'], ['kept']],
] as const)(
- 'says %s could not read a missing image, never that it is still loading',
+ 'says %s could not read a missing image, naming its layer, never that it is still loading',
async (label, ids, readable) => {
const { document, notices, openMenu } = await renderMenu(
- ids.map(imageLayer),
+ ids.map((id) => (id === 'gone' ? { ...imageLayer(id), name: 'Sky' } : imageLayer(id))),
ids,
ids.filter((id) => !(readable as readonly string[]).includes(id)).map((id) => `${id}.png`)
);
@@ -211,7 +211,7 @@ describe('Layers context menu over a real engine', () => {
await vi.waitFor(() =>
expect(notices()).toContainEqual([
'Layer action failed',
- "A layer's image could not be read (it may have been deleted or damaged), so nothing was changed.",
+ '“Sky” could not be read (its image may have been deleted or damaged), so nothing was changed. Delete or replace that layer, then try again.',
])
);
expect(notices().flat()).not.toContain('The layer content is still loading. Try again shortly.');
@@ -219,6 +219,17 @@ describe('Layers context menu over a real engine', () => {
}
);
+ it('describes Add regenerate region under its label', async () => {
+ const { openMenu } = await renderMenu([imageLayer('art')]);
+
+ await openMenu('art');
+
+ const regenerate = document.querySelector('[role="menuitem"][data-value="add-regenerate-region"]');
+ expect(regenerate?.textContent).toBe(
+ 'Add regenerate regionRegenerate where this layer has content, as a live inpaint mask.'
+ );
+ });
+
it('keeps an unavailable Merge masks reachable by keyboard and says why', async () => {
const { engine, openMenu } = await renderMenu(
[maskLayer('m1'), maskLayer('m2', { noise: { isEnabled: true, level: 0.5 } } as Partial<CanvasLayerContract>)],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 114dc91b2c..c57d6d4704 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -9,6 +9,7 @@ import type {
CanvasMaskNoiseContract,
BooleanRasterOperation,
LayerStackMoveKind,
+ LayerUnreadable,
RegionalGuidanceReferenceImage,
} from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
@@ -49,7 +50,7 @@ import {
useLayerQuickSwitch,
} from '@workbench/widgets/canvas/engineStoreHooks';
import {
- describeAdjustmentRefusal,
+ describeNamedRefusal,
reportLayerOperation,
usePreparedCommit,
} from '@workbench/widgets/canvas/useStructuralCommit';
@@ -166,7 +167,6 @@ type LayerActionErrorStatus =
| 'missing'
| 'not-ready'
| 'over-budget'
- | 'unreadable'
| 'unsupported';
const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {
@@ -179,7 +179,6 @@ const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {
missing: 'widgets.layers.actions.missing',
'not-ready': 'widgets.layers.actions.notReady',
'over-budget': 'widgets.layers.actions.overBudget',
- unreadable: 'widgets.layers.actions.unreadable',
unsupported: 'widgets.layers.actions.unsupported',
};
@@ -379,8 +378,8 @@ const LayerMenu = ({
);
const makeStatusError = useCallback(
- (status: LayerActionErrorStatus | AdjustmentRefusal): Error =>
- new Error(typeof status === 'string' ? t(LAYER_ACTION_ERROR_KEYS[status]) : describeAdjustmentRefusal(status, t)),
+ (status: LayerActionErrorStatus | AdjustmentRefusal | LayerUnreadable): Error =>
+ new Error(typeof status === 'string' ? t(LAYER_ACTION_ERROR_KEYS[status]) : describeNamedRefusal(status, t)),
[t]
);
@@ -402,7 +401,7 @@ const LayerMenu = ({
return;
}
if (result.status !== 'nothing') {
- reportLayerOperation(result.status, notify.error, t);
+ reportLayerOperation(result.status === 'unreadable' ? result : result.status, notify.error, t);
return;
}
} catch {
@@ -441,7 +440,7 @@ const LayerMenu = ({
throw makeStatusError('not-ready');
}
const result = await engine.layers.mergeInpaintMasks(actionTargets({ layer, selectedIds }));
- if (isAdjustmentRefusal(result)) {
+ if (isAdjustmentRefusal(result) || result.status === 'unreadable') {
reportLayerOperation(result, notify.error, t);
} else if (result.status === 'ineligible') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.mergeMasksIneligible'));
@@ -457,12 +456,10 @@ const LayerMenu = ({
return;
}
void engine.layers.mergeSelectedRasterLayers(actionTargets({ layer, selectedIds })).then((result) => {
- if (isAdjustmentRefusal(result)) {
- notify.error(t('widgets.layers.actions.actionFailed'), describeAdjustmentRefusal(result, t));
+ if (typeof result === 'object') {
+ notify.error(t('widgets.layers.actions.actionFailed'), describeNamedRefusal(result, t));
} else if (result === 'not-ready') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeNotReady'));
- } else if (result === 'unreadable') {
- notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.unreadable'));
} else if (result === 'over-budget') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeOverBudget'));
} else if (result === 'failed') {
@@ -726,11 +723,11 @@ const LayerMenu = ({
case 'locked':
case 'empty':
case 'not-ready':
- case 'unreadable':
case 'over-budget':
throw makeStatusError(result.status);
case 'outside-frame':
throw new Error(t('widgets.layers.actions.cropOutsideFrame'));
+ case 'unreadable':
case 'adjustment-refused':
throw makeStatusError(result);
case 'busy':
@@ -750,7 +747,7 @@ const LayerMenu = ({
}
const result = await engine.exports.extractMaskedArea(layer.id);
if (result.status !== 'extracted') {
- throw makeStatusError(isAdjustmentRefusal(result) ? result : result.status);
+ throw makeStatusError(isAdjustmentRefusal(result) || result.status === 'unreadable' ? result : result.status);
}
}, [engine, layer.id, makeStatusError]);
@@ -783,7 +780,7 @@ const LayerMenu = ({
}
const result = await engine.layers.copyLayerToRaster(layer.id);
if (result.status !== 'copied') {
- throw makeStatusError(isAdjustmentRefusal(result) ? result : result.status);
+ throw makeStatusError(isAdjustmentRefusal(result) || result.status === 'unreadable' ? result : result.status);
}
}, [addCopy, engine, getActionLabel, layer, makeStatusError]);
@@ -803,7 +800,7 @@ const LayerMenu = ({
}
const result = await engine.layers.copyLayerToControl(layer.id);
if (result.status !== 'copied') {
- throw makeStatusError(isAdjustmentRefusal(result) ? result : result.status);
+ throw makeStatusError(isAdjustmentRefusal(result) || result.status === 'unreadable' ? result : result.status);
}
}, [addCopy, base, defaultControlModel, engine, getActionLabel, layer, makeStatusError]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
index e37a693c29..a0c392d027 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
@@ -184,7 +184,7 @@ export const LayerGroupContextMenu = ({
return;
}
if (result.status !== 'nothing') {
- reportLayerOperation(result.status, notify.error, t);
+ reportLayerOperation(result.status === 'unreadable' ? result : result.status, notify.error, t);
return;
}
} catch {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index e1a6259808..45a55b5d4d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -11,12 +11,7 @@ import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { useMountEffect } from '@platform/react/useMountEffect';
import { toaster } from '@platform/ui';
import { Scrollable } from '@platform/ui/Scrollable';
-import {
- getDocumentIndex,
- getDocumentNode,
- isAdjustmentRefusal,
- lookupDocumentNodeState,
-} from '@workbench/canvas-engine/api';
+import { getDocumentIndex, getDocumentNode, lookupDocumentNodeState } from '@workbench/canvas-engine/api';
import {
publishLayerPanelSelection,
readLayerPanelState,
@@ -27,7 +22,7 @@ import {
toggleLayerStackCollapsed,
} from '@workbench/layerPanelState';
import { useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';
-import { describeAdjustmentRefusal, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { describeNamedRefusal, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useCallback, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { defaultRangeExtractor, useVirtualizer, type Range } from 'react-hook-tanstack-virtual';
import { useTranslation } from 'react-i18next';
@@ -514,13 +509,7 @@ export const LayersTree = ({
void copyLayerToClipboard(key, { exportLayer: currentEngine.exports.exportBakedLayerBlob }).then(
(status) => {
if (status !== 'ok') {
- copyFailed(
- isAdjustmentRefusal(status)
- ? describeAdjustmentRefusal(status, t)
- : status === 'unreadable'
- ? t('widgets.layers.actions.unreadable')
- : undefined
- );
+ copyFailed(typeof status === 'object' ? describeNamedRefusal(status, t) : undefined);
}
},
() => copyFailed()
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
index a3aa9ed3df..04b0e9aeb0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts
@@ -1,5 +1,5 @@
import type { QueryClient } from '@tanstack/react-query';
-import type { AdjustmentRefusal, ExportBakedLayerBlobResult } from '@workbench/canvas-engine/api';
+import type { AdjustmentRefusal, ExportBakedLayerBlobResult, LayerUnreadable } from '@workbench/canvas-engine/api';
import { canOnBoard } from '@features/gallery/contracts';
import {
@@ -17,10 +17,14 @@ import {
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
-type LayerAssetExportFailureStatus = Exclude<ExportBakedLayerBlobResult['status'], 'ok' | 'adjustment-refused'>;
+type LayerAssetExportFailureStatus = Exclude<
+ ExportBakedLayerBlobResult['status'],
+ 'ok' | 'adjustment-refused' | 'unreadable'
+>;
type LayerAssetExportResult =
| { status: 'ok'; blob: Blob }
| { status: LayerAssetExportFailureStatus }
+ | LayerUnreadable
| AdjustmentRefusal;
interface CopyLayerToClipboardDeps extends ClipboardAccess {
@@ -31,9 +35,9 @@ interface CopyLayerToClipboardDeps extends ClipboardAccess {
export const copyLayerToClipboard = async (
layerId: string,
{ exportLayer, ...clipboard }: CopyLayerToClipboardDeps
-): Promise<'ok' | LayerAssetExportFailureStatus | AdjustmentRefusal> => {
+): Promise<'ok' | LayerAssetExportFailureStatus | LayerUnreadable | AdjustmentRefusal> => {
const result = await exportLayer(layerId, { includeDisabled: true });
- if (result.status === 'adjustment-refused') {
+ if (result.status === 'adjustment-refused' || result.status === 'unreadable') {
return result;
}
if (result.status !== 'ok') {
@@ -58,6 +62,7 @@ export type SaveLayerToBoardResult =
| 'board-view-only'
| 'board-unavailable'
| LayerAssetExportFailureStatus
+ | LayerUnreadable
| AdjustmentRefusal;
/**
@@ -92,7 +97,7 @@ export const saveLayerToBoard = async (
const result = await exportLayer(layerId, { includeDisabled: true, signal: owner.signal });
assertAccountScopeCurrent(owner);
- if (result.status === 'adjustment-refused') {
+ if (result.status === 'adjustment-refused' || result.status === 'unreadable') {
return result;
}
if (result.status !== 'ok') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.test.ts
index 1745639e9e..251102dc22 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
-import { getPsdExportNoticeKey } from './psdExportNotice';
+import { getPsdExportNotice } from './psdExportNotice';
-describe('getPsdExportNoticeKey', () => {
+describe('getPsdExportNotice', () => {
it.each([
['not-ready', 'widgets.layers.groupActions.exportNotReady'],
['too-large', 'widgets.layers.groupActions.exportTooLarge'],
@@ -10,8 +10,18 @@ describe('getPsdExportNoticeKey', () => {
['over-budget', 'widgets.layers.groupActions.exportOverBudget'],
['stale', 'widgets.layers.groupActions.exportStale'],
['aborted', 'widgets.layers.groupActions.exportAborted'],
- ['exported', null],
- ] as const)('maps %s to a user-visible typed notice', (result, expected) => {
- expect(getPsdExportNoticeKey(result)).toBe(expected);
+ ] as const)('maps %s to a user-visible typed notice', (result, key) => {
+ expect(getPsdExportNotice(result)).toEqual({ key });
+ });
+
+ it('names the layer that could not be read', () => {
+ expect(getPsdExportNotice({ layerId: 'layer-7', layerName: 'Sky', status: 'unreadable' })).toEqual({
+ key: 'widgets.layers.groupActions.exportUnreadable',
+ options: { name: 'Sky' },
+ });
+ });
+
+ it('has nothing to say once exported', () => {
+ expect(getPsdExportNotice('exported')).toBeNull();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
index 87505e742e..77855ef5c1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
@@ -9,26 +9,31 @@ export type PsdExportNoticeKey =
| 'widgets.layers.groupActions.exportUnreadable'
| 'widgets.layers.groupActions.exportAborted';
+/** A notice's translation key and interpolation; an unreadable layer is named. */
+export interface PsdExportNotice {
+ readonly key: PsdExportNoticeKey;
+ readonly options?: { readonly name: string };
+}
+
/** The notice for a non-refusal result; an `AdjustmentRefusal` is worded by `describeAdjustmentRefusal`. */
-export const getPsdExportNoticeKey = (
- result: Exclude<PsdExportResult, AdjustmentRefusal>
-): PsdExportNoticeKey | null => {
+export const getPsdExportNotice = (result: Exclude<PsdExportResult, AdjustmentRefusal>): PsdExportNotice | null => {
+ if (typeof result === 'object') {
+ return { key: 'widgets.layers.groupActions.exportUnreadable', options: { name: result.layerName } };
+ }
switch (result) {
case 'exported':
return null;
case 'not-ready':
- return 'widgets.layers.groupActions.exportNotReady';
+ return { key: 'widgets.layers.groupActions.exportNotReady' };
case 'too-large':
- return 'widgets.layers.groupActions.exportTooLarge';
+ return { key: 'widgets.layers.groupActions.exportTooLarge' };
case 'nothing':
- return 'widgets.layers.groupActions.exportNothing';
+ return { key: 'widgets.layers.groupActions.exportNothing' };
case 'over-budget':
- return 'widgets.layers.groupActions.exportOverBudget';
+ return { key: 'widgets.layers.groupActions.exportOverBudget' };
case 'stale':
- return 'widgets.layers.groupActions.exportStale';
- case 'unreadable':
- return 'widgets.layers.groupActions.exportUnreadable';
+ return { key: 'widgets.layers.groupActions.exportStale' };
case 'aborted':
- return 'widgets.layers.groupActions.exportAborted';
+ return { key: 'widgets.layers.groupActions.exportAborted' };
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts
index 336782ed0e..dbf5ce5a59 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts
@@ -55,7 +55,7 @@ export const useLayerSelectionCommands = (
}
if (result && result.status !== 'nothing') {
reportLayerOperation(
- result.status,
+ result.status === 'unreadable' ? result : result.status,
(title, description) => toaster.create({ description, title, type: 'warning' }),
t
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
index 3ab9d3c3ac..4b171d5c8d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
@@ -10,7 +10,11 @@ import {
isAdjustmentRefusal,
} from '@workbench/canvas-engine/api';
import { useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
-import { describeAdjustmentRefusal, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import {
+ describeAdjustmentRefusal,
+ describeNamedRefusal,
+ usePreparedCommit,
+} from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectName } from '@workbench/WorkbenchContext';
import { EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
import { useMemo } from 'react';
@@ -25,7 +29,7 @@ import {
stackVisibilityAxis,
type StackActionId,
} from './layerStackActions';
-import { getPsdExportNoticeKey } from './psdExportNotice';
+import { getPsdExportNotice } from './psdExportNotice';
import { useAddLayer } from './useAddLayer';
export type LayerStackActionsEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
@@ -93,9 +97,9 @@ export const useLayerStackActions = (
});
return;
}
- const noticeKey = getPsdExportNoticeKey(result);
- if (noticeKey) {
- toaster.create({ title: t(noticeKey), type: 'warning' });
+ const notice = getPsdExportNotice(result);
+ if (notice) {
+ toaster.create({ title: t(notice.key, notice.options), type: 'warning' });
}
})
.catch(() => toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' }));
@@ -111,20 +115,14 @@ export const useLayerStackActions = (
return;
}
void engine.layers.mergeVisibleRasterLayers().then((result) => {
- if (isAdjustmentRefusal(result)) {
+ if (typeof result === 'object') {
toaster.create({
- description: describeAdjustmentRefusal(result, t),
+ description: describeNamedRefusal(result, t),
title: t('widgets.layers.actions.actionFailed'),
- type: 'warning',
+ type: isAdjustmentRefusal(result) ? 'warning' : 'error',
});
} else if (result === 'not-ready') {
toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });
- } else if (result === 'unreadable') {
- toaster.create({
- description: t('widgets.layers.actions.unreadable'),
- title: t('widgets.layers.actions.actionFailed'),
- type: 'error',
- });
} else if (result === 'over-budget') {
toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });
} else if (result === 'failed') {