Skip to content

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

feat(gallery): filter polymorphic items by created range

joshistoast8359375a5768
diff --git a/invokeai/app/api/routers/gallery.py b/invokeai/app/api/routers/gallery.py
index a70822c5af..0cecd05615 100644
--- a/invokeai/app/api/routers/gallery.py
+++ b/invokeai/app/api/routers/gallery.py
@@ -1,3 +1,4 @@
+from datetime import date
from typing import Optional
from fastapi import HTTPException, Query
@@ -38,6 +39,12 @@ async def list_gallery_items(
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred items first"),
search_term: Optional[str] = Query(default=None, description="The term to search for"),
+ created_from: Optional[date] = Query(
+ default=None, description="Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ ),
+ created_to: Optional[date] = Query(
+ default=None, description="Inclusive end date (YYYY-MM-DD) to filter by created_at."
+ ),
) -> OffsetPaginatedResults[GalleryItem]:
"""Returns a paginated, time-sorted stream of polymorphic gallery items (images + videos)."""
if board_id is not None and board_id != "none":
@@ -55,6 +62,8 @@ async def list_gallery_items(
search_term=search_term,
user_id=current_user.user_id,
is_admin=current_user.is_admin,
+ created_from=created_from.isoformat() if created_from else None,
+ created_to=created_to.isoformat() if created_to else None,
)
@@ -78,6 +87,12 @@ async def get_gallery_item_names(
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred items first"),
search_term: Optional[str] = Query(default=None, description="The term to search for"),
+ created_from: Optional[date] = Query(
+ default=None, description="Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ ),
+ created_to: Optional[date] = Query(
+ default=None, description="Inclusive end date (YYYY-MM-DD) to filter by created_at."
+ ),
) -> GalleryItemNamesResult:
"""Returns an ordered (kind, name) list — used to drive virtualized gallery selection."""
if board_id is not None and board_id != "none":
@@ -94,6 +109,8 @@ async def get_gallery_item_names(
search_term=search_term,
user_id=current_user.user_id,
is_admin=current_user.is_admin,
+ created_from=created_from.isoformat() if created_from else None,
+ created_to=created_to.isoformat() if created_to else None,
)
except Exception:
raise HTTPException(status_code=500, detail="Failed to get gallery item names")
diff --git a/invokeai/app/services/gallery/gallery_base.py b/invokeai/app/services/gallery/gallery_base.py
index bd6591884d..1366308a53 100644
--- a/invokeai/app/services/gallery/gallery_base.py
+++ b/invokeai/app/services/gallery/gallery_base.py
@@ -25,6 +25,8 @@ class GalleryServiceABC(ABC):
search_term: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
) -> OffsetPaginatedResults[GalleryItem]:
"""Lists a paginated, time-sorted stream of image + video items."""
pass
@@ -42,11 +44,15 @@ class GalleryServiceABC(ABC):
user_id: Optional[str] = None,
is_admin: bool = False,
created_date: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
) -> GalleryItemNamesResult:
"""Returns ordered (kind, name) refs for optimistic UI / virtualized lists.
`created_date` restricts the result to items created on the given ISO date — used by
date-based virtual boards.
+
+ `created_from` and `created_to` are inclusive YYYY-MM-DD bounds on created_at (UTC days).
"""
pass
diff --git a/invokeai/app/services/gallery/gallery_default.py b/invokeai/app/services/gallery/gallery_default.py
index a0f2fe1f39..dbb6efb088 100644
--- a/invokeai/app/services/gallery/gallery_default.py
+++ b/invokeai/app/services/gallery/gallery_default.py
@@ -47,6 +47,8 @@ class SqliteGalleryService(GalleryServiceABC):
search_term: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
) -> OffsetPaginatedResults[GalleryItem]:
image_half, image_params, image_count_query = self._build_half(
kind="image",
@@ -57,6 +59,8 @@ class SqliteGalleryService(GalleryServiceABC):
search_term=search_term,
user_id=user_id,
is_admin=is_admin,
+ created_from=created_from,
+ created_to=created_to,
)
video_half, video_params, video_count_query = self._build_half(
kind="video",
@@ -67,6 +71,8 @@ class SqliteGalleryService(GalleryServiceABC):
search_term=search_term,
user_id=user_id,
is_admin=is_admin,
+ created_from=created_from,
+ created_to=created_to,
)
order_clause = self._build_order_clause(starred_first, order_dir)
@@ -112,6 +118,8 @@ class SqliteGalleryService(GalleryServiceABC):
user_id: Optional[str] = None,
is_admin: bool = False,
created_date: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
) -> GalleryItemNamesResult:
image_half, image_params, _ = self._build_half(
kind="image",
@@ -124,6 +132,8 @@ class SqliteGalleryService(GalleryServiceABC):
is_admin=is_admin,
names_only=True,
created_date=created_date,
+ created_from=created_from,
+ created_to=created_to,
)
video_half, video_params, _ = self._build_half(
kind="video",
@@ -136,6 +146,8 @@ class SqliteGalleryService(GalleryServiceABC):
is_admin=is_admin,
names_only=True,
created_date=created_date,
+ created_from=created_from,
+ created_to=created_to,
)
order_clause = self._build_order_clause(starred_first, order_dir)
@@ -343,6 +355,8 @@ class SqliteGalleryService(GalleryServiceABC):
is_admin: bool,
names_only: bool = False,
created_date: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
) -> tuple[str, list[Union[int, str, bool]], str]:
"""Builds one half of the union (either `images` or `videos`).
@@ -418,6 +432,14 @@ class SqliteGalleryService(GalleryServiceABC):
conditions += f" AND DATE({base_table}.created_at) = ? "
params.append(created_date)
+ if created_from is not None:
+ conditions += f" AND {base_table}.created_at >= ? "
+ params.append(created_from)
+
+ if created_to is not None:
+ conditions += f" AND {base_table}.created_at < DATE(?, '+1 day') "
+ params.append(created_to)
+
if board_id == "none":
conditions += f" AND {join_table}.board_id IS NULL "
if user_id is not None and not is_admin:
diff --git a/tests/app/routers/test_gallery.py b/tests/app/routers/test_gallery.py
new file mode 100644
index 0000000000..ae1219fcd7
--- /dev/null
+++ b/tests/app/routers/test_gallery.py
@@ -0,0 +1,60 @@
+"""Router contracts for polymorphic gallery filtering."""
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi.testclient import TestClient
+
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.gallery.gallery_common import GalleryItemNamesResult
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.pagination import OffsetPaginatedResults
+
+
+class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker: Invoker) -> None:
+ self.invoker = invoker
+
+
+def _prepare_gallery_router_test(monkeypatch: Any, mock_invoker: Invoker) -> tuple[MagicMock, MagicMock]:
+ dependencies = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.gallery.ApiDependencies", dependencies)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", dependencies)
+
+ list_items = MagicMock(return_value=OffsetPaginatedResults(items=[], offset=0, limit=10, total=0))
+ list_item_names = MagicMock(return_value=GalleryItemNamesResult(items=[], starred_count=0, total_count=0))
+ monkeypatch.setattr(mock_invoker.services.gallery, "list_items", list_items)
+ monkeypatch.setattr(mock_invoker.services.gallery, "list_item_names", list_item_names)
+ return list_items, list_item_names
+
+
+ ("path", "service_index"),
+ [("/api/v1/gallery/items/", 0), ("/api/v1/gallery/items/names", 1)],
+)
+def test_gallery_list_endpoints_parse_and_forward_created_ranges(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, service_index: int
+) -> None:
+ service_calls = _prepare_gallery_router_test(monkeypatch, mock_invoker)
+
+ response = client.get(path, params={"created_from": "2026-07-01", "created_to": "2026-07-15"})
+
+ assert response.status_code == 200
+ kwargs = service_calls[service_index].call_args.kwargs
+ assert kwargs["created_from"] == "2026-07-01"
+ assert kwargs["created_to"] == "2026-07-15"
+
+
[email protected]("path", ["/api/v1/gallery/items/", "/api/v1/gallery/items/names"])
[email protected]("param", ["created_from", "created_to"])
+def test_gallery_list_endpoints_reject_invalid_created_range_dates(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, param: str
+) -> None:
+ _prepare_gallery_router_test(monkeypatch, mock_invoker)
+
+ response = client.get(path, params={param: "2026-02-31"})
+
+ assert response.status_code == 422
diff --git a/tests/app/services/gallery/test_gallery_default.py b/tests/app/services/gallery/test_gallery_default.py
index 7bf410b23c..402c5e1188 100644
--- a/tests/app/services/gallery/test_gallery_default.py
+++ b/tests/app/services/gallery/test_gallery_default.py
@@ -15,6 +15,8 @@ Covers JPPhoto's code-review findings (PR #9163):
``list_item_names`` so virtual boards cover both kinds.
"""
+from types import SimpleNamespace
+
import pytest
from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
@@ -123,6 +125,35 @@ def _backdate(services, table: str, name_col: str, name: str, created_at: str) -
cursor.execute(f"UPDATE {table} SET created_at = ? WHERE {name_col} = ?", (created_at, name))
+def _start_gallery_for_item_results(services) -> None:
+ """Provide the URL service dependency required when gallery rows become item DTOs."""
+ urls = SimpleNamespace(
+ get_image_url=lambda name, thumbnail=False: f"/images/{name}{'?thumbnail=1' if thumbnail else ''}",
+ get_video_url=lambda name, thumbnail=False: f"/videos/{name}{'?thumbnail=1' if thumbnail else ''}",
+ )
+ services["gallery"].start(SimpleNamespace(services=SimpleNamespace(urls=urls)))
+
+
+def _seed_created_range(services) -> None:
+ """Seed inclusive-day boundaries, excluded neighbours, and another user's matching media."""
+ for name in ("before.png", "range-start.png", "range-end.png", "after.png"):
+ _save_image(services["images"], name, user_id="alice")
+ for name in ("before.mp4", "range-video.mp4", "range-video-end.mp4", "bob-range.mp4"):
+ _save_video(services["videos"], name, user_id="bob" if name == "bob-range.mp4" else "alice")
+
+ for table, name_col, name, created_at in [
+ ("images", "image_name", "before.png", "2026-03-09 23:59:59.999"),
+ ("images", "image_name", "range-start.png", "2026-03-10 00:00:00.000"),
+ ("images", "image_name", "range-end.png", "2026-03-11 23:59:59.999"),
+ ("images", "image_name", "after.png", "2026-03-12 00:00:00.000"),
+ ("videos", "video_name", "before.mp4", "2026-03-09 23:59:59.999"),
+ ("videos", "video_name", "range-video.mp4", "2026-03-10 15:00:00.000"),
+ ("videos", "video_name", "range-video-end.mp4", "2026-03-11 09:00:00.000"),
+ ("videos", "video_name", "bob-range.mp4", "2026-03-11 12:00:00.000"),
+ ]:
+ _backdate(services, table, name_col, name, created_at)
+
+
class TestGetDatesPolymorphic:
def test_video_only_date_appears(self, services) -> None:
# A date with videos and no images must still produce a virtual board — with the
@@ -215,6 +246,61 @@ class TestListItemNamesByCreatedDate:
assert [(item.kind, item.name) for item in result.items] == [(GalleryItemKind.VIDEO, "alice-day.mp4")]
+class TestCreatedRangeFiltering:
+ def test_list_items_includes_utc_day_bounds_and_reports_total(self, services) -> None:
+ _seed_created_range(services)
+ _start_gallery_for_item_results(services)
+
+ result = services["gallery"].list_items(
+ limit=10,
+ user_id="alice",
+ is_admin=False,
+ created_from="2026-03-10",
+ created_to="2026-03-11",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.IMAGE, "range-end.png"),
+ (GalleryItemKind.VIDEO, "range-video-end.mp4"),
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total == 4
+
+ def test_list_item_names_created_range_matches_item_order_and_counts(self, services) -> None:
+ _seed_created_range(services)
+
+ result = services["gallery"].list_item_names(
+ user_id="alice",
+ is_admin=False,
+ created_from="2026-03-10",
+ created_to="2026-03-11",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.IMAGE, "range-end.png"),
+ (GalleryItemKind.VIDEO, "range-video-end.mp4"),
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total_count == 4
+
+ def test_created_date_remains_an_exact_day_filter_without_ranges(self, services) -> None:
+ _seed_created_range(services)
+
+ result = services["gallery"].list_item_names(
+ user_id="alice",
+ is_admin=False,
+ created_date="2026-03-10",
+ )
+
+ assert [(item.kind, item.name) for item in result.items] == [
+ (GalleryItemKind.VIDEO, "range-video.mp4"),
+ (GalleryItemKind.IMAGE, "range-start.png"),
+ ]
+ assert result.total_count == 2
+
+
class TestGetBoardMediaSummaries:
def test_returns_counts_and_deterministic_covers_in_one_result(self, services) -> None:
populated = services["boards"].save("Populated", "alice")