From 608556f716207fd7f9a92b6779ad5a480d726c8f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 15:51:16 +0100 Subject: [PATCH 1/2] feat: let each source kind describe its Smart Mix rules Adds GET /api/smart-mix/kinds (capability smart_mix_kinds): per kind, the fields, widgets, choices, presets and a summary recipe, owned by the provider (rule_spec.py) and checked against the request models by tests. Co-Authored-By: Claude Sonnet 5.5 --- app/api/routes/smart_mix.py | 26 ++ app/core/contract.py | 1 + app/providers/immich/rule_spec.py | 202 ++++++++++++++ app/providers/tmdb/rule_spec.py | 96 +++++++ app/services/rule_catalog.py | 192 +++++++++++++ docs/API_CONTRACT.md | 6 + docs/openapi.json | 443 ++++++++++++++++++++++++++++++ tests/test_rule_catalog.py | 128 +++++++++ 8 files changed, 1094 insertions(+) create mode 100644 app/providers/immich/rule_spec.py create mode 100644 app/providers/tmdb/rule_spec.py create mode 100644 app/services/rule_catalog.py create mode 100644 tests/test_rule_catalog.py diff --git a/app/api/routes/smart_mix.py b/app/api/routes/smart_mix.py index 81780cb..8a10986 100644 --- a/app/api/routes/smart_mix.py +++ b/app/api/routes/smart_mix.py @@ -28,6 +28,7 @@ from app.providers.immich.models import ImmichDisplayRequest, MatchMode, OnThisDay from app.providers.tmdb.models import TmdbDisplayRequest from app.services.display import DisplayResult +from app.services.rule_catalog import Placeholder, RuleKindSpec, default_catalog, placeholders from app.services.scheduler import ContextView, validation_summary from app.services.smart_mix import DEFAULT_CONTEXT_WEIGHT, MixContext @@ -245,6 +246,31 @@ async def clear_context(scheduler: SchedulerDep) -> ClearedResponse: return ClearedResponse(cleared=had) +# --- Rule editor catalog --------------------------------------------------------------- +class RuleKindsResponse(BaseModel): + """What each source kind accepts, for building a rule editor.""" + + kinds: list[RuleKindSpec] = Field( + description="Descriptor of every runnable source kind that has one; a kind listed in " + "supported_kinds of GET /api/smart-mix but missing here can only be edited as raw params" + ) + placeholders: list[Placeholder] = Field( + description="{name} placeholders a rule's text may contain, expanded on every run" + ) + + +@router.get( + "/kinds", + response_model=RuleKindsResponse, + summary="Describe the rules each source kind accepts", +) +async def get_rule_kinds(scheduler: SchedulerDep) -> RuleKindsResponse: + """Fields, choices, presets and summary recipe of each source kind (providers own them).""" + runnable = set(scheduler.supported_kinds) + kinds = [spec for spec in default_catalog().all() if spec.kind in runnable] + return RuleKindsResponse(kinds=kinds, placeholders=placeholders()) + + # --- Inspection ------------------------------------------------------------------------ class MixEntryView(BaseModel): index: int diff --git a/app/core/contract.py b/app/core/contract.py index 4fdf2ea..2578a5b 100644 --- a/app/core/contract.py +++ b/app/core/contract.py @@ -39,6 +39,7 @@ "random_discovery": ("PUT", "/api/config"), "smart_mix": ("GET", "/api/smart-mix"), "smart_mix_context": ("POST", "/api/smart-mix/context"), + "smart_mix_kinds": ("GET", "/api/smart-mix/kinds"), "title_card": ("POST", "/api/display/title-card"), "upload_image": ("POST", "/api/display/upload"), } diff --git a/app/providers/immich/rule_spec.py b/app/providers/immich/rule_spec.py new file mode 100644 index 0000000..c6abca3 --- /dev/null +++ b/app/providers/immich/rule_spec.py @@ -0,0 +1,202 @@ +"""How an Immich rule is presented in the Smart Mix editor (see ``app/services/rule_catalog.py``). + +The keys are fields of ``ImmichDisplayRequest``; ``tests/test_rule_catalog.py`` keeps them in sync. +""" + +from __future__ import annotations + +from app.services.rule_catalog import ( + Condition, + FieldSpec, + Option, + Preset, + RuleKindSpec, + SummaryPart, +) + + +def _mode_is(*modes: str) -> Condition: + return Condition(field="mode", any_of=list(modes)) + + +def immich_rule_spec() -> RuleKindSpec: + """Descriptor of the ``immich`` source kind.""" + return RuleKindSpec( + kind="immich", + label="Immich photos", + description="Photos from your Immich libraries, filtered by people, album or theme.", + icon="๐Ÿ–ผ๏ธ", + service="immich", + fields=[ + FieldSpec( + key="mode", + label="Pick photos from", + widget="segmented", + default="random", + options=[ + Option(value="random", label="Anywhere", help="Any photo matching the filters"), + Option(value="favorites", label="Favorites", help="Photos you starred"), + Option(value="album", label="An album"), + Option(value="search", label="A theme", help="Describe it, e.g. a beach"), + ], + ), + FieldSpec( + key="album_name", + label="Album", + widget="album", + help="Photos are picked from this album.", + show_when=[_mode_is("album")], + required_when=[_mode_is("album")], + ), + FieldSpec( + key="clip_queries", + label="Themes", + widget="text_list", + help="Describe what you want to see; a photo matching any phrase can be picked. " + "Placeholders such as {season} follow the calendar.", + placeholder="e.g. {season} landscape", + show_when=[_mode_is("search")], + required_when=[_mode_is("search")], + max=10, + ), + FieldSpec( + key="persons", + label="People", + widget="person_list", + help="Only photos with these people. Leave empty to use the people chosen in " + "Settings > Immich.", + ), + FieldSpec( + key="match_mode", + label="Photos must show", + widget="segmented", + nullable=True, + options=[ + Option(value="any", label="Any of them"), + Option(value="all", label="All of them"), + ], + show_when=[Condition(field="persons", filled=True)], + ), + FieldSpec( + key="on_this_day", + label="On this day", + widget="on_this_day", + help="Memories: photos taken around today's date in previous years.", + show_when=[ + Condition(field="taken_after", filled=False), + Condition(field="taken_before", filled=False), + ], + ), + FieldSpec( + key="taken_after", + label="Taken after", + widget="date", + time="00:00:00", + group="advanced", + show_when=[Condition(field="on_this_day", filled=False)], + ), + FieldSpec( + key="taken_before", + label="Taken before", + widget="date", + time="23:59:59", + group="advanced", + show_when=[Condition(field="on_this_day", filled=False)], + ), + FieldSpec( + key="accounts", + label="Immich accounts", + widget="account_list", + help="Limit the selection to these accounts. Leave empty for all of them.", + group="advanced", + ), + FieldSpec( + key="always_include", + label="Always include", + widget="person_list", + help="People added to every selection. Leave empty to use Settings > Immich.", + group="advanced", + ), + FieldSpec( + key="whole_library", + label="Ignore the default filters", + widget="bool", + help="Do not apply the people, album and favorites chosen in Settings > Immich.", + group="advanced", + ), + FieldSpec( + key="fit", + label="Framing", + widget="segmented", + nullable=True, + group="advanced", + options=[ + Option(value="smart_crop", label="Smart crop", help="Fill the frame"), + Option(value="contain", label="Whole photo", help="Never cropped"), + ], + ), + ], + presets=[ + Preset( + id="favorites", + label="Favorites", + description="Photos you starred in Immich.", + icon="โญ", + params={"mode": "favorites"}, + ), + Preset( + id="on-this-day", + label="On this day", + description="Photos taken around today's date in previous years.", + icon="๐Ÿ“…", + params={"on_this_day": {}}, + weight=2.0, + ), + Preset( + id="person", + label="A person", + description="Photos of one or more people.", + icon="๐Ÿง‘", + params={"mode": "random", "persons": []}, + edit_first=True, + ), + Preset( + id="album", + label="An album", + description="Photos from one album.", + icon="๐Ÿ“š", + params={"mode": "album"}, + edit_first=True, + ), + Preset( + id="theme", + label="A theme", + description="Photos matching a description, such as a beach or snow.", + icon="๐Ÿ”Ž", + params={"mode": "search", "clip_queries": ["beach vacation"]}, + edit_first=True, + ), + Preset( + id="season", + label="Photos of the season", + description="Landscapes that follow the calendar: spring, summer, autumn, winter.", + icon="๐Ÿ‚", + params={"mode": "search", "clip_queries": ["{season} landscape"]}, + ), + Preset( + id="whole-library", + label="Whole library", + description="Any photo, ignoring the default people, album and favorites filters.", + icon="๐ŸŒ", + params={"mode": "random", "whole_library": True}, + ), + ], + summary=[ + SummaryPart(template="Favorites", when=[_mode_is("favorites")]), + SummaryPart(template="Album: {value}", field="album_name", when=[_mode_is("album")]), + SummaryPart(template="Theme: {value}", field="clip_queries", when=[_mode_is("search")]), + SummaryPart(template="People: {value}", field="persons"), + SummaryPart(template="On this day", field="on_this_day"), + SummaryPart(template="Whole library", field="whole_library"), + ], + ) diff --git a/app/providers/tmdb/rule_spec.py b/app/providers/tmdb/rule_spec.py new file mode 100644 index 0000000..e76aaca --- /dev/null +++ b/app/providers/tmdb/rule_spec.py @@ -0,0 +1,96 @@ +"""How a TMDB rule is presented in the Smart Mix editor (see ``app/services/rule_catalog.py``). + +The keys are fields of ``TmdbRequest``; ``tests/test_rule_catalog.py`` keeps them in sync. Only +the lookup is stored in a rule: the scheduler never replays the fallback picture or the +ephemeral settings of a direct push. +""" + +from __future__ import annotations + +from app.services.rule_catalog import ( + Condition, + FieldSpec, + Option, + Preset, + RuleKindSpec, + SummaryPart, +) + + +def tmdb_rule_spec() -> RuleKindSpec: + """Descriptor of the ``tmdb`` source kind.""" + return RuleKindSpec( + kind="tmdb", + label="Movie & TV posters", + description="The HD poster of a movie or series from TMDB, shown whole (never cropped).", + icon="๐ŸŽฌ", + service="tmdb", + fields=[ + FieldSpec( + key="query", + label="Title", + widget="text", + required=True, + placeholder="e.g. Blade Runner", + ), + FieldSpec( + key="media_type", + label="Look for", + widget="segmented", + default="multi", + options=[ + Option(value="multi", label="Movie or series"), + Option(value="movie", label="Movie"), + Option(value="tv", label="TV series"), + ], + ), + FieldSpec( + key="year", + label="Year", + widget="int", + help="Release year, to tell remakes apart. Optional.", + min=1870, + max=2200, + ), + FieldSpec( + key="season", + label="Season", + widget="int", + help="Prefer the poster of this season. Optional.", + min=0, + max=100, + show_when=[Condition(field="media_type", any_of=["tv", "multi", None])], + ), + FieldSpec( + key="language", + label="Poster language", + widget="text", + help="Overrides the language set in Settings > TMDB, e.g. fr-FR or en-US.", + placeholder="Default", + group="advanced", + ), + ], + presets=[ + Preset( + id="movie", + label="A movie poster", + description="The poster of one movie.", + icon="๐ŸŽž๏ธ", + params={"query": "Blade Runner", "media_type": "movie"}, + edit_first=True, + ), + Preset( + id="series", + label="A series poster", + description="The poster of a series, optionally of one season.", + icon="๐Ÿ“บ", + params={"query": "Severance", "media_type": "tv", "season": 1}, + edit_first=True, + ), + ], + summary=[ + SummaryPart(template="{value}", field="query"), + SummaryPart(template="({value})", field="year"), + SummaryPart(template="season {value}", field="season"), + ], + ) diff --git a/app/services/rule_catalog.py b/app/services/rule_catalog.py new file mode 100644 index 0000000..81c9abf --- /dev/null +++ b/app/services/rule_catalog.py @@ -0,0 +1,192 @@ +"""Describes the rules each source kind accepts, so a UI can offer a form instead of raw JSON. + +A Smart Mix entry (or a pinned rule) is ``{kind, params}``, where ``params`` is the body of the +kind's display endpoint. The request models (``ImmichDisplayRequest``, ``TmdbDisplayRequest``) +stay the single source of truth for *validation*; the descriptors here only carry what a form +needs to *present* those parameters: a label, a help text, a widget, the allowed values, the +conditions under which a field matters, ready-made presets and a one-line summary recipe. + +Each provider package owns its descriptor (``app/providers//rule_spec.py``) and +``default_catalog()`` registers them. A kind that has a runner but no descriptor still works: the +UI falls back to a raw JSON editor for it. ``tests/test_rule_catalog.py`` checks every descriptor +against its request model so the two cannot drift apart. +""" + +from __future__ import annotations + +from typing import Final, Literal + +from pydantic import BaseModel, ConfigDict, Field, JsonValue + +Widget = Literal[ + "segmented", # a few mutually exclusive choices (``options``) + "text", # one line of text + "text_list", # several phrases, entered as chips + "int", # a whole number (``min`` / ``max``) + "bool", # a switch + "date", # a calendar day, stored as an ISO 8601 UTC timestamp (see ``FieldSpec.time``) + "person_list", # people picked from the Immich libraries + "album", # one album picked from the Immich libraries (stored by name) + "account_list", # Immich account names + "on_this_day", # the ``OnThisDay`` object (window / years back), switchable off +] + +Group = Literal["basic", "advanced"] + +#: Placeholders expanded in a stored rule right before it runs (``app/core/context.py``). +PLACEHOLDERS: Final[tuple[tuple[str, str], ...]] = ( + ("season", "spring, summer, autumn or winter (follows the configured hemisphere)"), + ("month", "the month number, 01 to 12"), + ("month_name", "the month name in lowercase, e.g. march"), + ("year", "the current year"), +) + + +class Option(BaseModel): + """One choice of a ``segmented`` field.""" + + value: str + label: str + help: str | None = None + + +class Condition(BaseModel): + """A test on one field of the rule being edited. + + ``any_of`` holds when the field equals one of the values (an unset field equals ``null``); + ``filled`` holds when the field is set (``true``) or not (``false``): ``null``, ``""``, + ``false`` and an empty list count as not set, while an empty object counts as set. Both + given means both must hold. + """ + + model_config = ConfigDict(extra="forbid") + + field: str + any_of: list[JsonValue] | None = None + filled: bool | None = None + + +class FieldSpec(BaseModel): + """One parameter of a rule, as a form presents it.""" + + model_config = ConfigDict(extra="forbid") + + key: str = Field(description="Key in the rule's params (a field of the request model)") + label: str + widget: Widget + help: str | None = None + group: Group = Field(default="basic", description="advanced fields start collapsed") + options: list[Option] = Field(default_factory=list, description="Choices of a segmented field") + nullable: bool = Field( + default=False, description="segmented only: offer a 'Default' choice that unsets the key" + ) + placeholder: str | None = None + default: JsonValue = Field(default=None, description="Value used when the key is unset") + required: bool = False + show_when: list[Condition] = Field( + default_factory=list, description="The field is shown only when all conditions hold" + ) + required_when: list[Condition] = Field( + default_factory=list, description="The field is required when all conditions hold" + ) + min: int | None = None + max: int | None = None + time: str | None = Field( + default=None, + description="date only: UTC time of day appended to the chosen day (HH:MM:SS)", + ) + + +class SummaryPart(BaseModel): + """One piece of the one-line description of a rule, e.g. ``Album: Holidays``. + + The piece is included when ``field`` is filled (if given) and every ``when`` condition holds. + ``template`` may use ``{value}``: lists are joined with ``, ``. + """ + + model_config = ConfigDict(extra="forbid") + + template: str + field: str | None = None + when: list[Condition] = Field(default_factory=list) + + +class Preset(BaseModel): + """A ready-made rule offered when adding an entry.""" + + model_config = ConfigDict(extra="forbid") + + id: str + label: str + description: str + icon: str = Field(description="One emoji shown on the preset tile") + params: dict[str, JsonValue] + weight: float = Field(default=1.0, gt=0, le=1000, description="Suggested weight") + edit_first: bool = Field( + default=False, description="The rule needs a choice from the user: open the editor" + ) + + +class RuleKindSpec(BaseModel): + """Everything a UI needs to edit the rules of one source kind.""" + + model_config = ConfigDict(extra="forbid") + + kind: str + label: str + description: str + icon: str + service: Literal["immich", "tmdb"] | None = Field( + default=None, description="Service that must be configured for the rule to run" + ) + fields: list[FieldSpec] + presets: list[Preset] + summary: list[SummaryPart] = Field( + description="Recipe of the one-line description; the kind label is used when it is empty" + ) + + def field_keys(self) -> set[str]: + """Every params key this descriptor knows about.""" + return {spec.key for spec in self.fields} + + +class Placeholder(BaseModel): + """A ``{name}`` usable in the text of a rule.""" + + name: str + description: str + + +class RuleCatalog: + """Registry of the descriptors, keyed by source kind.""" + + def __init__(self, specs: list[RuleKindSpec] | None = None) -> None: + self._specs: dict[str, RuleKindSpec] = {} + for spec in specs or []: + self.register(spec) + + def register(self, spec: RuleKindSpec) -> None: + """Add (or replace) the descriptor of one kind.""" + self._specs[spec.kind] = spec + + def get(self, kind: str) -> RuleKindSpec | None: + """The descriptor of ``kind``, or ``None`` when it has none.""" + return self._specs.get(kind) + + def all(self) -> list[RuleKindSpec]: + """Every descriptor, ordered by kind.""" + return [self._specs[kind] for kind in sorted(self._specs)] + + +def placeholders() -> list[Placeholder]: + """The placeholders a rule's text may contain.""" + return [Placeholder(name=name, description=text) for name, text in PLACEHOLDERS] + + +def default_catalog() -> RuleCatalog: + """The descriptors of the built-in providers.""" + # Imported here: provider packages import the models of this module. + from app.providers.immich.rule_spec import immich_rule_spec + from app.providers.tmdb.rule_spec import tmdb_rule_spec + + return RuleCatalog([immich_rule_spec(), tmdb_rule_spec()]) diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 5d28f4e..8f1f6d4 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -70,6 +70,7 @@ one to a real endpoint. Within a contract version they are only ever **added**. | `random_discovery` | `PUT /api/config` (`smart_mix.discovery_share`) | Occasional whole-library surprise photo. | | `smart_mix` | `GET /api/smart-mix` | Inspect the weighted playlist. | | `smart_mix_context` | `POST /api/smart-mix/context` | Set a temporary playlist boost. | +| `smart_mix_kinds` | `GET /api/smart-mix/kinds` | Describe the fields, choices, presets and summary of each rule kind, to build a rule editor. | | `title_card` | `POST /api/display/title-card` | Show a text card. | | `upload_image` | `POST /api/display/upload` | Show an image you send. | @@ -182,6 +183,7 @@ Generated from `openapi.json` by `scripts/export_openapi.py`; do not edit by han | `GET` | `/api/smart-mix` | Show the Smart Mix playlist | | `POST` | `/api/smart-mix/context` | Boost or override the Smart Mix temporarily | | `DELETE` | `/api/smart-mix/context` | Remove the Smart Mix boost | +| `GET` | `/api/smart-mix/kinds` | Describe the rules each source kind accepts | | `GET` | `/api/status` | System status | | `GET` | `/api/tmdb/search` | Search movies and series (for the web UI picker) | | `POST` | `/api/tmdb/test` | Test a TMDB API key | @@ -226,6 +228,10 @@ changelog) and run `python scripts/export_openapi.py` (see `CLAUDE.md`). image tag (SemVer, `1.0.0-rc.2`), with `+` appended for images built outside a release tag. It is for display only; `version` (PEP 440) on `/api/status` and `/api/health` is unchanged. No `api_version` change. +- New capability `smart_mix_kinds`: `GET /api/smart-mix/kinds` returns a descriptor per runnable + source kind (`kinds`: fields, widgets, choices, presets, summary recipe) and the `placeholders` + a rule's text may use. Providers own their descriptor; a kind without one has to be edited as + raw `params`. API-key protected like the rest of `/api/smart-mix`. No `api_version` change. ### 1.1 (engine 1.0.0rc2), additive diff --git a/docs/openapi.json b/docs/openapi.json index d8fc128..80ad6fe 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -677,6 +677,46 @@ "title": "ClearedResponse", "type": "object" }, + "Condition": { + "additionalProperties": false, + "description": "A test on one field of the rule being edited.\n\n``any_of`` holds when the field equals one of the values (an unset field equals ``null``);\n``filled`` holds when the field is set (``true``) or not (``false``): ``null``, ``\"\"``,\n``false`` and an empty list count as not set, while an empty object counts as set. Both\ngiven means both must hold.", + "properties": { + "any_of": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/JsonValue" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Any Of" + }, + "field": { + "title": "Field", + "type": "string" + }, + "filled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Filled" + } + }, + "required": [ + "field" + ], + "title": "Condition", + "type": "object" + }, "ConfigErrorResponse": { "description": "Validation error payload (never echoes submitted values).", "properties": { @@ -1400,6 +1440,149 @@ "title": "EphemeralView", "type": "object" }, + "FieldSpec": { + "additionalProperties": false, + "description": "One parameter of a rule, as a form presents it.", + "properties": { + "default": { + "$ref": "#/components/schemas/JsonValue", + "description": "Value used when the key is unset" + }, + "group": { + "default": "basic", + "description": "advanced fields start collapsed", + "enum": [ + "basic", + "advanced" + ], + "title": "Group", + "type": "string" + }, + "help": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Help" + }, + "key": { + "description": "Key in the rule's params (a field of the request model)", + "title": "Key", + "type": "string" + }, + "label": { + "title": "Label", + "type": "string" + }, + "max": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max" + }, + "min": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Min" + }, + "nullable": { + "default": false, + "description": "segmented only: offer a 'Default' choice that unsets the key", + "title": "Nullable", + "type": "boolean" + }, + "options": { + "description": "Choices of a segmented field", + "items": { + "$ref": "#/components/schemas/Option" + }, + "title": "Options", + "type": "array" + }, + "placeholder": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Placeholder" + }, + "required": { + "default": false, + "title": "Required", + "type": "boolean" + }, + "required_when": { + "description": "The field is required when all conditions hold", + "items": { + "$ref": "#/components/schemas/Condition" + }, + "title": "Required When", + "type": "array" + }, + "show_when": { + "description": "The field is shown only when all conditions hold", + "items": { + "$ref": "#/components/schemas/Condition" + }, + "title": "Show When", + "type": "array" + }, + "time": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "date only: UTC time of day appended to the chosen day (HH:MM:SS)", + "title": "Time" + }, + "widget": { + "enum": [ + "segmented", + "text", + "text_list", + "int", + "bool", + "date", + "person_list", + "album", + "account_list", + "on_this_day" + ], + "title": "Widget", + "type": "string" + } + }, + "required": [ + "key", + "label", + "widget" + ], + "title": "FieldSpec", + "type": "object" + }, "FlagInput": { "additionalProperties": false, "description": "``{\"value\": true, \"ttl_minutes\": 30}``.", @@ -2401,6 +2584,36 @@ "title": "OnThisDay", "type": "object" }, + "Option": { + "description": "One choice of a ``segmented`` field.", + "properties": { + "help": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Help" + }, + "label": { + "title": "Label", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + }, + "required": [ + "value", + "label" + ], + "title": "Option", + "type": "object" + }, "PendingUpload": { "description": "Metadata of the image waiting for the frame (persisted as ``pending.json``).", "properties": { @@ -2563,6 +2776,25 @@ "title": "PersonView", "type": "object" }, + "Placeholder": { + "description": "A ``{name}`` usable in the text of a rule.", + "properties": { + "description": { + "title": "Description", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "name", + "description" + ], + "title": "Placeholder", + "type": "object" + }, "PlaygroundResult": { "description": "Body of ``POST /api/playground/render``.", "properties": { @@ -2642,6 +2874,59 @@ "title": "PlaygroundVariant", "type": "object" }, + "Preset": { + "additionalProperties": false, + "description": "A ready-made rule offered when adding an entry.", + "properties": { + "description": { + "title": "Description", + "type": "string" + }, + "edit_first": { + "default": false, + "description": "The rule needs a choice from the user: open the editor", + "title": "Edit First", + "type": "boolean" + }, + "icon": { + "description": "One emoji shown on the preset tile", + "title": "Icon", + "type": "string" + }, + "id": { + "title": "Id", + "type": "string" + }, + "label": { + "title": "Label", + "type": "string" + }, + "params": { + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "title": "Params", + "type": "object" + }, + "weight": { + "default": 1.0, + "description": "Suggested weight", + "exclusiveMinimum": 0.0, + "maximum": 1000.0, + "title": "Weight", + "type": "number" + } + }, + "required": [ + "id", + "label", + "description", + "icon", + "params" + ], + "title": "Preset", + "type": "object" + }, "QueueView": { "description": "The upload queue and the ephemeral image state.", "properties": { @@ -2915,6 +3200,104 @@ "title": "ResetRequest", "type": "object" }, + "RuleKindSpec": { + "additionalProperties": false, + "description": "Everything a UI needs to edit the rules of one source kind.", + "properties": { + "description": { + "title": "Description", + "type": "string" + }, + "fields": { + "items": { + "$ref": "#/components/schemas/FieldSpec" + }, + "title": "Fields", + "type": "array" + }, + "icon": { + "title": "Icon", + "type": "string" + }, + "kind": { + "title": "Kind", + "type": "string" + }, + "label": { + "title": "Label", + "type": "string" + }, + "presets": { + "items": { + "$ref": "#/components/schemas/Preset" + }, + "title": "Presets", + "type": "array" + }, + "service": { + "anyOf": [ + { + "enum": [ + "immich", + "tmdb" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Service that must be configured for the rule to run", + "title": "Service" + }, + "summary": { + "description": "Recipe of the one-line description; the kind label is used when it is empty", + "items": { + "$ref": "#/components/schemas/SummaryPart" + }, + "title": "Summary", + "type": "array" + } + }, + "required": [ + "kind", + "label", + "description", + "icon", + "fields", + "presets", + "summary" + ], + "title": "RuleKindSpec", + "type": "object" + }, + "RuleKindsResponse": { + "description": "What each source kind accepts, for building a rule editor.", + "properties": { + "kinds": { + "description": "Descriptor of every runnable source kind that has one; a kind listed in supported_kinds of GET /api/smart-mix but missing here can only be edited as raw params", + "items": { + "$ref": "#/components/schemas/RuleKindSpec" + }, + "title": "Kinds", + "type": "array" + }, + "placeholders": { + "description": "{name} placeholders a rule's text may contain, expanded on every run", + "items": { + "$ref": "#/components/schemas/Placeholder" + }, + "title": "Placeholders", + "type": "array" + } + }, + "required": [ + "kinds", + "placeholders" + ], + "title": "RuleKindsResponse", + "type": "object" + }, "SchedulerSnapshot": { "description": "Scheduler state exposed through ``GET /api/status`` (no network access).", "properties": { @@ -3522,6 +3905,39 @@ "title": "StatusResponse", "type": "object" }, + "SummaryPart": { + "additionalProperties": false, + "description": "One piece of the one-line description of a rule, e.g. ``Album: Holidays``.\n\nThe piece is included when ``field`` is filled (if given) and every ``when`` condition holds.\n``template`` may use ``{value}``: lists are joined with ``, ``.", + "properties": { + "field": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Field" + }, + "template": { + "title": "Template", + "type": "string" + }, + "when": { + "items": { + "$ref": "#/components/schemas/Condition" + }, + "title": "When", + "type": "array" + } + }, + "required": [ + "template" + ], + "title": "SummaryPart", + "type": "object" + }, "TextInput": { "additionalProperties": false, "description": "``{\"value\": \"rainy\", \"ttl_minutes\": 30}``.", @@ -5858,6 +6274,33 @@ ] } }, + "/api/smart-mix/kinds": { + "get": { + "description": "Fields, choices, presets and summary recipe of each source kind (providers own them).", + "operationId": "get_rule_kinds_api_smart_mix_kinds_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RuleKindsResponse" + } + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Describe the rules each source kind accepts", + "tags": [ + "smart-mix" + ] + } + }, "/api/status": { "get": { "description": "Overall system status, queue state and current image (no secrets, no network).", diff --git a/tests/test_rule_catalog.py b/tests/test_rule_catalog.py new file mode 100644 index 0000000..1e37b82 --- /dev/null +++ b/tests/test_rule_catalog.py @@ -0,0 +1,128 @@ +"""Rule descriptors stay in sync with the request models and are served by the API.""" + +from __future__ import annotations + +from typing import Any + +import pytest +from pydantic import BaseModel + +from app.api.routes.smart_mix import _RULE_MODELS +from app.core.context import RuleContext, expand_params +from app.providers.immich.models import ImmichDisplayRequest +from app.providers.tmdb.models import TmdbDisplayRequest +from app.services.rule_catalog import ( + Condition, + RuleKindSpec, + default_catalog, + placeholders, +) +from tests.conftest import ClientFactory + +SPECS = default_catalog().all() +IDS = [spec.kind for spec in SPECS] + + +def conditions(spec: RuleKindSpec) -> list[Condition]: + found: list[Condition] = [] + for field in spec.fields: + found += field.show_when + field.required_when + for part in spec.summary: + found += part.when + return found + + +def model_of(spec: RuleKindSpec) -> type[BaseModel]: + return _RULE_MODELS[spec.kind] + + +def test_catalog_covers_the_built_in_kinds() -> None: + assert IDS == ["immich", "tmdb"] + assert _RULE_MODELS["immich"] is ImmichDisplayRequest + assert _RULE_MODELS["tmdb"] is TmdbDisplayRequest + + +@pytest.mark.parametrize("spec", SPECS, ids=IDS) +def test_every_field_is_a_field_of_the_request_model(spec: RuleKindSpec) -> None: + model_fields = set(model_of(spec).model_fields) + assert spec.field_keys() <= model_fields + assert len(spec.field_keys()) == len(spec.fields), "duplicate field key" + + +@pytest.mark.parametrize("spec", SPECS, ids=IDS) +def test_conditions_and_summary_reference_known_fields(spec: RuleKindSpec) -> None: + keys = spec.field_keys() + assert {condition.field for condition in conditions(spec)} <= keys + assert {part.field for part in spec.summary if part.field} <= keys + + +@pytest.mark.parametrize("spec", SPECS, ids=IDS) +def test_stored_rules_never_carry_non_replayed_fields(spec: RuleKindSpec) -> None: + from app.services.scheduler import NON_REPLAYED_FIELDS + + assert not spec.field_keys() & set(NON_REPLAYED_FIELDS) + + +@pytest.mark.parametrize("spec", SPECS, ids=IDS) +def test_presets_are_valid_rules(spec: RuleKindSpec) -> None: + assert spec.presets + for preset in spec.presets: + assert set(preset.params) <= spec.field_keys(), preset.id + model_of(spec).model_validate(_expand(preset.params)) + assert len({preset.id for preset in spec.presets}) == len(spec.presets) + + +def _expand(params: dict[str, Any]) -> dict[str, Any]: + from datetime import UTC, datetime + from zoneinfo import ZoneInfo + + context = RuleContext(now=datetime(2026, 3, 14, tzinfo=UTC), tz=ZoneInfo("UTC")) + expanded = expand_params(params, context) + assert isinstance(expanded, dict) + return expanded + + +@pytest.mark.parametrize("spec", SPECS, ids=IDS) +def test_segmented_fields_offer_valid_choices(spec: RuleKindSpec) -> None: + for field in spec.fields: + if field.widget == "segmented": + assert len(field.options) >= 2, field.key + allowed = {option.value for option in field.options} + if field.default is not None: + assert field.default in allowed, field.key + else: + assert not field.options, field.key + + +def test_placeholders_match_the_expander() -> None: + from datetime import UTC, datetime + from zoneinfo import ZoneInfo + + context = RuleContext(now=datetime(2026, 3, 14, tzinfo=UTC), tz=ZoneInfo("UTC")) + assert {item.name for item in placeholders()} == set(context.variables) + + +# --- GET /api/smart-mix/kinds ------------------------------------------------------------ +def test_kinds_endpoint_serves_the_descriptors(make_client: ClientFactory) -> None: + response = make_client().get("/api/smart-mix/kinds") + assert response.status_code == 200, response.text + body = response.json() + assert [kind["kind"] for kind in body["kinds"]] == ["immich", "tmdb"] + immich = body["kinds"][0] + assert immich["service"] == "immich" + assert {"mode", "persons", "album_name", "clip_queries"} <= {f["key"] for f in immich["fields"]} + assert body["placeholders"][0]["name"] == "season" + + +def test_kinds_endpoint_only_lists_runnable_kinds(make_client: ClientFactory) -> None: + client = make_client() + runnable = set(client.get("/api/smart-mix").json()["supported_kinds"]) + kinds = {kind["kind"] for kind in client.get("/api/smart-mix/kinds").json()["kinds"]} + assert kinds <= runnable + + +def test_kinds_endpoint_needs_the_api_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key="secret") + assert client.get("/api/smart-mix/kinds").status_code == 401 + ok = client.get("/api/smart-mix/kinds", headers={"X-API-Key": "secret"}) + assert ok.status_code == 200 From cdd65373f25ca701b74d037bd4c2d7e343e7e38f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 16:02:01 +0100 Subject: [PATCH 2/2] feat: friendly Smart Mix editor built from provider descriptors Replaces the raw JSON params textarea with entry cards (one-line summary, share of refreshes), a preset picker and a form generated from GET /api/smart-mix/kinds: people and album pickers, theme chips, on-this-day, date range, TMDB title lookup. Raw JSON stays as an opt-in escape hatch and unknown params keys are preserved. Co-Authored-By: Claude Sonnet 5.5 --- CONTRIBUTING.md | 5 +- README.md | 2 + app/providers/immich/rule_spec.py | 1 + app/providers/tmdb/rule_spec.py | 5 +- app/services/rule_catalog.py | 6 +- app/templates/index.html | 428 +++++++++++++++++++++++++++--- docs/openapi.json | 14 +- tests/test_web_ui.py | 8 + 8 files changed, 431 insertions(+), 38 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4d8a2e0..bfc8d1f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,4 +39,7 @@ pytest Providers live in `app/providers/`. Implement the provider base class, return an `ImageAsset`, register it where the existing providers are wired in `app/main.py`, and add tests next to the -existing provider tests. Open a *Feature request* first if you want to discuss the design. +existing provider tests. To make the source usable in Smart Mix, describe the rules it accepts in +`app/providers//rule_spec.py` (see `immich_rule_spec()`) and add it to `default_catalog()` +in `app/services/rule_catalog.py`: the Smart Mix editor builds its form from that descriptor, and +`tests/test_rule_catalog.py` checks it against your request model. Open a *Feature request* first if you want to discuss the design. diff --git a/README.md b/README.md index a10d2d6..ff50b46 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ Want it to refresh by itself? Turn on the scheduler in *Settings โ†’ Frame & sch - **Smart Mix**: a weighted playlist ("60% family, 25% travel, 15% movie posters") for scheduled refreshes, plus **Random Discovery** that occasionally digs up a forgotten photo. + Entries are built from friendly presets and forms (people, albums, themes, posters...): no + JSON to write. - **Ambient context**: Home Assistant can say who is home, the weather or the season; the engine leans the playlist that way for a while, then forgets on its own. - **Battery frames**: in deep-sleep mode, new pictures wait in a queue and are delivered the diff --git a/app/providers/immich/rule_spec.py b/app/providers/immich/rule_spec.py index c6abca3..9501fb2 100644 --- a/app/providers/immich/rule_spec.py +++ b/app/providers/immich/rule_spec.py @@ -199,4 +199,5 @@ def immich_rule_spec() -> RuleKindSpec: SummaryPart(template="On this day", field="on_this_day"), SummaryPart(template="Whole library", field="whole_library"), ], + summary_fallback="Any photo", ) diff --git a/app/providers/tmdb/rule_spec.py b/app/providers/tmdb/rule_spec.py index e76aaca..69e61fa 100644 --- a/app/providers/tmdb/rule_spec.py +++ b/app/providers/tmdb/rule_spec.py @@ -90,7 +90,8 @@ def tmdb_rule_spec() -> RuleKindSpec: ], summary=[ SummaryPart(template="{value}", field="query"), - SummaryPart(template="({value})", field="year"), - SummaryPart(template="season {value}", field="season"), + SummaryPart(template="{value}", field="year"), + SummaryPart(template="Season {value}", field="season"), ], + summary_fallback="Poster (no title yet)", ) diff --git a/app/services/rule_catalog.py b/app/services/rule_catalog.py index 81c9abf..eee5f0b 100644 --- a/app/services/rule_catalog.py +++ b/app/services/rule_catalog.py @@ -142,7 +142,11 @@ class RuleKindSpec(BaseModel): fields: list[FieldSpec] presets: list[Preset] summary: list[SummaryPart] = Field( - description="Recipe of the one-line description; the kind label is used when it is empty" + description="Recipe of the one-line description of a rule, parts joined with ' ยท '" + ) + summary_fallback: str | None = Field( + default=None, + description="Description of a rule none of the summary parts applies to (default: label)", ) def field_keys(self) -> set[str]: diff --git a/app/templates/index.html b/app/templates/index.html index 55ce8eb..bc7ec08 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -726,30 +726,28 @@

Family Mode

Smart Mix

-

Scheduled refreshes pick an entry at random, in proportion to its weight. {season}, {month_name}โ€ฆ in parameters are filled in each time.

+

Each scheduled refresh picks one entry at random: the more often an entry comes up, the more you see it. Press Save to apply your changes.

+

No entries yet. Add one to start mixing your sources.

- +
@@ -831,6 +829,197 @@

API key

+ +
+ +
+ + +
+ +
+
@@ -869,6 +1058,8 @@

API key

.badge-amber { @apply bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300; } .chip { @apply rounded-full px-2 py-0.5 text-[10px] ring-1 ring-slate-300 dark:ring-slate-700 text-slate-500; } .chip-on { @apply bg-blue-600 text-white ring-blue-600; } + .pill { @apply rounded-full px-3 py-1 text-sm ring-1 ring-inset ring-slate-300 dark:ring-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800; } + .pill-on { @apply bg-blue-600 text-white ring-blue-600 hover:bg-blue-600 dark:hover:bg-blue-600; } .chip-on-green { @apply bg-emerald-600 text-white ring-emerald-600; } .env { @apply ml-1 rounded bg-slate-200 dark:bg-slate-700 px-1 text-[10px] font-normal text-slate-600 dark:text-slate-300; } } @@ -897,6 +1088,10 @@

API key

card: { title: "", subtitle: "", caption: "", accent: "red", ttl: 60 }, lab: { file: null, template: "none", fit: "", variants: [{ profile: "auto", dither: "auto" }, { profile: "official", dither: "atkinson" }], results: [], frameSize: null }, config: null, sources: {}, draft: null, accounts: [], mixRows: [], mixView: null, + // Smart Mix editor: the forms are generated from GET api/smart-mix/kinds (providers describe their own rules). + mixSpecs: {}, mixAdd: false, mixEdit: null, mixOpen: false, + mixLevels: [{ label: "Rarely", w: 0.5 }, { label: "Normal", w: 1 }, { label: "Often", w: 3 }, { label: "Very often", w: 8 }], + otdFields: [{ key: "window_days", label: "Days around", min: 0, max: 31, def: "3" }, { key: "years_back", label: "Years back", min: 1, max: 20, def: "10" }, { key: "min_years_ago", label: "Skip recent years", min: 1, max: 20, def: "1" }], frameAsked: false, ambient: null, albums: [], people: [], peopleFilter: "", tmdbTest: null, apiKey: { value: "", shown: false, source: "none", regenerable: false }, // --- Lifecycle ------------------------------------------------------------------- @@ -1143,11 +1338,17 @@

API key

var accounts = view.config.immich.accounts || {}; this.accounts = Object.keys(accounts).map(function (name) { return { name: name, url: accounts[name].url, api_key: "", test: null, isNew: false }; }); this.mixRows = (view.config.smart_mix.entries || []).map(function (e) { - return { label: e.label || "", kind: e.kind, weight: e.weight, enabled: e.enabled, paramsText: JSON.stringify(e.params || {}, null, 2), error: "" }; + return { label: e.label || "", kind: e.kind, weight: e.weight, enabled: e.enabled, params: JSON.parse(JSON.stringify(e.params || {})) }; }); }, onSection() { - if (this.section === "mix") this.loadMixView(); + if (this.section === "mix") { + this.loadMixView(); this.loadMixKinds(); + if (this.accounts.length) { + if (!this.people.length) this.loadPeople(false); + if (!this.albums.length) this.loadAlbums(); + } + } if (this.section === "security") this.loadKeyInfo(); if (this.section === "immich" && this.accounts.length && !this.people.length) this.loadPeople(false); if (this.section === "family" && this.accounts.length) { @@ -1256,10 +1457,30 @@

API key

finally { this.busy.tmdbTest = false; } }, async loadMixView() { try { this.mixView = await this.api("api/smart-mix"); } catch (e) { this.mixView = null; } }, - mixKinds() { - var kinds = (this.mixView && this.mixView.supported_kinds) || ["immich", "tmdb"]; - this.mixRows.forEach(function (r) { if (kinds.indexOf(r.kind) === -1) kinds = kinds.concat([r.kind]); }); - return kinds; + async loadMixKinds() { + try { + var r = await this.api("api/smart-mix/kinds"); var map = {}; + r.kinds.forEach(function (k) { map[k.kind] = k; }); + this.mixSpecs = map; + } catch (e) { this.mixSpecs = {}; } + }, + mixSpec(kind) { return this.mixSpecs[kind] || null; }, + mixKindList() { var self = this; return Object.keys(this.mixSpecs).sort().map(function (k) { return self.mixSpecs[k]; }); }, + mixUnknownKinds() { + var self = this; + return ((this.mixView && this.mixView.supported_kinds) || []).filter(function (k) { return !self.mixSpecs[k]; }); + }, + mixIcon(kind) { var s = this.mixSpec(kind); return s ? s.icon : "๐Ÿงฉ"; }, + mixKindLabel(kind) { var s = this.mixSpec(kind); return s ? s.label : "Custom rule ยท " + kind; }, + mixMissingService(row) { + var s = this.mixSpec(row.kind); + if (!s || !s.service || !this.status || !this.status.services || this.status.services[s.service] !== false) return ""; + return s.service === "tmdb" ? "TMDB API key not set (Settings > TMDB): this entry is skipped." : "Immich is not configured (Settings > Immich): this entry is skipped."; + }, + mixLevel(weight) { + var w = Number(weight); + var hit = this.mixLevels.find(function (l) { return l.w === w; }); + return hit ? hit.label : "Custom (" + w + ")"; }, mixChance(i) { // Live probability of unsaved weights (enabled entries only). @@ -1269,16 +1490,157 @@

API key

if (!total || !row.enabled) return row.enabled ? null : 0; return Number(row.weight) / total; }, + + // --- Smart Mix: descriptor evaluation (shared by the forms and the one-line summaries) --- + mixFilled(v) { + if (v === null || v === undefined || v === "" || v === false) return false; + if (Array.isArray(v)) return v.length > 0; + return true; + }, + mixValue(spec, params, key) { + var v = params[key]; + if (v === undefined) { + var f = spec.fields.find(function (x) { return x.key === key; }); + v = f && f.default !== undefined ? f.default : null; + } + return v; + }, + mixHolds(conds, params, spec) { + var self = this; + return (conds || []).every(function (c) { + var v = self.mixValue(spec, params, c.field); + if (c.any_of && !c.any_of.some(function (x) { return x === v; })) return false; + if (c.filled !== null && c.filled !== undefined && self.mixFilled(v) !== c.filled) return false; + return true; + }); + }, + mixSummary(row) { + var spec = this.mixSpec(row.kind); + if (!spec) return "Custom " + row.kind + " rule"; + var self = this; var parts = []; + spec.summary.forEach(function (p) { + if (!self.mixHolds(p.when, row.params, spec)) return; + var v = p.field ? self.mixValue(spec, row.params, p.field) : null; + if (p.field && !self.mixFilled(v)) return; + var text = Array.isArray(v) ? v.join(", ") : (v !== null && typeof v === "object" ? "" : String(v === null ? "" : v)); + parts.push(p.template.replace("{value}", text)); + }); + return parts.length ? parts.join(" ยท ") : (spec.summary_fallback || spec.label); + }, + + // --- Smart Mix: add / edit / duplicate --------------------------------------------------- + mixNewRow(kind, params, weight) { return { label: "", kind: kind, weight: weight || 1, enabled: true, params: JSON.parse(JSON.stringify(params || {})) }; }, + startMixEdit(row, index) { + var spec = this.mixSpec(row.kind); var self = this; var more = false; + if (spec) more = spec.fields.some(function (f) { return f.group === "advanced" && self.mixFilled(row.params[f.key]); }); + var json = spec ? "" : JSON.stringify(row.params, null, 2); + this.mixEdit = { i: index, isNew: index < 0, row: row, more: more, chip: {}, errors: [], jsonOpen: !spec, json: json, jsonBase: json }; + this.mixAdd = false; this.mixOpen = true; + }, + openMixEdit(i) { this.startMixEdit(JSON.parse(JSON.stringify(this.mixRows[i])), i); }, + addMixPreset(kind, preset) { + var row = this.mixNewRow(kind, preset.params, preset.weight); + if (preset.edit_first) { this.startMixEdit(row, -1); return; } + this.mixRows.push(row); + this.mixAdd = false; + this.toast("Entry added: press Save to apply"); + }, + addMixBlank(kind) { this.startMixEdit(this.mixNewRow(kind, {}, 1), -1); }, + duplicateMix(i) { + var copy = JSON.parse(JSON.stringify(this.mixRows[i])); + if (copy.label) copy.label = (copy.label + " (copy)").slice(0, 80); + this.mixRows.splice(i + 1, 0, copy); + }, + // mixEdit stays set after closing (only mixOpen flips) so the hidden form never evaluates against null. + mixCancel() { this.mixOpen = false; }, + mixToggleJson() { + var e = this.mixEdit; e.jsonOpen = !e.jsonOpen; + if (e.jsonOpen) { e.json = JSON.stringify(e.row.params, null, 2); e.jsonBase = e.json; } + }, + mixApplyJson() { + var e = this.mixEdit; + try { + var p = JSON.parse(e.json || "{}"); + if (typeof p !== "object" || Array.isArray(p) || p === null) throw new Error("must be a JSON object"); + e.row.params = p; e.errors = []; e.jsonBase = e.json; + return true; + } catch (err) { e.errors = ["Invalid JSON: " + err.message]; return false; } + }, + mixDone() { + var e = this.mixEdit; var self = this; + // The raw JSON wins only when it was edited; otherwise the form is the source of truth. + if (e.jsonOpen && e.json !== e.jsonBase && !this.mixApplyJson()) return; + var spec = this.mixSpec(e.row.kind); var params = e.row.params; var errors = []; + if (spec) { + spec.fields.forEach(function (f) { + if (!self.mixHolds(f.show_when, params, spec)) { delete params[f.key]; return; } + if (typeof params[f.key] === "string") params[f.key] = params[f.key].trim(); + if (params[f.key] !== undefined && !self.mixFilled(params[f.key])) delete params[f.key]; + if (self.mixIsRequired(f) && !self.mixFilled(params[f.key])) errors.push(f.label + " is required"); + }); + } + if (errors.length) { e.errors = errors; return; } + e.row.label = (e.row.label || "").trim(); + e.row.weight = Number(e.row.weight) > 0 ? Number(e.row.weight) : 1; + if (e.isNew) this.mixRows.push(e.row); else this.mixRows.splice(e.i, 1, e.row); + this.toast("Entry " + (e.isNew ? "added" : "updated") + ": press Save to apply"); + this.mixOpen = false; + }, + + // --- Smart Mix: form fields (all operate on the params of the entry being edited) ---------- + mixFields() { + var e = this.mixEdit; var spec = e && this.mixSpec(e.row.kind); var self = this; + if (!spec) return []; + return spec.fields.filter(function (f) { return self.mixHolds(f.show_when, e.row.params, spec); }); + }, + mixAdvancedCount() { return this.mixFields().filter(function (f) { return f.group === "advanced"; }).length; }, + mixIsRequired(f) { + var e = this.mixEdit; var spec = this.mixSpec(e.row.kind); + return !!f.required || (f.required_when.length > 0 && this.mixHolds(f.required_when, e.row.params, spec)); + }, + mixGet(key) { + var e = this.mixEdit; var spec = this.mixSpec(e.row.kind); + if (spec) return this.mixValue(spec, e.row.params, key); + var v = e.row.params[key]; return v === undefined ? null : v; + }, + mixSet(key, value) { + var params = this.mixEdit.row.params; + if (value === null || value === undefined || value === "" || (Array.isArray(value) && !value.length)) delete params[key]; + else params[key] = value; + }, + mixSetInt(key, raw) { this.mixSet(key, raw === "" || isNaN(Number(raw)) ? null : Number(raw)); }, + mixDate(key) { var v = this.mixGet(key); return v ? String(v).slice(0, 10) : ""; }, + mixSetDate(f, day) { this.mixSet(f.key, day ? day + "T" + (f.time || "00:00:00") + "Z" : null); }, + mixList(key) { var v = this.mixEdit.row.params[key]; return Array.isArray(v) ? v : []; }, + mixHas(key, name) { + var n = String(name).toLowerCase(); + return this.mixList(key).some(function (x) { return String(x).toLowerCase() === n; }); + }, + mixToggle(key, name) { + var list = this.mixList(key).slice(); var n = String(name).toLowerCase(); + var i = list.findIndex(function (x) { return String(x).toLowerCase() === n; }); + if (i === -1) list.push(name); else list.splice(i, 1); + this.mixSet(key, list); + }, + mixListAdd(f) { + var e = this.mixEdit; var text = (e.chip[f.key] || "").trim(); + if (!text) return; + if (f.max && this.mixList(f.key).length >= f.max && !this.mixHas(f.key, text)) { e.errors = ["At most " + f.max + " values for " + f.label]; return; } + e.errors = []; + if (!this.mixHas(f.key, text)) this.mixToggle(f.key, text); + e.chip[f.key] = ""; + }, + mixListRemove(key, i) { var list = this.mixList(key).slice(); list.splice(i, 1); this.mixSet(key, list); }, + mixOtd() { var v = this.mixEdit.row.params.on_this_day; return v && typeof v === "object" ? v : null; }, + mixSetOtd(field, key, raw) { + var cur = Object.assign({}, this.mixOtd() || {}); + if (raw === "" || isNaN(Number(raw))) delete cur[key]; else cur[key] = Number(raw); + this.mixEdit.row.params[field] = cur; + }, async saveMix() { - var entries = []; var failed = false; - this.mixRows.forEach(function (r) { - r.error = ""; - var params; - try { params = JSON.parse(r.paramsText || "{}"); if (typeof params !== "object" || Array.isArray(params) || params === null) throw new Error("must be a JSON object"); } - catch (e) { r.error = "Invalid JSON: " + e.message; failed = true; return; } - entries.push({ kind: r.kind, params: params, weight: Number(r.weight) || 1, label: r.label.trim() || null, enabled: r.enabled }); + var entries = this.mixRows.map(function (r) { + return { kind: r.kind, params: r.params, weight: Number(r.weight) || 1, label: (r.label || "").trim() || null, enabled: r.enabled }; }); - if (failed) { this.toast("Fix the entry parameters first", true); return; } var patch = this.changes(["smart_mix"], ["entries"]); patch.smart_mix = Object.assign(patch.smart_mix || {}, { entries: entries }); if (await this.putConfig(patch)) this.loadMixView(); diff --git a/docs/openapi.json b/docs/openapi.json index 80ad6fe..b02d0af 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3251,12 +3251,24 @@ "title": "Service" }, "summary": { - "description": "Recipe of the one-line description; the kind label is used when it is empty", + "description": "Recipe of the one-line description of a rule, parts joined with ' ยท '", "items": { "$ref": "#/components/schemas/SummaryPart" }, "title": "Summary", "type": "array" + }, + "summary_fallback": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Description of a rule none of the summary parts applies to (default: label)", + "title": "Summary Fallback" } }, "required": [ diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py index c846e04..fe342e9 100644 --- a/tests/test_web_ui.py +++ b/tests/test_web_ui.py @@ -355,3 +355,11 @@ def test_immich_connection_test(make_client: ClientFactory) -> None: } invalid = client.post("/api/immich/test", json={"url": "ftp://x", "api_key": "k"}).json() assert invalid["ok"] is False + + +def test_smart_mix_editor_is_driven_by_the_kinds_endpoint() -> None: + html = page("index.html") + assert 'this.api("api/smart-mix/kinds")' in html + # The old raw-JSON textarea per entry is gone; JSON stays available as an opt-in escape hatch. + assert "paramsText" not in html + assert "Edit raw JSON" in html