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(wildcards): give wildcards real per-user storage

joshistoastc9f6cce316e9
diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.py
index 67e80ff55e..ba129e63e4 100644
--- a/invokeai/app/api/dependencies.py
+++ b/invokeai/app/api/dependencies.py
@@ -53,6 +53,7 @@ from invokeai.app.services.style_preset_images.style_preset_images_disk import S
from invokeai.app.services.style_preset_records.style_preset_records_sqlite import SqliteStylePresetRecordsStorage
from invokeai.app.services.urls.urls_default import LocalUrlService
from invokeai.app.services.users.users_default import UserService
+from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
from invokeai.app.services.workflow_thumbnails.workflow_thumbnails_disk import WorkflowThumbnailFileStorageDisk
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
@@ -187,6 +188,7 @@ class ApiDependencies:
urls = LocalUrlService()
workflow_records = SqliteWorkflowRecordsStorage(db=db)
style_preset_records = SqliteStylePresetRecordsStorage(db=db)
+ wildcard_records = SqliteWildcardRecordsStorage(db=db)
style_preset_image_files = StylePresetImageFileStorageDisk(style_presets_folder / "images")
workflow_thumbnails = WorkflowThumbnailFileStorageDisk(workflow_thumbnails_folder)
client_state_persistence = ClientStatePersistenceSqlite(db=db)
@@ -222,6 +224,7 @@ class ApiDependencies:
tensors=tensors,
conditioning=conditioning,
style_preset_records=style_preset_records,
+ wildcard_records=wildcard_records,
style_preset_image_files=style_preset_image_files,
workflow_thumbnails=workflow_thumbnails,
client_state_persistence=client_state_persistence,
diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.py
index 4541aadb62..073e6837ff 100644
--- a/invokeai/app/api/routers/utilities.py
+++ b/invokeai/app/api/routers/utilities.py
@@ -2,14 +2,12 @@ import asyncio
import logging
import threading
from pathlib import Path
-from typing import Optional, Union
+from typing import Optional
import torch
-from dynamicprompts.generators import CombinatorialPromptGenerator, RandomPromptGenerator
from fastapi import Body, HTTPException
from fastapi.routing import APIRouter
from pydantic import BaseModel, Field
-from pyparsing import ParseException
from transformers import AutoProcessor, AutoTokenizer, LlavaOnevisionForConditionalGeneration, LlavaOnevisionProcessor
from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
@@ -18,7 +16,8 @@ from invokeai.app.api.routers._access import assert_image_read_access
from invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive
from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
from invokeai.app.services.model_records.model_records_base import UnknownModelException
-from invokeai.app.util.dynamicprompts import find_missing_wildcards
+from invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_manager
+from invokeai.app.util.dynamicprompts import expand_dynamic_prompt
from invokeai.backend.llava_onevision_pipeline import LlavaOnevisionPipeline
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, TextLLMPipeline
@@ -51,32 +50,17 @@ async def parse_dynamicprompts(
combinatorial: bool = Body(default=True, description="Whether to use the combinatorial generator"),
seed: int | None = Body(None, description="The seed to use for random generation. Only used if not combinatorial"),
) -> DynamicPromptsResponse:
- """Creates a batch process"""
- max_prompts = min(max_prompts, 10000)
- generator: Union[RandomPromptGenerator, CombinatorialPromptGenerator]
- error: Optional[str] = None
-
- # An unknown wildcard used as a variant value sends the combinatorial generator into an infinite
- # loop, so bail out early with a clear message instead of hanging the request (and with it the UI
- # preview). The random generator handles unknown wildcards gracefully, so only the combinatorial
- # path is guarded.
- if combinatorial:
- missing_wildcards = find_missing_wildcards(prompt)
- if missing_wildcards:
- wildcards = ", ".join(missing_wildcards)
- return DynamicPromptsResponse(prompts=[prompt], error=f"No values found for wildcard(s): {wildcards}")
-
- try:
- if combinatorial:
- generator = CombinatorialPromptGenerator()
- prompts = generator.generate(prompt, max_prompts=max_prompts)
- else:
- generator = RandomPromptGenerator(seed=seed)
- prompts = generator.generate(prompt, num_images=max_prompts)
- except ParseException as e:
- prompts = [prompt]
- error = str(e)
- return DynamicPromptsResponse(prompts=prompts if prompts else [""], error=error)
+ """Expands a prompt's dynamic syntax against the current user's wildcards."""
+ expanded = expand_dynamic_prompt(
+ prompt,
+ max_prompts=min(max_prompts, 10000),
+ combinatorial=combinatorial,
+ seed=seed,
+ wildcard_manager=build_wildcard_manager(
+ ApiDependencies.invoker.services.wildcard_records.get_many(user_id=current_user.user_id)
+ ),
+ )
+ return DynamicPromptsResponse(prompts=expanded.prompts, error=expanded.error)
# --- Expand Prompt ---
diff --git a/invokeai/app/api/routers/wildcards.py b/invokeai/app/api/routers/wildcards.py
new file mode 100644
index 0000000000..ed08c76033
--- /dev/null
+++ b/invokeai/app/api/routers/wildcards.py
@@ -0,0 +1,90 @@
+from fastapi import Body, HTTPException, Path
+from fastapi.routing import APIRouter
+
+from invokeai.app.api.auth_dependencies import CurrentUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.wildcard_records.wildcard_records_common import (
+ WildcardChanges,
+ WildcardNameConflictError,
+ WildcardNotFoundError,
+ WildcardRecordDTO,
+ WildcardWithoutId,
+)
+
+wildcards_router = APIRouter(prefix="/v1/wildcards", tags=["wildcards"])
+
+
+def _get_owned_wildcard(wildcard_id: str, user_id: str) -> WildcardRecordDTO:
+ """Loads a wildcard, treating someone else's as absent rather than forbidden.
+
+ Answering 403 would confirm the id exists, so a non-owner gets the same 404 as a bad id.
+ """
+ try:
+ wildcard = ApiDependencies.invoker.services.wildcard_records.get(wildcard_id)
+ except WildcardNotFoundError:
+ raise HTTPException(status_code=404, detail="Wildcard not found")
+
+ if wildcard.user_id != user_id:
+ raise HTTPException(status_code=404, detail="Wildcard not found")
+
+ return wildcard
+
+
+@wildcards_router.get(
+ "/",
+ operation_id="list_wildcards",
+ responses={200: {"model": list[WildcardRecordDTO]}},
+)
+async def list_wildcards(current_user: CurrentUserOrDefault) -> list[WildcardRecordDTO]:
+ """Lists the current user's wildcards."""
+ return ApiDependencies.invoker.services.wildcard_records.get_many(user_id=current_user.user_id)
+
+
+@wildcards_router.post(
+ "/",
+ operation_id="create_wildcard",
+ responses={201: {"model": WildcardRecordDTO}},
+ status_code=201,
+)
+async def create_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard: WildcardWithoutId = Body(description="The wildcard to create"),
+) -> WildcardRecordDTO:
+ """Creates a wildcard owned by the current user."""
+ try:
+ return ApiDependencies.invoker.services.wildcard_records.create(wildcard=wildcard, user_id=current_user.user_id)
+ except WildcardNameConflictError as e:
+ raise HTTPException(status_code=409, detail=str(e))
+
+
+@wildcards_router.patch(
+ "/{wildcard_id}",
+ operation_id="update_wildcard",
+ responses={200: {"model": WildcardRecordDTO}},
+)
+async def update_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard_id: str = Path(description="The id of the wildcard to update"),
+ changes: WildcardChanges = Body(description="The changes to apply"),
+) -> WildcardRecordDTO:
+ """Updates a wildcard owned by the current user."""
+ _get_owned_wildcard(wildcard_id, current_user.user_id)
+
+ try:
+ return ApiDependencies.invoker.services.wildcard_records.update(wildcard_id=wildcard_id, changes=changes)
+ except WildcardNameConflictError as e:
+ raise HTTPException(status_code=409, detail=str(e))
+
+
+@wildcards_router.delete(
+ "/{wildcard_id}",
+ operation_id="delete_wildcard",
+ status_code=204,
+)
+async def delete_wildcard(
+ current_user: CurrentUserOrDefault,
+ wildcard_id: str = Path(description="The id of the wildcard to delete"),
+) -> None:
+ """Deletes a wildcard owned by the current user."""
+ _get_owned_wildcard(wildcard_id, current_user.user_id)
+ ApiDependencies.invoker.services.wildcard_records.delete(wildcard_id)
diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py
index 7570085442..6c26bfc405 100644
--- a/invokeai/app/api_app.py
+++ b/invokeai/app/api_app.py
@@ -34,6 +34,7 @@ from invokeai.app.api.routers import (
style_presets,
utilities,
virtual_boards,
+ wildcards,
workflows,
)
from invokeai.app.api.sockets import SocketIO
@@ -232,6 +233,7 @@ app.include_router(app_info.app_router, prefix="/api")
app.include_router(session_queue.session_queue_router, prefix="/api")
app.include_router(workflows.workflows_router, prefix="/api")
app.include_router(style_presets.style_presets_router, prefix="/api")
+app.include_router(wildcards.wildcards_router, prefix="/api")
app.include_router(client_state.client_state_router, prefix="/api")
app.include_router(projects.projects_router, prefix="/api")
app.include_router(recall_parameters.recall_parameters_router, prefix="/api")
diff --git a/invokeai/app/invocations/prompt.py b/invokeai/app/invocations/prompt.py
index 6658b0da7d..d998200ceb 100644
--- a/invokeai/app/invocations/prompt.py
+++ b/invokeai/app/invocations/prompt.py
@@ -2,14 +2,13 @@ from os.path import exists
from typing import Optional, Union
import numpy as np
-from dynamicprompts.generators import CombinatorialPromptGenerator, RandomPromptGenerator
from pydantic import field_validator
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.fields import InputField, UIComponent
from invokeai.app.invocations.primitives import StringCollectionOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.app.util.dynamicprompts import find_missing_wildcards
+from invokeai.app.util.dynamicprompts import expand_dynamic_prompt
@invocation(
@@ -31,21 +30,18 @@ class DynamicPromptInvocation(BaseInvocation):
combinatorial: bool = InputField(default=False, description="Whether to use the combinatorial generator")
def invoke(self, context: InvocationContext) -> StringCollectionOutput:
- if self.combinatorial:
- # An unknown wildcard used as a variant value sends the combinatorial generator into an
- # infinite loop, so fail fast with a clear message instead of hanging the invocation. The
- # random generator handles unknown wildcards gracefully and needs no guard.
- missing_wildcards = find_missing_wildcards(self.prompt)
- if missing_wildcards:
- raise ValueError(f"No values found for wildcard(s): {', '.join(missing_wildcards)}")
+ expanded = expand_dynamic_prompt(
+ self.prompt,
+ max_prompts=self.max_prompts,
+ combinatorial=self.combinatorial,
+ wildcard_manager=context.wildcards.get_manager(),
+ )
- generator = CombinatorialPromptGenerator()
- prompts = generator.generate(self.prompt, max_prompts=self.max_prompts)
- else:
- generator = RandomPromptGenerator()
- prompts = generator.generate(self.prompt, num_images=self.max_prompts)
+ # Unlike the HTTP route, a graph cannot usefully carry on with an unexpanded prompt.
+ if expanded.error is not None:
+ raise ValueError(expanded.error)
- return StringCollectionOutput(collection=prompts)
+ return StringCollectionOutput(collection=expanded.prompts)
@invocation(
diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.py
index d46289a65e..25579fd80d 100644
--- a/invokeai/app/services/invocation_services.py
+++ b/invokeai/app/services/invocation_services.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from invokeai.app.services.object_serializer.object_serializer_base import ObjectSerializerBase
from invokeai.app.services.style_preset_images.style_preset_images_base import StylePresetImageFileStorageBase
from invokeai.app.services.style_preset_records.style_preset_records_base import StylePresetRecordsStorageBase
+from invokeai.app.services.wildcard_records.wildcard_records_base import WildcardRecordsStorageBase
if TYPE_CHECKING:
from logging import Logger
@@ -77,6 +78,7 @@ class InvocationServices:
tensors: "ObjectSerializerBase[torch.Tensor]",
conditioning: "ObjectSerializerBase[ConditioningFieldData]",
style_preset_records: "StylePresetRecordsStorageBase",
+ wildcard_records: "WildcardRecordsStorageBase",
style_preset_image_files: "StylePresetImageFileStorageBase",
workflow_thumbnails: "WorkflowThumbnailServiceBase",
client_state_persistence: "ClientStatePersistenceABC",
@@ -112,6 +114,7 @@ class InvocationServices:
self.tensors = tensors
self.conditioning = conditioning
self.style_preset_records = style_preset_records
+ self.wildcard_records = wildcard_records
self.style_preset_image_files = style_preset_image_files
self.workflow_thumbnails = workflow_thumbnails
self.client_state_persistence = client_state_persistence
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 9c142359bc..1d00ed6bdc 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -3,6 +3,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Optional, Union
+from dynamicprompts.wildcards import WildcardManager
from PIL.Image import Image
from pydantic.networks import AnyHttpUrl
from torch import Tensor
@@ -18,6 +19,7 @@ from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.model_records.model_records_base import UnknownModelException
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
+from invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_manager
from invokeai.app.util.step_callback import diffusion_step_callback
from invokeai.backend.model_manager.configs.base import Config_Base
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
@@ -721,6 +723,16 @@ class UtilInterface(InvocationContextInterface):
)
+class WildcardsInterface(InvocationContextInterface):
+ def get_manager(self) -> WildcardManager:
+ """Builds the wildcard manager that resolves `__name__` for the queue item's owner.
+
+ Wildcards are per-user records, so an invocation resolves them against whoever queued it.
+ """
+ wildcards = self._services.wildcard_records.get_many(user_id=self._data.queue_item.user_id)
+ return build_wildcard_manager(wildcards)
+
+
class InvocationContext:
"""Provides access to various services and data for the current invocation.
@@ -733,6 +745,7 @@ class InvocationContext:
config (ConfigInterface): The app config.
util (UtilInterface): Utility methods, including a method to check if an invocation was canceled and step callbacks.
boards (BoardsInterface): Methods to interact with boards.
+ wildcards (WildcardsInterface): Access to the queueing user's wildcards.
"""
def __init__(
@@ -745,6 +758,7 @@ class InvocationContext:
config: ConfigInterface,
util: UtilInterface,
boards: BoardsInterface,
+ wildcards: WildcardsInterface,
data: InvocationContextData,
services: InvocationServices,
) -> None:
@@ -764,6 +778,9 @@ class InvocationContext:
"""Utility methods, including a method to check if an invocation was canceled and step callbacks."""
self.boards = boards
"""Methods to interact with boards."""
+ self.wildcards = wildcards
+ """Access to the queueing user's wildcards."""
+ """Methods to interact with boards."""
self._data = data
"""An internal API providing access to data about the current queue item and invocation. You probably shouldn't use this. It may change without warning."""
self._services = services
@@ -793,6 +810,7 @@ def build_invocation_context(
models = ModelsInterface(services=services, data=data, util=util)
images = ImagesInterface(services=services, data=data, util=util)
boards = BoardsInterface(services=services, data=data)
+ wildcards = WildcardsInterface(services=services, data=data)
ctx = InvocationContext(
images=images,
@@ -805,6 +823,7 @@ def build_invocation_context(
conditioning=conditioning,
services=services,
boards=boards,
+ wildcards=wildcards,
)
return ctx
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py
new file mode 100644
index 0000000000..1e35681434
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py
@@ -0,0 +1,54 @@
+import sqlite3
+
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+
+
+class WildcardsMigrationCallback:
+ def __call__(self, cursor: sqlite3.Cursor) -> None:
+ self._create_wildcards_table(cursor)
+
+ def _create_wildcards_table(self, cursor: sqlite3.Cursor) -> None:
+ cursor.execute(
+ """--sql
+ CREATE TABLE IF NOT EXISTS wildcards (
+ id TEXT NOT NULL PRIMARY KEY,
+ name TEXT NOT NULL,
+ values_json TEXT NOT NULL DEFAULT '[]',
+ user_id TEXT NOT NULL,
+ created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
+ );
+ """
+ )
+ # A wildcard is referenced by name, so a user cannot own the same name twice. The index is
+ # the authority: it makes a concurrent create fail on insert rather than in a check-then-act
+ # race, and it is also the lookup path for listing a user's wildcards.
+ cursor.execute(
+ """--sql
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_wildcards_user_id_name ON wildcards(user_id, name);
+ """
+ )
+ cursor.execute(
+ """--sql
+ CREATE TRIGGER IF NOT EXISTS tg_wildcards_updated_at
+ AFTER UPDATE ON wildcards FOR EACH ROW
+ BEGIN
+ UPDATE wildcards SET updated_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')
+ WHERE id = old.id;
+ END;
+ """
+ )
+
+
+def build_migration() -> Migration:
+ """
+ Build the migration that adds per-user wildcard storage.
+
+ Wildcards expand `__name__` in a prompt. They are user-owned content, so they live here rather
+ than on disk, and a `WildcardManager` is built from these rows per request.
+ """
+ return Migration(
+ id="2026_07_27_wildcards",
+ depends_on="migration_9",
+ callback=WildcardsMigrationCallback(),
+ )
diff --git a/invokeai/app/services/wildcard_records/__init__.py b/invokeai/app/services/wildcard_records/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/invokeai/app/services/wildcard_records/wildcard_records_base.py b/invokeai/app/services/wildcard_records/wildcard_records_base.py
new file mode 100644
index 0000000000..0898a6452f
--- /dev/null
+++ b/invokeai/app/services/wildcard_records/wildcard_records_base.py
@@ -0,0 +1,42 @@
+from abc import ABC, abstractmethod
+
+from invokeai.app.services.wildcard_records.wildcard_records_common import (
+ WildcardChanges,
+ WildcardRecordDTO,
+ WildcardWithoutId,
+)
+
+
+class WildcardRecordsStorageBase(ABC):
+ """Base class for wildcard storage services."""
+
+ @abstractmethod
+ def get(self, wildcard_id: str) -> WildcardRecordDTO:
+ """Gets a wildcard by id. Authorization is the caller's responsibility."""
+ pass
+
+ @abstractmethod
+ def create(self, wildcard: WildcardWithoutId, user_id: str) -> WildcardRecordDTO:
+ """Creates a wildcard owned by user_id.
+
+ Raises WildcardNameConflictError if the user already owns that name.
+ """
+ pass
+
+ @abstractmethod
+ def update(self, wildcard_id: str, changes: WildcardChanges) -> WildcardRecordDTO:
+ """Updates a wildcard. Authorization is the caller's responsibility.
+
+ Raises WildcardNameConflictError if the rename collides with another of the owner's names.
+ """
+ pass
+
+ @abstractmethod
+ def delete(self, wildcard_id: str) -> None:
+ """Deletes a wildcard. Authorization is the caller's responsibility."""
+ pass
+
+ @abstractmethod
+ def get_many(self, user_id: str) -> list[WildcardRecordDTO]:
+ """Gets every wildcard owned by user_id, ordered by name."""
+ pass
diff --git a/invokeai/app/services/wildcard_records/wildcard_records_common.py b/invokeai/app/services/wildcard_records/wildcard_records_common.py
new file mode 100644
index 0000000000..f1530986ba
--- /dev/null
+++ b/invokeai/app/services/wildcard_records/wildcard_records_common.py
@@ -0,0 +1,103 @@
+import json
+import re
+from typing import Any
+
+from dynamicprompts.wildcards import WildcardManager
+from pydantic import BaseModel, Field, TypeAdapter, field_validator
+
+
+class WildcardNotFoundError(Exception):
+ """Raised when a wildcard is not found"""
+
+
+class WildcardNameConflictError(Exception):
+ """Raised when a user already owns a wildcard with the requested name"""
+
+
+# A wildcard name is spliced into a prompt as `__name__`, and `/` is dynamicprompts' nesting
+# separator (`__animals/dogs__`). Each segment must begin and end alphanumerically: a leading or
+# trailing underscore would run into the `__` delimiters and make the reference ambiguous
+# (`__trailing___` could be read either way). Underscores and hyphens are fine inside.
+_WILDCARD_NAME_SEGMENT = r"[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?"
+WILDCARD_NAME_RE = re.compile(rf"^{_WILDCARD_NAME_SEGMENT}(?:/{_WILDCARD_NAME_SEGMENT})*$")
+
+MAX_WILDCARD_NAME_LENGTH = 128
+
+
+def validate_wildcard_name(name: str) -> str:
+ """Normalizes and validates a wildcard name, or raises ValueError."""
+ normalized = name.strip()
+
+ if not normalized:
+ raise ValueError("Wildcard name must not be empty")
+ if len(normalized) > MAX_WILDCARD_NAME_LENGTH:
+ raise ValueError(f"Wildcard name must be at most {MAX_WILDCARD_NAME_LENGTH} characters")
+ if not WILDCARD_NAME_RE.match(normalized):
+ raise ValueError(
+ "Wildcard name may contain only letters, numbers, underscores and hyphens, must start "
+ "and end with a letter or number, and may be nested with '/' (for example 'animals/dogs')"
+ )
+
+ return normalized
+
+
+def _clean_values(values: list[str]) -> list[str]:
+ """Drops blank entries and surrounding whitespace; a wildcard of empty strings expands to nothing."""
+ return [stripped for stripped in (value.strip() for value in values) if stripped]
+
+
+class WildcardWithoutId(BaseModel):
+ name: str = Field(description="The wildcard's name, referenced in a prompt as `__name__`.")
+ values: list[str] = Field(description="The values this wildcard expands to.")
+
+ @field_validator("name")
+ @classmethod
+ def _validate_name(cls, value: str) -> str:
+ return validate_wildcard_name(value)
+
+ @field_validator("values")
+ @classmethod
+ def _validate_values(cls, value: list[str]) -> list[str]:
+ return _clean_values(value)
+
+
+class WildcardChanges(BaseModel, extra="forbid"):
+ name: str | None = Field(default=None, description="The wildcard's new name.")
+ values: list[str] | None = Field(default=None, description="The wildcard's new values.")
+
+ @field_validator("name")
+ @classmethod
+ def _validate_name(cls, value: str | None) -> str | None:
+ return None if value is None else validate_wildcard_name(value)
+
+ @field_validator("values")
+ @classmethod
+ def _validate_values(cls, value: list[str] | None) -> list[str] | None:
+ return None if value is None else _clean_values(value)
+
+
+class WildcardRecordDTO(WildcardWithoutId):
+ id: str = Field(description="The wildcard ID.")
+ user_id: str = Field(description="The user who owns this wildcard.")
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "WildcardRecordDTO":
+ data["values"] = json.loads(data.get("values") or "[]")
+ return WildcardRecordDTOValidator.validate_python(data)
+
+
+WildcardRecordDTOValidator = TypeAdapter(WildcardRecordDTO)
+
+
+def build_wildcard_manager(wildcards: list[WildcardRecordDTO]) -> WildcardManager:
+ """Builds the manager that resolves `__name__` against a user's wildcards.
+
+ `root_map` accepts in-memory value lists, so wildcards resolve without ever touching the
+ filesystem. Wildcards with no values are omitted: an empty collection would register the name as
+ "known" while expanding to nothing, which reads as a silently dropped prompt.
+
+ Constructed per request. The tree is built lazily from a handful of small lists, so there is
+ nothing here worth caching and invalidating against edits.
+ """
+ root_map = {"": [{wildcard.name: wildcard.values for wildcard in wildcards if wildcard.values}]}
+ return WildcardManager(root_map=root_map)
diff --git a/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py b/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py
new file mode 100644
index 0000000000..df578de960
--- /dev/null
+++ b/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py
@@ -0,0 +1,95 @@
+import json
+import sqlite3
+
+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
+from invokeai.app.services.wildcard_records.wildcard_records_base import WildcardRecordsStorageBase
+from invokeai.app.services.wildcard_records.wildcard_records_common import (
+ WildcardChanges,
+ WildcardNameConflictError,
+ WildcardNotFoundError,
+ WildcardRecordDTO,
+ WildcardWithoutId,
+)
+from invokeai.app.util.misc import uuid_string
+
+
+class SqliteWildcardRecordsStorage(WildcardRecordsStorageBase):
+ def __init__(self, db: SqliteDatabase) -> None:
+ super().__init__()
+ self._db = db
+
+ def get(self, wildcard_id: str) -> WildcardRecordDTO:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT id, name, values_json AS "values", user_id
+ FROM wildcards
+ WHERE id = ?;
+ """,
+ (wildcard_id,),
+ )
+ row = cursor.fetchone()
+ if row is None:
+ raise WildcardNotFoundError(f"Wildcard with id {wildcard_id} not found")
+ return WildcardRecordDTO.from_dict(dict(row))
+
+ def create(self, wildcard: WildcardWithoutId, user_id: str) -> WildcardRecordDTO:
+ wildcard_id = uuid_string()
+ try:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ INSERT INTO wildcards (id, name, values_json, user_id)
+ VALUES (?, ?, ?, ?);
+ """,
+ (wildcard_id, wildcard.name, json.dumps(wildcard.values), user_id),
+ )
+ except sqlite3.IntegrityError as e:
+ # The (user_id, name) unique index is the authority on uniqueness, so a concurrent
+ # create loses here rather than in a check-then-insert race.
+ raise WildcardNameConflictError(f"A wildcard named '{wildcard.name}' already exists") from e
+ return self.get(wildcard_id)
+
+ def update(self, wildcard_id: str, changes: WildcardChanges) -> WildcardRecordDTO:
+ try:
+ with self._db.transaction() as cursor:
+ if changes.name is not None:
+ cursor.execute(
+ """--sql
+ UPDATE wildcards SET name = ? WHERE id = ?;
+ """,
+ (changes.name, wildcard_id),
+ )
+ if changes.values is not None:
+ cursor.execute(
+ """--sql
+ UPDATE wildcards SET values_json = ? WHERE id = ?;
+ """,
+ (json.dumps(changes.values), wildcard_id),
+ )
+ except sqlite3.IntegrityError as e:
+ raise WildcardNameConflictError(f"A wildcard named '{changes.name}' already exists") from e
+ return self.get(wildcard_id)
+
+ def delete(self, wildcard_id: str) -> None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ DELETE FROM wildcards WHERE id = ?;
+ """,
+ (wildcard_id,),
+ )
+
+ def get_many(self, user_id: str) -> list[WildcardRecordDTO]:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT id, name, values_json AS "values", user_id
+ FROM wildcards
+ WHERE user_id = ?
+ ORDER BY name ASC;
+ """,
+ (user_id,),
+ )
+ rows = cursor.fetchall()
+ return [WildcardRecordDTO.from_dict(dict(row)) for row in rows]
diff --git a/invokeai/app/util/dynamicprompts.py b/invokeai/app/util/dynamicprompts.py
index 4d71f04d7c..cadf45d0bd 100644
--- a/invokeai/app/util/dynamicprompts.py
+++ b/invokeai/app/util/dynamicprompts.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Iterator
+from dataclasses import dataclass
from dynamicprompts.commands import (
Command,
@@ -9,6 +10,7 @@ from dynamicprompts.commands import (
WildcardCommand,
WrapCommand,
)
+from dynamicprompts.generators import CombinatorialPromptGenerator, RandomPromptGenerator
from dynamicprompts.parser.parse import parse
from dynamicprompts.wildcards import WildcardManager
from pyparsing import ParseException
@@ -36,7 +38,7 @@ def _iter_wildcard_names(command: Command) -> Iterator[str]:
def find_missing_wildcards(prompt: str, wildcard_manager: WildcardManager | None = None) -> list[str]:
"""Return the unique wildcard names in `prompt` that `wildcard_manager` cannot resolve.
- An unresolvable wildcard breaks the combinatorial generator in two different ways, so callers
+ An unresolvable wildcard breaks the combinatorial generator two different ways, so callers
should treat any non-empty result as a hard error rather than generating:
- *As a variant value* (e.g. `{__nope__|x}`) it loops forever: the not-found fallback
@@ -66,3 +68,50 @@ def find_missing_wildcards(prompt: str, wildcard_manager: WildcardManager | None
if name not in missing and not wildcard_manager.get_values(name):
missing.append(name)
return missing
+
+
+@dataclass(frozen=True)
+class ExpandedPrompts:
+ """The outcome of expanding one prompt.
+
+ `error` is a soft failure: `prompts` always holds something submittable (the original prompt
+ when expansion could not proceed), so an HTTP caller can surface the message while a caller that
+ must fail hard can raise on it.
+ """
+
+ prompts: list[str]
+ error: str | None = None
+
+
+def expand_dynamic_prompt(
+ prompt: str,
+ *,
+ max_prompts: int,
+ combinatorial: bool,
+ seed: int | None = None,
+ wildcard_manager: WildcardManager | None = None,
+) -> ExpandedPrompts:
+ """Expand `prompt` with adieyal/dynamicprompts, guarding the cases that misbehave.
+
+ Shared by the `/utilities/dynamicprompts` route and `DynamicPromptInvocation` so the two agree
+ on guard, generator selection and error text.
+ """
+ if combinatorial:
+ # Unresolvable wildcards either hang the combinatorial generator or silently collapse the
+ # prompt, so bail out before generating. The random generator needs no such guard.
+ missing_wildcards = find_missing_wildcards(prompt, wildcard_manager)
+ if missing_wildcards:
+ return ExpandedPrompts(
+ prompts=[prompt],
+ error=f"No values found for wildcard(s): {', '.join(missing_wildcards)}",
+ )
+
+ try:
+ if combinatorial:
+ prompts = CombinatorialPromptGenerator(wildcard_manager).generate(prompt, max_prompts=max_prompts)
+ else:
+ prompts = RandomPromptGenerator(wildcard_manager, seed=seed).generate(prompt, num_images=max_prompts)
+ except ParseException as e:
+ return ExpandedPrompts(prompts=[prompt], error=str(e))
+
+ return ExpandedPrompts(prompts=list(prompts) if prompts else [""])
diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.py
index fe3e2bba14..1658e4ba25 100644
--- a/tests/app/routers/conftest.py
+++ b/tests/app/routers/conftest.py
@@ -53,6 +53,7 @@ _PATCHED_API_DEPENDENCIES_MODULES = (
"invokeai.app.api.routers.style_presets",
"invokeai.app.api.routers.model_relationships",
"invokeai.app.api.routers.utilities",
+ "invokeai.app.api.routers.wildcards",
"invokeai.app.api.routers.virtual_boards",
"invokeai.app.api.routers.images",
"invokeai.app.api.routers.workflows",
diff --git a/tests/app/routers/test_image_moves.py b/tests/app/routers/test_image_moves.py
index 9d93b6ad24..23bc6f2c6b 100644
--- a/tests/app/routers/test_image_moves.py
+++ b/tests/app/routers/test_image_moves.py
@@ -24,6 +24,7 @@ from invokeai.app.services.invoker import Invoker
from invokeai.app.services.project_records.project_records_sqlite import ProjectRecordsSqlite
from invokeai.app.services.users.users_common import UserCreateRequest
from invokeai.app.services.users.users_default import UserService
+from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
from invokeai.backend.util.logging import InvokeAILogger
from tests.fixtures.sqlite_database import create_mock_sqlite_database
@@ -81,6 +82,7 @@ def mock_services() -> InvocationServices:
client_state_persistence=ClientStatePersistenceSqlite(db=db),
project_records=ProjectRecordsSqlite(db=db),
users=UserService(db),
+ wildcard_records=SqliteWildcardRecordsStorage(db=db),
image_moves=image_moves,
)
diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.py
index ab20a31711..52c3e6d8af 100644
--- a/tests/app/routers/test_multiuser_authorization.py
+++ b/tests/app/routers/test_multiuser_authorization.py
@@ -79,6 +79,7 @@ def mock_services() -> InvocationServices:
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
from invokeai.app.services.users.users_default import UserService
+ from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from tests.test_nodes import TestEventService
configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
@@ -117,6 +118,7 @@ def mock_services() -> InvocationServices:
client_state_persistence=ClientStatePersistenceSqlite(db=db),
project_records=ProjectRecordsSqlite(db=db),
users=UserService(db),
+ wildcard_records=SqliteWildcardRecordsStorage(db=db),
external_generation=None, # type: ignore
)
diff --git a/tests/app/routers/test_session_queue_workflow_call.py b/tests/app/routers/test_session_queue_workflow_call.py
index 2db412291a..2ee4fc5e86 100644
--- a/tests/app/routers/test_session_queue_workflow_call.py
+++ b/tests/app/routers/test_session_queue_workflow_call.py
@@ -56,6 +56,7 @@ def mock_services() -> InvocationServices:
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
from invokeai.app.services.project_records.project_records_sqlite import ProjectRecordsSqlite
from invokeai.app.services.users.users_default import UserService
+ from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from tests.test_nodes import TestEventService
configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
@@ -94,6 +95,7 @@ def mock_services() -> InvocationServices:
client_state_persistence=ClientStatePersistenceSqlite(db=db),
project_records=ProjectRecordsSqlite(db=db),
users=UserService(db),
+ wildcard_records=SqliteWildcardRecordsStorage(db=db),
external_generation=None, # type: ignore
)
diff --git a/tests/app/routers/test_wildcards.py b/tests/app/routers/test_wildcards.py
new file mode 100644
index 0000000000..0441783449
--- /dev/null
+++ b/tests/app/routers/test_wildcards.py
@@ -0,0 +1,127 @@
+"""Router-level tests for /api/v1/wildcards.
+
+Covers ownership scoping (a user may only see and mutate their own wildcards, and someone else's
+reads as absent rather than forbidden) and the end-to-end effect on prompt expansion.
+"""
+
+from typing import Any
+
+import pytest
+from fastapi import status
+from fastapi.testclient import TestClient
+
+
+def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+def _create(client: TestClient, token: str, name: str, values: list[str]):
+ return client.post("/api/v1/wildcards/", json={"name": name, "values": values}, headers=_auth(token))
+
+
+ "method,path",
+ [
+ ("get", "/api/v1/wildcards/"),
+ ("post", "/api/v1/wildcards/"),
+ ("patch", "/api/v1/wildcards/some-id"),
+ ("delete", "/api/v1/wildcards/some-id"),
+ ],
+)
+def test_routes_require_auth(enable_multiuser: Any, client: TestClient, method: str, path: str):
+ r = client.request(method.upper(), path, json={"name": "colors", "values": ["red"]})
+ assert r.status_code == status.HTTP_401_UNAUTHORIZED
+
+
+def test_create_then_list_returns_the_wildcard(client: TestClient, user1_token: str):
+ assert _create(client, user1_token, "colors", ["red", "green"]).status_code == status.HTTP_201_CREATED
+
+ listed = client.get("/api/v1/wildcards/", headers=_auth(user1_token)).json()
+ assert [(w["name"], w["values"]) for w in listed] == [("colors", ["red", "green"])]
+
+
+def test_a_user_only_sees_their_own_wildcards(client: TestClient, user1_token: str, user2_token: str):
+ _create(client, user1_token, "colors", ["red"])
+
+ assert client.get("/api/v1/wildcards/", headers=_auth(user2_token)).json() == []
+
+
+def test_another_users_wildcard_reads_as_absent_rather_than_forbidden(
+ client: TestClient, user1_token: str, user2_token: str
+):
+ # 403 would confirm the id exists, so a non-owner gets the same 404 as a bad id.
+ created = _create(client, user1_token, "colors", ["red"]).json()
+
+ assert (
+ client.patch(
+ f"/api/v1/wildcards/{created['id']}", json={"values": ["blue"]}, headers=_auth(user2_token)
+ ).status_code
+ == status.HTTP_404_NOT_FOUND
+ )
+ assert (
+ client.delete(f"/api/v1/wildcards/{created['id']}", headers=_auth(user2_token)).status_code
+ == status.HTTP_404_NOT_FOUND
+ )
+ # ...and the record is untouched.
+ assert client.get("/api/v1/wildcards/", headers=_auth(user1_token)).json()[0]["values"] == ["red"]
+
+
+def test_duplicate_name_for_the_same_user_conflicts(client: TestClient, user1_token: str):
+ _create(client, user1_token, "colors", ["red"])
+
+ assert _create(client, user1_token, "colors", ["blue"]).status_code == status.HTTP_409_CONFLICT
+
+
+def test_invalid_name_is_rejected(client: TestClient, user1_token: str):
+ assert _create(client, user1_token, "has space", ["red"]).status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
+
+
+def test_update_and_delete(client: TestClient, user1_token: str):
+ created = _create(client, user1_token, "colors", ["red"]).json()
+
+ updated = client.patch(
+ f"/api/v1/wildcards/{created['id']}", json={"values": ["red", "blue"]}, headers=_auth(user1_token)
+ )
+ assert updated.status_code == status.HTTP_200_OK
+ assert updated.json()["values"] == ["red", "blue"]
+
+ assert (
+ client.delete(f"/api/v1/wildcards/{created['id']}", headers=_auth(user1_token)).status_code
+ == status.HTTP_204_NO_CONTENT
+ )
+ assert client.get("/api/v1/wildcards/", headers=_auth(user1_token)).json() == []
+
+
+def test_dynamicprompts_expands_the_callers_wildcards(client: TestClient, user1_token: str, user2_token: str):
+ _create(client, user1_token, "colors", ["red", "green", "blue"])
+
+ owner = client.post(
+ "/api/v1/utilities/dynamicprompts",
+ json={"prompt": "a __colors__ ball"},
+ headers=_auth(user1_token),
+ ).json()
+ assert owner["error"] is None
+ assert sorted(owner["prompts"]) == ["a blue ball", "a green ball", "a red ball"]
+
+ # The same prompt is unresolvable for a user who does not own that wildcard.
+ other = client.post(
+ "/api/v1/utilities/dynamicprompts",
+ json={"prompt": "a __colors__ ball"},
+ headers=_auth(user2_token),
+ ).json()
+ assert other["error"] == "No values found for wildcard(s): colors"
+
+
+def test_dynamicprompts_resolves_a_wildcard_nested_in_a_variant(client: TestClient, user1_token: str):
+ # Unresolvable, this shape hangs the combinatorial generator. Resolvable, it just expands.
+ _create(client, user1_token, "colors", ["red", "green"])
+
+ body = client.post(
+ "/api/v1/utilities/dynamicprompts",
+ json={"prompt": "{__colors__|x}"},
+ headers=_auth(user1_token),
+ ).json()
+
+ assert body["error"] is None
+ assert sorted(body["prompts"]) == ["green", "red", "x"]
diff --git a/tests/app/routers/test_workflows_multiuser.py b/tests/app/routers/test_workflows_multiuser.py
index 0dd92388ff..5572089dea 100644
--- a/tests/app/routers/test_workflows_multiuser.py
+++ b/tests/app/routers/test_workflows_multiuser.py
@@ -70,6 +70,7 @@ def mock_services() -> InvocationServices:
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
from invokeai.app.services.users.users_default import UserService
+ from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from tests.test_nodes import TestEventService
configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
@@ -108,6 +109,7 @@ def mock_services() -> InvocationServices:
client_state_persistence=ClientStatePersistenceSqlite(db=db),
project_records=ProjectRecordsSqlite(db=db),
users=UserService(db),
+ wildcard_records=SqliteWildcardRecordsStorage(db=db),
external_generation=None, # type: ignore
)
diff --git a/tests/app/services/test_image_move_startup_safety.py b/tests/app/services/test_image_move_startup_safety.py
index a72661bf66..ef57cb0731 100644
--- a/tests/app/services/test_image_move_startup_safety.py
+++ b/tests/app/services/test_image_move_startup_safety.py
@@ -39,6 +39,7 @@ def _services(**overrides):
"client_state_persistence": object(),
"project_records": object(),
"users": object(),
+ "wildcard_records": object(),
"image_moves": None,
}
services.update(overrides)
diff --git a/tests/app/services/test_wildcard_records.py b/tests/app/services/test_wildcard_records.py
new file mode 100644
index 0000000000..d06247c2ff
--- /dev/null
+++ b/tests/app/services/test_wildcard_records.py
@@ -0,0 +1,152 @@
+import logging
+
+import pytest
+from dynamicprompts.generators import CombinatorialPromptGenerator
+
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.wildcard_records.wildcard_records_common import (
+ WildcardChanges,
+ WildcardNameConflictError,
+ WildcardNotFoundError,
+ WildcardWithoutId,
+ build_wildcard_manager,
+)
+from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
+from invokeai.app.util.dynamicprompts import expand_dynamic_prompt
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+
+def store() -> SqliteWildcardRecordsStorage:
+ db = create_mock_sqlite_database(InvokeAIAppConfig(use_memory_db=True), logging.getLogger(__name__))
+ return SqliteWildcardRecordsStorage(db=db)
+
+
+def test_create_and_list_is_scoped_to_the_owner(store: SqliteWildcardRecordsStorage) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red", "green"]), user_id="user-1")
+ store.create(WildcardWithoutId(name="animals", values=["cat"]), user_id="user-2")
+
+ assert [w.name for w in store.get_many("user-1")] == ["colors"]
+ assert [w.name for w in store.get_many("user-2")] == ["animals"]
+
+
+def test_get_many_is_ordered_by_name(store: SqliteWildcardRecordsStorage) -> None:
+ for name in ["zebra", "apple", "mango"]:
+ store.create(WildcardWithoutId(name=name, values=["x"]), user_id="user-1")
+
+ assert [w.name for w in store.get_many("user-1")] == ["apple", "mango", "zebra"]
+
+
+def test_a_name_is_unique_per_user_but_not_across_users(store: SqliteWildcardRecordsStorage) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-1")
+ store.create(WildcardWithoutId(name="colors", values=["blue"]), user_id="user-2")
+
+ with pytest.raises(WildcardNameConflictError):
+ store.create(WildcardWithoutId(name="colors", values=["green"]), user_id="user-1")
+
+
+def test_update_changes_name_and_values(store: SqliteWildcardRecordsStorage) -> None:
+ created = store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-1")
+
+ updated = store.update(created.id, WildcardChanges(name="colours", values=["red", "green"]))
+
+ assert updated.name == "colours"
+ assert updated.values == ["red", "green"]
+
+
+def test_update_to_a_taken_name_conflicts(store: SqliteWildcardRecordsStorage) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-1")
+ other = store.create(WildcardWithoutId(name="animals", values=["cat"]), user_id="user-1")
+
+ with pytest.raises(WildcardNameConflictError):
+ store.update(other.id, WildcardChanges(name="colors"))
+
+
+def test_delete_removes_the_record(store: SqliteWildcardRecordsStorage) -> None:
+ created = store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-1")
+
+ store.delete(created.id)
+
+ assert store.get_many("user-1") == []
+ with pytest.raises(WildcardNotFoundError):
+ store.get(created.id)
+
+
+ "name",
+ [
+ "",
+ " ",
+ "has space",
+ # A leading or trailing underscore runs into the `__` delimiters: `__trailing___` is
+ # ambiguous, so the reference could not be parsed back reliably.
+ "trailing_",
+ "_leading",
+ "nested/_leading",
+ "trailing/",
+ "a/../b",
+ "x" * 129,
+ ],
+)
+def test_invalid_names_are_rejected(name: str) -> None:
+ with pytest.raises(ValueError):
+ WildcardWithoutId(name=name, values=["x"])
+
+
[email protected]("name", ["colors", "animals/dogs", "a-b_c", "has__inner__underscores", "deeply/nested/name"])
+def test_valid_names_are_accepted(name: str) -> None:
+ assert WildcardWithoutId(name=name, values=["x"]).name == name
+
+
+def test_values_are_trimmed_and_blanks_dropped() -> None:
+ assert WildcardWithoutId(name="colors", values=[" red ", "", " ", "green"]).values == ["red", "green"]
+
+
+def test_build_wildcard_manager_resolves_a_users_wildcards(store: SqliteWildcardRecordsStorage) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red", "green", "blue"]), user_id="user-1")
+ manager = build_wildcard_manager(store.get_many("user-1"))
+
+ assert sorted(manager.get_all_values("colors")) == ["blue", "green", "red"]
+ assert sorted(CombinatorialPromptGenerator(manager).generate("a __colors__ ball", max_prompts=5)) == [
+ "a blue ball",
+ "a green ball",
+ "a red ball",
+ ]
+
+
+def test_build_wildcard_manager_omits_valueless_wildcards(store: SqliteWildcardRecordsStorage) -> None:
+ # A name that is "known" but expands to nothing would silently drop the prompt, so it must stay
+ # unresolvable and be reported as missing instead.
+ store.create(WildcardWithoutId(name="empty", values=[]), user_id="user-1")
+ manager = build_wildcard_manager(store.get_many("user-1"))
+
+ assert (
+ expand_dynamic_prompt("a __empty__ ball", max_prompts=4, combinatorial=True, wildcard_manager=manager).error
+ == "No values found for wildcard(s): empty"
+ )
+
+
+def test_a_resolvable_wildcard_in_a_variant_generates_instead_of_hanging(
+ store: SqliteWildcardRecordsStorage,
+) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red", "green"]), user_id="user-1")
+ manager = build_wildcard_manager(store.get_many("user-1"))
+
+ expanded = expand_dynamic_prompt("{__colors__|x}", max_prompts=5, combinatorial=True, wildcard_manager=manager)
+
+ assert expanded.error is None
+ assert sorted(expanded.prompts) == ["green", "red", "x"]
+
+
+def test_one_users_wildcards_do_not_resolve_for_another(store: SqliteWildcardRecordsStorage) -> None:
+ store.create(WildcardWithoutId(name="colors", values=["red", "green"]), user_id="user-1")
+
+ other = expand_dynamic_prompt(
+ "a __colors__ ball",
+ max_prompts=4,
+ combinatorial=True,
+ wildcard_manager=build_wildcard_manager(store.get_many("user-2")),
+ )
+
+ assert other.error == "No values found for wildcard(s): colors"
diff --git a/tests/conftest.py b/tests/conftest.py
index a65c0cd483..7022b129f2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -25,6 +25,7 @@ from invokeai.app.services.invocation_stats.invocation_stats_default import Invo
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.project_records.project_records_sqlite import ProjectRecordsSqlite
from invokeai.app.services.users.users_default import UserService
+from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
from invokeai.backend.util.logging import InvokeAILogger
from tests.backend.model_manager.model_manager_fixtures import * # noqa: F403
@@ -72,6 +73,7 @@ def mock_services() -> InvocationServices:
client_state_persistence=ClientStatePersistenceSqlite(db=db),
project_records=ProjectRecordsSqlite(db=db),
users=UserService(db),
+ wildcard_records=SqliteWildcardRecordsStorage(db=db),
)