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(gallery): keep canvas-owned images out of assets

joshistoast148d179235ab
diff --git a/invokeai/app/services/image_records/image_records_common.py b/invokeai/app/services/image_records/image_records_common.py
index 3d4650b77a..44faa6305a 100644
--- a/invokeai/app/services/image_records/image_records_common.py
+++ b/invokeai/app/services/image_records/image_records_common.py
@@ -63,8 +63,16 @@ ASSETS_CATEGORIES: list[ImageCategory] = [
ImageCategory.CONTROL,
ImageCategory.MASK,
ImageCategory.USER,
- ImageCategory.OTHER,
]
+"""The categories the gallery's assets view lists.
+
+OTHER is deliberately absent: it is the private category for images a canvas
+layer owns (paint bitmaps, composites, adopted filter results). Those are layer
+pixels, not gallery content, so they belong to neither view. Because OTHER is in
+neither IMAGE_CATEGORIES nor ASSETS_CATEGORIES, such an image can stay durable —
+safe from intermediate garbage collection, which would strand the layer pointing
+at it — without ever surfacing in the gallery or in a board's counts.
+"""
class InvalidImageCategoryException(ValueError):
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 6b99068309..a4e0f69e6b 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -6,6 +6,8 @@ from typing import Optional, Union, cast
from invokeai.app.invocations.fields import MetadataField, MetadataFieldValidator
from invokeai.app.services.image_records.image_records_base import ImageRecordStorageBase
from invokeai.app.services.image_records.image_records_common import (
+ ASSETS_CATEGORIES,
+ IMAGE_CATEGORIES,
IMAGE_DTO_COLS,
ImageCategory,
ImageNamesResult,
@@ -569,11 +571,17 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
"""
query_params.append(user_id)
+ # Derived from the category constants rather than `!= 'general'`, so a
+ # category belonging to neither view (OTHER, owned by canvas layers) is
+ # counted by neither. These are enum values, never user input.
+ image_categories_sql = ",".join(f"'{c.value}'" for c in IMAGE_CATEGORIES)
+ assets_categories_sql = ",".join(f"'{c.value}'" for c in ASSETS_CATEGORIES)
+
query = f"""--sql
SELECT
DATE(images.created_at) as date,
- SUM(CASE WHEN images.image_category = 'general' THEN 1 ELSE 0 END) as image_count,
- SUM(CASE WHEN images.image_category != 'general' THEN 1 ELSE 0 END) as asset_count,
+ SUM(CASE WHEN images.image_category IN ({image_categories_sql}) THEN 1 ELSE 0 END) as image_count,
+ SUM(CASE WHEN images.image_category IN ({assets_categories_sql}) THEN 1 ELSE 0 END) as asset_count,
(
SELECT i2.image_name FROM images i2
WHERE DATE(i2.created_at) = DATE(images.created_at)
diff --git a/invokeai/frontend/web/src/features/gallery/store/types.ts b/invokeai/frontend/web/src/features/gallery/store/types.ts
index c040e5834d..bcc80800d7 100644
--- a/invokeai/frontend/web/src/features/gallery/store/types.ts
+++ b/invokeai/frontend/web/src/features/gallery/store/types.ts
@@ -15,8 +15,14 @@ export type OrderDir = z.infer<typeof zOrderDir>;
const zBoardRecordOrderBy = z.enum(['created_at', 'board_name']);
export type BoardRecordOrderBy = z.infer<typeof zBoardRecordOrderBy>;
+// Mirrors the backend's IMAGE_CATEGORIES / ASSETS_CATEGORIES
+// (image_records_common.py). 'other' is in neither: it is the private category
+// for images a canvas layer owns, which are layer pixels rather than gallery
+// content. The list endpoint filters by whatever categories the client sends,
+// so leaving 'other' here would list those images in the assets view while the
+// board counts — which come from the backend constant — excluded them.
export const IMAGE_CATEGORIES: ImageCategory[] = ['general'];
-export const ASSETS_CATEGORIES: ImageCategory[] = ['control', 'mask', 'user', 'other'];
+export const ASSETS_CATEGORIES: ImageCategory[] = ['control', 'mask', 'user'];
export const zGalleryState = z.object({
selection: z.array(z.string()),
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 13dcfb4a7c..33c118ff0a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -256,3 +256,42 @@ describe('imageMakeCanvasAssetChanges', () => {
expect(imageMakeCanvasAssetChanges().is_intermediate).toBe(false);
});
});
+
+describe('gallery category queries', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchJson.mockResolvedValue({ items: [], limit: 20, offset: 0, total: 0 });
+ });
+
+ const categoriesFor = async (galleryView: 'images' | 'assets'): Promise<string[]> => {
+ await listGalleryImages({ boardId: 'board-1', galleryView, searchTerm: '' });
+ const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;
+
+ return new URLSearchParams(url.split('?')[1]).getAll('categories');
+ };
+
+ it('never asks the assets view for the canvas-owned category', async () => {
+ // The regression this guards: canvas paint bitmaps, composites and adopted
+ // filter results all upload as `other`. While `other` was an assets
+ // category, every brush stroke and every generation put an image in the
+ // user's Assets tab.
+ expect(await categoriesFor('assets')).not.toContain('other');
+ });
+
+ it('lists only user-facing categories in the assets view', async () => {
+ expect(await categoriesFor('assets')).toEqual(['control', 'mask', 'user']);
+ });
+
+ it('lists only general in the images view', async () => {
+ expect(await categoriesFor('images')).toEqual(['general']);
+ });
+
+ it('leaves the canvas category out of both views', async () => {
+ const assets = await categoriesFor('assets');
+
+ mocks.apiFetchJson.mockClear();
+ const images = await categoriesFor('images');
+
+ expect([...assets, ...images]).not.toContain('other');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 6dfc36e97f..2284158fbb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -58,8 +58,14 @@ interface ListImagesResponse {
total: number;
}
+/**
+ * Mirrors the backend's `IMAGE_CATEGORIES` / `ASSETS_CATEGORIES`
+ * (`image_records_common.py`). `'other'` is in neither: it is the private
+ * category for images a canvas layer owns, which are layer pixels rather than
+ * gallery content and so belong to neither view.
+ */
const imageCategories = ['general'];
-const assetCategories = ['control', 'mask', 'user', 'other'];
+const assetCategories = ['control', 'mask', 'user'];
const toSearchParams = (entries: Record<string, boolean | number | string | string[] | undefined>): string => {
const params = new URLSearchParams();
@@ -390,8 +396,9 @@ export const imageMakeDurableChanges = (): { is_intermediate: false } => ({
* A node's output is `general` by default, which is exactly what the gallery's
* Images view lists — so promoting a control-layer filter result with
* {@link imageMakeDurableChanges} alone published every ControlNet preprocess
- * into the user's gallery. These are layer pixels, not gallery images: they
- * belong with the rest of the canvas's assets.
+ * into the user's gallery. These are layer pixels, not gallery images, and
+ * `'other'` belongs to neither {@link imageCategories} nor
+ * {@link assetCategories}, so they surface in neither view.
*/
export const imageMakeCanvasAssetChanges = (): { is_intermediate: false; image_category: 'other' } => ({
image_category: 'other',
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 bdc1e09fcc..b9fd0ceccb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -48,6 +48,7 @@ import type { StrokeCommittedEvent } from './tools/tool';
import { createBitmapStore } from './document/bitmapStore';
import { mergeDownMatrix } from './document/mergeDown';
+import { createCanvasEngine as createCoreCanvasEngine } from './engine';
interface EngineStore {
dispatch(action: EngineTestAction): void;
@@ -1039,6 +1040,32 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
+ it('uploads per-generation composites through the intermediate seam, not the durable one', async () => {
+ // Both consumers once shared a single un-parameterised `uploadImage`, so
+ // every invocation's base/mask composite was stored as a permanent image.
+ // Nothing in the document ever points at a composite, so it must be
+ // reclaimable; only pixels a layer references may be durable.
+ const doc = makeDoc();
+ const { store } = createFakeStore(doc);
+ const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'durable', width: 1 }));
+ const uploadIntermediateImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'transient', width: 1 }));
+ const { engine } = createCoreCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort: createTestMutationPort(store, 'p1'),
+ projectId: 'p1',
+ reportError: () => undefined,
+ uploadImage,
+ uploadIntermediateImage,
+ });
+
+ await engine.exports.getCompositeExecutorDeps().uploadImage(new Blob());
+
+ expect(uploadIntermediateImage).toHaveBeenCalledOnce();
+ expect(uploadImage).not.toHaveBeenCalled();
+ engine.lifecycle.dispose();
+ });
+
it('keeps an in-flight invocation reservation accounted through cooldown', async () => {
const { engine } = createEngine();
const deps = engine.exports.getCompositeExecutorDeps();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 6b4a4875cd..8f176740a5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -239,8 +239,18 @@ export interface CanvasEngineErrorReport {
export interface CanvasEngineOptions {
projectId: string;
mutationPort: CanvasProjectMutationPort;
- /** Persists encoded engine-owned bitmaps. Application networking stays outside the core. */
+ /**
+ * Persists encoded engine-owned bitmaps DURABLY. A layer's document points at
+ * the resulting image name, so the upload must not be garbage-collectable.
+ * Application networking stays outside the core.
+ */
uploadImage(blob: Blob): Promise<{ height: number; imageName: string; width: number }>;
+ /**
+ * Uploads a TRANSIENT image — one no layer will reference, such as a
+ * per-generation composite. Marked intermediate so it is reclaimable instead
+ * of accumulating one durable image per invocation forever.
+ */
+ uploadIntermediateImage(blob: Blob): Promise<{ height: number; imageName: string; width: number }>;
/** Supplies the currently selected model base for core-created control layer contracts. */
getMainModelBase?: () => string | null;
/** Supplies the default control model key for core-created control layer contracts. */
@@ -2275,7 +2285,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
syncMemoryBaselines();
return rasterController.memory.reserveOperation(bytes, { purpose: 'invocation-composite' });
},
- uploadImage: (blob) => opts.uploadImage(blob),
+ // Generation inputs, not layer pixels: nothing in the document will point at
+ // these, so they upload as intermediates rather than durable images.
+ uploadImage: (blob) => opts.uploadIntermediateImage(blob),
});
const exportRasterComposite = (request: RasterCompositeExportRequest) =>
exportRasterCompositeWithDeps(request, {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
index 81c2791491..7be55be79f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/backend/canvasImages.ts
@@ -4,9 +4,14 @@
* inline data), so the persisted workbench document — which autosaves to
* localStorage (~5 MB) — stays ref-only and the pixels live server-side.
*
- * `image_category='other'` + `is_intermediate=false` keeps the bitmap durable
- * (not garbage-collected as an intermediate) while hiding it from the gallery's
- * general/asset views.
+ * `image_category='other'` is the canvas's private category: the backend lists
+ * it in neither `IMAGE_CATEGORIES` nor `ASSETS_CATEGORIES`
+ * (`image_records_common.py`), so it surfaces in neither gallery view nor in a
+ * board's counts. That is what hides it — NOT `is_intermediate`, which is a
+ * separate axis. `is_intermediate=false` is what keeps it durable, and every
+ * image a layer points at must be durable or garbage collection would strand
+ * the layer. Transient images no layer will reference (per-generation
+ * composites) pass `isIntermediate: true` instead.
*
* The `fetch` seam is injectable so this runs in node tests without a DOM.
* Auth + base-URL resolution mirror the shared HTTP client so uploads carry the
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
index 02ac2ccc9e..1a112c7a5f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts
@@ -15,7 +15,10 @@ import type { CanvasOperationCapability, CanvasOperationImplementation } from '.
import { attachCanvasOperations } from './operationAccess';
-export interface CanvasEngineOptions extends Omit<CoreCanvasEngineOptions, 'uploadImage' | 'getMainModelBase'> {
+export interface CanvasEngineOptions extends Omit<
+ CoreCanvasEngineOptions,
+ 'uploadImage' | 'uploadIntermediateImage' | 'getMainModelBase'
+> {
getMainModelBase?: () => string | null;
selectObjectDeps?: {
uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ height: number; imageName: string; width: number }>;
@@ -46,6 +49,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =
...coreOptions,
getMainModelBase: options.getMainModelBase,
uploadImage: (blob) => canvasApplicationPort.uploadImage(blob),
+ uploadIntermediateImage: (blob) => canvasApplicationPort.uploadImage(blob, { isIntermediate: true }),
});
const { applicationHost: host } = composition;
const core = composition.engine;
diff --git a/tests/app/services/test_image_category_views.py b/tests/app/services/test_image_category_views.py
new file mode 100644
index 0000000000..8d049f85ef
--- /dev/null
+++ b/tests/app/services/test_image_category_views.py
@@ -0,0 +1,75 @@
+"""Pins which image categories each gallery view lists.
+
+`OTHER` is the private category for images a canvas layer owns — paint bitmaps,
+composited layer pixels, adopted filter results. Those are layer pixels rather
+than gallery content, so they must appear in neither the images view nor the
+assets view, while still being non-intermediate so garbage collection cannot
+strand the layer pointing at them.
+
+Regression guarded: while `OTHER` was an assets category, every brush stroke and
+every canvas operation added an image to the user's Assets tab.
+"""
+
+from invokeai.app.services.image_records.image_records_common import (
+ ASSETS_CATEGORIES,
+ IMAGE_CATEGORIES,
+ ImageCategory,
+ ResourceOrigin,
+)
+from invokeai.app.services.invocation_services import InvocationServices
+
+
+def _save(services: InvocationServices, image_name: str, category: ImageCategory) -> None:
+ services.image_records.save(
+ image_name=image_name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=category,
+ width=10,
+ height=10,
+ has_workflow=False,
+ )
+
+
+def test_other_belongs_to_neither_view() -> None:
+ assert ImageCategory.OTHER not in IMAGE_CATEGORIES
+ assert ImageCategory.OTHER not in ASSETS_CATEGORIES
+
+
+def test_the_two_views_never_overlap() -> None:
+ assert set(IMAGE_CATEGORIES).isdisjoint(ASSETS_CATEGORIES)
+
+
+def test_assets_view_excludes_canvas_owned_images(mock_services: InvocationServices) -> None:
+ _save(mock_services, "painted.png", ImageCategory.OTHER)
+ _save(mock_services, "uploaded.png", ImageCategory.USER)
+
+ result = mock_services.image_records.get_many(offset=0, limit=10, categories=ASSETS_CATEGORIES)
+
+ assert [record.image_name for record in result.items] == ["uploaded.png"]
+
+
+def test_images_view_excludes_canvas_owned_images(mock_services: InvocationServices) -> None:
+ _save(mock_services, "painted.png", ImageCategory.OTHER)
+ _save(mock_services, "generated.png", ImageCategory.GENERAL)
+
+ result = mock_services.image_records.get_many(offset=0, limit=10, categories=IMAGE_CATEGORIES)
+
+ assert [record.image_name for record in result.items] == ["generated.png"]
+
+
+def test_date_board_counts_ignore_canvas_owned_images(mock_services: InvocationServices) -> None:
+ """`get_image_dates` derives its counts from the category constants.
+
+ It previously classified every non-`general` image as an asset, which would
+ keep counting canvas-owned images after they left the assets view — leaving
+ the date board's badge disagreeing with the images it actually lists.
+ """
+ _save(mock_services, "painted.png", ImageCategory.OTHER)
+ _save(mock_services, "uploaded.png", ImageCategory.USER)
+ _save(mock_services, "generated.png", ImageCategory.GENERAL)
+
+ dates = mock_services.image_records.get_image_dates()
+
+ assert len(dates) == 1
+ assert dates[0].image_count == 1
+ assert dates[0].asset_count == 1