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(api): add created_from/created_to date range filters to image listing

joshistoast47a0e3d5d417
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 8d282ac0bb..679d2158e0 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -1,6 +1,7 @@
import io
import json
import traceback
+from datetime import date
from typing import ClassVar, Optional
from fastapi import BackgroundTasks, Body, HTTPException, Path, Query, Request, Response, UploadFile
@@ -453,6 +454,12 @@ async def list_image_dtos(
order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),
starred_first: bool = Query(default=True, description="Whether to sort by starred images 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[ImageDTO]:
"""Gets a list of image DTOs for the current user"""
@@ -462,17 +469,19 @@ async def list_image_dtos(
_assert_board_read_access(board_id, current_user)
image_dtos = ApiDependencies.invoker.services.images.get_many(
- offset,
- limit,
- starred_first,
- order_dir,
- image_origin,
- categories,
- is_intermediate,
- board_id,
- search_term,
- current_user.user_id,
- current_user.is_admin,
+ offset=offset,
+ limit=limit,
+ starred_first=starred_first,
+ order_dir=order_dir,
+ image_origin=image_origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ created_from=created_from.isoformat() if created_from else None,
+ created_to=created_to.isoformat() if created_to else None,
+ user_id=current_user.user_id,
+ is_admin=current_user.is_admin,
)
return image_dtos
@@ -733,6 +742,12 @@ async def get_image_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 images 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."
+ ),
) -> ImageNamesResult:
"""Gets ordered list of image names with metadata for optimistic updates"""
@@ -749,6 +764,8 @@ async def get_image_names(
is_intermediate=is_intermediate,
board_id=board_id,
search_term=search_term,
+ created_from=created_from.isoformat() if created_from else None,
+ created_to=created_to.isoformat() if created_to else None,
user_id=current_user.user_id,
is_admin=current_user.is_admin,
)
diff --git a/invokeai/app/services/image_records/image_records_base.py b/invokeai/app/services/image_records/image_records_base.py
index 9e263522cd..820d988751 100644
--- a/invokeai/app/services/image_records/image_records_base.py
+++ b/invokeai/app/services/image_records/image_records_base.py
@@ -56,10 +56,15 @@ class ImageRecordStorageBase(ABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> OffsetPaginatedResults[ImageRecord]:
- """Gets a page of image records. When board_id is 'none', filters by user_id for per-user uncategorized images unless is_admin is True."""
+ """Gets a page of image records. When board_id is 'none', filters by user_id for per-user uncategorized images unless is_admin is True.
+
+ created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
+ """
pass
# TODO: The database has a nullable `deleted_at` column, currently unused.
@@ -124,10 +129,15 @@ class ImageRecordStorageBase(ABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> ImageNamesResult:
- """Gets ordered list of image names with metadata for optimistic updates."""
+ """Gets ordered list of image names with metadata for optimistic updates.
+
+ created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
+ """
pass
@abstractmethod
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index f7931870fa..1c901b2a4a 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -161,6 +161,8 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> OffsetPaginatedResults[ImageRecord]:
@@ -246,6 +248,21 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
query_params.append(f"%{search_term.lower()}%")
query_params.append(f"%{search_term.lower()}%")
+ # created_at is ISO text; date-only lexicographic bounds are safe for
+ # both space- and T-separated stored values. created_to is inclusive,
+ # hence the exclusive < next-day bound.
+ if created_from:
+ query_conditions += """--sql
+ AND images.created_at >= ?
+ """
+ query_params.append(created_from)
+
+ if created_to:
+ query_conditions += """--sql
+ AND images.created_at < DATE(?, '+1 day')
+ """
+ query_params.append(created_to)
+
if starred_first:
query_pagination = f"""--sql
ORDER BY images.starred DESC, images.created_at {order_dir.value} LIMIT ? OFFSET ?
@@ -439,6 +456,8 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> ImageNamesResult:
@@ -502,6 +521,21 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
query_params.append(f"%{search_term.lower()}%")
query_params.append(f"%{search_term.lower()}%")
+ # created_at is ISO text; date-only lexicographic bounds are safe for
+ # both space- and T-separated stored values. created_to is inclusive,
+ # hence the exclusive < next-day bound.
+ if created_from:
+ query_conditions += """--sql
+ AND images.created_at >= ?
+ """
+ query_params.append(created_from)
+
+ if created_to:
+ query_conditions += """--sql
+ AND images.created_at < DATE(?, '+1 day')
+ """
+ query_params.append(created_to)
+
# Get starred count if starred_first is enabled
starred_count = 0
if starred_first:
diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.py
index aebbead2f3..cce1590932 100644
--- a/invokeai/app/services/images/images_base.py
+++ b/invokeai/app/services/images/images_base.py
@@ -126,10 +126,15 @@ class ImageServiceABC(ABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> OffsetPaginatedResults[ImageDTO]:
- """Gets a paginated list of image DTOs with starred images first when starred_first=True."""
+ """Gets a paginated list of image DTOs with starred images first when starred_first=True.
+
+ created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
+ """
pass
@abstractmethod
@@ -162,8 +167,13 @@ class ImageServiceABC(ABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> ImageNamesResult:
- """Gets ordered list of image names with metadata for optimistic updates."""
+ """Gets ordered list of image names with metadata for optimistic updates.
+
+ created_from/created_to are inclusive YYYY-MM-DD bounds on created_at (UTC days).
+ """
pass
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.py
index dabc65fb9f..07b0cfeaa3 100644
--- a/invokeai/app/services/images/images_default.py
+++ b/invokeai/app/services/images/images_default.py
@@ -249,22 +249,26 @@ class ImageService(ImageServiceABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> OffsetPaginatedResults[ImageDTO]:
try:
results = self.__invoker.services.image_records.get_many(
- offset,
- limit,
- starred_first,
- order_dir,
- image_origin,
- categories,
- is_intermediate,
- board_id,
- search_term,
- user_id,
- is_admin,
+ offset=offset,
+ limit=limit,
+ starred_first=starred_first,
+ order_dir=order_dir,
+ image_origin=image_origin,
+ categories=categories,
+ is_intermediate=is_intermediate,
+ board_id=board_id,
+ search_term=search_term,
+ created_from=created_from,
+ created_to=created_to,
+ user_id=user_id,
+ is_admin=is_admin,
)
image_dtos = [
@@ -363,6 +367,8 @@ class ImageService(ImageServiceABC):
is_intermediate: Optional[bool] = None,
board_id: Optional[str] = None,
search_term: Optional[str] = None,
+ created_from: Optional[str] = None,
+ created_to: Optional[str] = None,
user_id: Optional[str] = None,
is_admin: bool = False,
) -> ImageNamesResult:
@@ -375,6 +381,8 @@ class ImageService(ImageServiceABC):
is_intermediate=is_intermediate,
board_id=board_id,
search_term=search_term,
+ created_from=created_from,
+ created_to=created_to,
user_id=user_id,
is_admin=is_admin,
)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 488724a4d3..1bc4bdeb72 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -4623,6 +4623,44 @@
"title": "Search Term"
},
"description": "The term to search for"
+ },
+ {
+ "name": "created_from",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at.",
+ "title": "Created From"
+ },
+ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ },
+ {
+ "name": "created_to",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at.",
+ "title": "Created To"
+ },
+ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at."
}
],
"responses": {
@@ -5499,6 +5537,44 @@
"title": "Search Term"
},
"description": "The term to search for"
+ },
+ {
+ "name": "created_from",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at.",
+ "title": "Created From"
+ },
+ "description": "Inclusive start date (YYYY-MM-DD) to filter by created_at."
+ },
+ {
+ "name": "created_to",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at.",
+ "title": "Created To"
+ },
+ "description": "Inclusive end date (YYYY-MM-DD) to filter by created_at."
}
],
"responses": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 81d0eaa291..a8707177b1 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -36455,6 +36455,10 @@ export interface operations {
starred_first?: boolean;
/** @description The term to search for */
search_term?: string | null;
+ /** @description Inclusive start date (YYYY-MM-DD) to filter by created_at. */
+ created_from?: string | null;
+ /** @description Inclusive end date (YYYY-MM-DD) to filter by created_at. */
+ created_to?: string | null;
};
header?: never;
path?: never;
@@ -37076,6 +37080,10 @@ export interface operations {
starred_first?: boolean;
/** @description The term to search for */
search_term?: string | null;
+ /** @description Inclusive start date (YYYY-MM-DD) to filter by created_at. */
+ created_from?: string | null;
+ /** @description Inclusive end date (YYYY-MM-DD) to filter by created_at. */
+ created_to?: string | null;
};
header?: never;
path?: never;
diff --git a/tests/app/routers/test_images.py b/tests/app/routers/test_images.py
index f533369a92..ab0712c01f 100644
--- a/tests/app/routers/test_images.py
+++ b/tests/app/routers/test_images.py
@@ -12,7 +12,9 @@ from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api_app import app
from invokeai.app.services.auth.token_service import TokenData
from invokeai.app.services.board_records.board_records_common import BoardRecord
+from invokeai.app.services.image_records.image_records_common import ImageNamesResult
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.pagination import OffsetPaginatedResults
@pytest.fixture(autouse=True, scope="module")
@@ -207,6 +209,68 @@ def test_get_bulk_download_image_not_found(monkeypatch: Any, mock_invoker: Invok
assert response.status_code == 404
+def prepare_created_range_test(monkeypatch: Any, mock_invoker: Invoker) -> tuple[MagicMock, MagicMock]:
+ """Patches list endpoints' service calls with capturing mocks; returns (get_many, get_image_names)."""
+ mock_deps = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr("invokeai.app.api.routers.images.ApiDependencies", mock_deps)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", mock_deps)
+
+ mock_get_many = MagicMock(return_value=OffsetPaginatedResults(items=[], offset=0, limit=10, total=0))
+ mock_get_image_names = MagicMock(return_value=ImageNamesResult(image_names=[], starred_count=0, total_count=0))
+ monkeypatch.setattr(mock_invoker.services.images, "get_many", mock_get_many)
+ monkeypatch.setattr(mock_invoker.services.images, "get_image_names", mock_get_image_names)
+ return mock_get_many, mock_get_image_names
+
+
[email protected]("path", ["/api/v1/images/", "/api/v1/images/names"])
[email protected]("bad_value", ["next-tuesday", "2026-02-31"])
[email protected]("param", ["created_from", "created_to"])
+def test_list_endpoints_reject_invalid_created_range_dates(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient, path: str, bad_value: str, param: str
+) -> None:
+ """Malformed shapes and impossible calendar dates are both rejected with 422."""
+ prepare_created_range_test(monkeypatch, mock_invoker)
+
+ response = client.get(path, params={param: bad_value})
+
+ assert response.status_code == 422
+
+
+def test_list_image_dtos_forwards_created_range(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ mock_get_many, _ = prepare_created_range_test(monkeypatch, mock_invoker)
+
+ response = client.get("/api/v1/images/", params={"created_from": "2026-07-01", "created_to": "2026-07-15"})
+
+ assert response.status_code == 200
+ kwargs = mock_get_many.call_args.kwargs
+ assert kwargs["created_from"] == "2026-07-01"
+ assert kwargs["created_to"] == "2026-07-15"
+
+
+def test_list_image_dtos_omits_created_range_by_default(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ mock_get_many, _ = prepare_created_range_test(monkeypatch, mock_invoker)
+
+ response = client.get("/api/v1/images/")
+
+ assert response.status_code == 200
+ kwargs = mock_get_many.call_args.kwargs
+ assert kwargs["created_from"] is None
+ assert kwargs["created_to"] is None
+
+
+def test_get_image_names_forwards_created_range(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ _, mock_get_image_names = prepare_created_range_test(monkeypatch, mock_invoker)
+
+ response = client.get("/api/v1/images/names", params={"created_from": "2026-07-01", "created_to": "2026-07-15"})
+
+ assert response.status_code == 200
+ kwargs = mock_get_image_names.call_args.kwargs
+ assert kwargs["created_from"] == "2026-07-01"
+ assert kwargs["created_to"] == "2026-07-15"
+
+
def test_get_bulk_download_image_image_deleted_after_response(
monkeypatch: Any, mock_invoker: Invoker, tmp_path: Path, client: TestClient
) -> None:
diff --git a/tests/app/services/image_records/test_image_records_sqlite.py b/tests/app/services/image_records/test_image_records_sqlite.py
index 2c3cdf86f3..397e753104 100644
--- a/tests/app/services/image_records/test_image_records_sqlite.py
+++ b/tests/app/services/image_records/test_image_records_sqlite.py
@@ -270,3 +270,110 @@ class TestOwnershipFilteringOmittedBoard:
result = image_store.get_image_names(board_id="none", user_id="user1", is_admin=False)
assert result.image_names == ["u1-uncat.png"]
+
+
+def _set_created_at(store: SqliteImageRecordStorage, name: str, created_at: str) -> None:
+ """created_at is written by a SQL column default; tests override it directly."""
+ with store._db.transaction() as cursor:
+ cursor.execute("UPDATE images SET created_at = ? WHERE image_name = ?", (created_at, name))
+
+
+class TestCreatedAtRangeFiltering:
+ """get_many()/get_image_names() filter by inclusive created_from/created_to dates.
+
+ Bounds are date-only strings compared lexicographically against the ISO text
+ column, which stores both space- and T-separated timestamps.
+ """
+
+ def _seed_dated(self, store: SqliteImageRecordStorage) -> None:
+ _save(store, "jan30.png")
+ _save(store, "jan31-morning.png")
+ _save(store, "jan31-last-second.png")
+ _save(store, "feb01-midnight.png")
+ _save(store, "feb15-t-sep.png")
+ _set_created_at(store, "jan30.png", "2026-01-30 12:00:00.000")
+ _set_created_at(store, "jan31-morning.png", "2026-01-31 08:30:00.000")
+ _set_created_at(store, "jan31-last-second.png", "2026-01-31 23:59:59.999")
+ _set_created_at(store, "feb01-midnight.png", "2026-02-01 00:00:00.000")
+ _set_created_at(store, "feb15-t-sep.png", "2026-02-15T10:00:00.000")
+
+ def test_created_from_is_inclusive(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10, created_from="2026-01-31")
+
+ assert {r.image_name for r in result.items} == {
+ "jan31-morning.png",
+ "jan31-last-second.png",
+ "feb01-midnight.png",
+ "feb15-t-sep.png",
+ }
+
+ def test_created_to_includes_end_of_day_and_excludes_next_midnight(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10, created_to="2026-01-31")
+
+ assert {r.image_name for r in result.items} == {
+ "jan30.png",
+ "jan31-morning.png",
+ "jan31-last-second.png",
+ }
+
+ def test_created_to_handles_month_rollover(self, store: SqliteImageRecordStorage) -> None:
+ """created_to on the last day of a month must not lexicographically leak into the next month."""
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-01-31")
+
+ assert {r.image_name for r in result.items} == {"jan31-morning.png", "jan31-last-second.png"}
+
+ def test_range_matches_t_separated_timestamps(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10, created_from="2026-02-15", created_to="2026-02-15")
+
+ assert {r.image_name for r in result.items} == {"feb15-t-sep.png"}
+
+ def test_range_combines_with_search_term(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01", search_term="feb01")
+
+ assert {r.image_name for r in result.items} == set()
+ # search_term matches metadata/created_at, not names; a created_at match works
+ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01", search_term="2026-02-01")
+ assert {r.image_name for r in result.items} == {"feb01-midnight.png"}
+
+ def test_range_combines_with_board_filter(
+ self,
+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],
+ ) -> None:
+ image_store, board_store, board_image_store = stores
+ self._seed_dated(image_store)
+ board = board_store.save(board_name="Dated Board", user_id="user1")
+ board_image_store.add_image_to_board(board_id=board.board_id, image_name="jan30.png")
+ board_image_store.add_image_to_board(board_id=board.board_id, image_name="feb01-midnight.png")
+
+ result = image_store.get_many(limit=10, board_id=board.board_id, created_from="2026-02-01")
+
+ assert {r.image_name for r in result.items} == {"feb01-midnight.png"}
+
+ def test_get_many_total_and_get_image_names_counts_are_consistent(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+ with store._db.transaction() as cursor:
+ cursor.execute("UPDATE images SET starred = TRUE WHERE image_name = ?", ("jan31-morning.png",))
+
+ dtos = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01")
+ names = store.get_image_names(created_from="2026-01-31", created_to="2026-02-01")
+
+ assert dtos.total == names.total_count == 3
+ assert set(names.image_names) == {r.image_name for r in dtos.items}
+ assert names.starred_count == 1
+
+ def test_no_range_returns_everything(self, store: SqliteImageRecordStorage) -> None:
+ self._seed_dated(store)
+
+ result = store.get_many(limit=10)
+
+ assert result.total == 5