* feat(inspector): use recorded run history when the graph alone can't name the prompt (#386) When a file's own graph leaves the prompt open, both inspect routes ask recorded run history about the file (one run reported it and it was written during that run). The save node that run reported it from anchors the walk like a file-name match, so dataset branches that share one saver prefix show their own prompt, labelled "Recorded run". Still open at one sampler whose PromptManager text was recorded at execution (a language model's output), the recorded text shows as "Execution recorded". Results the file resolves alone never change; a failed lookup judges the file alone. * fix(inspector): recorded texts follow history's saver; conflicts anchor nothing (#386) Review follow-ups: the texts PromptManager recorded are looked up at the sampler history's saver leads to, never at a sampler the unanchored walk named; a file name naming a different saver than history anchors nothing; outputs and texts are read in one transaction; "Recorded run" ranks below every workflow-inferred source; unexpected lookup errors log at error level. * fix(history): look up recorded runs by history's own spelling of the file (#386) The history route inspects a case-normalized target on Windows, while history matches file names exactly, so the occurrence's reference names the file. * refactor(inspector): share the inspector's resolve as inspection_resolution inspect_prompt_evidence now calls inspection_resolution, which returns the resolution to use, the anchored result and whether the recorded saver chose it. Ingestion can call the same helper for files the default profile cannot decide (#247). * feat(ingestion): one per-file prompt decision for the scan and the monitor utils/file_prompt.py holds decide_file_prompt, the ladder the output scan runs today plus the inspector's rule (inspection profile, then the recorded saver) before the legacy parser, with a SCAN and a MONITOR policy. Junk text (blank, numbers, LoRA tags only, model file names) is never stored. graph_prompt_text and parse_comfyui_prompt move here; the parser accepts parsed metadata (#247). * feat(ingestion): store a file's prompt in one transaction, one prompt per file database/scanned_prompts.py links a file to the prompt of one text, creating it when new, inside one BEGIN IMMEDIATE transaction: a file linked to another prompt is a conflict, a failed link leaves no prompt behind and two writers store one prompt. pair_ingestion gains file_link_rows, link_conflict and Marks/mark_created; ingest_resolved_pair takes optional marks for the components it creates. recorded_runs and named_prompt in run_attribution become public (#247). * feat(scan): decide each scanned file with the shared ladder (#247) _ingest_scanned_file calls decide_file_prompt (scan policy) and stores the result: pairs through ingest_resolved_pair and positives through store_scanned_prompt, both with the scan marks. Files the default profile leaves undecided now get the inspector's resolve, with the saver recorded history names, before the legacy parser, so each branch of a shared-prefix dataset run links its own prompt. Junk text is never stored, a file linked to another prompt is a conflict instead of a second link, and a failed link leaves no prompt behind. _BatchHistory reads the stored prompt and the recorded saver from one recorded_runs pass. _parse_comfyui_prompt calls the moved parse_comfyui_prompt. TESTING.md documents the decision. * fix(ingestion): keep the file-name saver anchor out of the ladder (#390) The #390 ruling queues a file that only its saver's file name resolves for Needs review, never linking it. inspection_resolution gains name_anchor; the ladder passes False, so such a file falls to the legacy floor in the scan (and to Needs review) and is never stored by the monitor, while the recorded saver still decides. The inspector keeps the name anchor. * feat(config): gallery.monitoring.save_foreign_runs, default on (#247) * fix(ingestion): no joined PromptManager text from the legacy floor; junk keeps its step's status The legacy parser returns prepend + text + append, so its answer is refused when a PromptManager-family node has a prepend or append part (#343). Junk found at the undecided-graph step keeps that step's unlinked status and review, so an ambiguous file is still queued for Needs review. The monitor policy's ambiguous file no longer asks for the recorded run, and the file size may be read lazily. * fix(ingestion): keep the legacy answer that is a PromptManager node's own text The joined-text refusal also refused the #170 parity files whose PromptManager prepend is a link the browser parser does not follow: its answer is then the node's literal text, which is what the node stores. Refuse only an answer that is not such a node's own text. * feat(monitor): store the certain prompt of a foreign workflow's output (#247) A foreign output (no positive PromptManager node) is decided by the shared ladder with the MONITOR policy. Certain files are stored at settle with RUN_MARKS through survive_switch; files only recorded history can decide wait in their own bounded set and are re-checked once after the run's outputs are sealed, with the sealed reference. The setting GalleryConfig.SAVE_FOREIGN_RUNS is read for every file. * fix(scan): one prompt per file for recorded-run links; writes survive a library move The recorded run's stored prompt now links in one transaction with the file's link rows, so a file linked to another prompt is a conflict instead of a second link. The scan's stores run through survive_library_switch. A single file asks history once (a one-file _BatchHistory), the scan passes in_output=False and reads the file size only for files with prompt metadata. A conflict row reads "Kept: already linked to a different prompt". TESTING.md records the rules. * feat(settings): save_foreign_runs through POST /settings, applied live (#247) GET /settings reports settings.save_foreign_runs; a save takes a strict bool, writes gallery.monitoring.save_foreign_runs and publishes it to GalleryConfig in the commit, with no restart field. The diagnostics report lists it. The legacy contract snapshot gains the added key (an addition, no legacy key moves). * feat(system): Save prompts from other workflows in Sources & scans (#247, D147) A host setting row below Watch for new outputs drafts save_foreign_runs and saves with the one Save row; the server applies it at once, so no restart is named. While monitoring is drafted off the row is disabled and says it applies while Watch for new outputs is on. The concept comparison maps the inserted row and its mutation check covers it. * test(comfyui): a workflow of ComfyUI's own nodes creates and links its prompt (#247) The real-host attribution spec gains the foreign case (CLIPTextEncode, KSampler, SaveImage): its prompt is created and linked at settle and a second run links to the same prompt. The fixture route lists the waiting foreign files. TESTING.md records the monitor's foreign path and D147. * test(vendor): the execution matrix counts the #247 real-host case * fix(monitor): read a foreign file's size only when the ladder needs it (#247) Uses PR 1's lazy file size and pins that a foreign file linked to another prompt keeps its one link on the pair and the positive store paths. * fix(ingestion): match a file's link rows under its resolved spelling too The scan stores realpath spellings and the monitor the watcher's raw path, so a file reached through a symlinked or junction output folder could get a second generated_images row. file_link_rows now queries the path and its realpath (each normalized and raw) and dedupes by row id. TESTING.md notes the reverse order is matched only when the raw spelling is the realpath. * fix(monitor): wait for the run unless history answered; monitoring off stops foreign writes (#247) Review fixes: at settle a certain answer ends the wait only when the lookup found a record or the answer is the inspector's or the recorded saver's; the legacy floor waits for the re-check. A record without a certain prompt ends the wait at once. Foreign writes need both save_foreign_runs and monitoring_enabled, read again just before the store. Dropped foreign files are logged outside the lock (evictions as evictions, due ones too), and a drained re-check never drops a newer reference. * fix(system): the foreign row can be set while the monitor still watches; its note describes it (#247, D147) Review fixes: while monitoring is saved off but a source still reads watching until restart (D128), the row stays enabled with its note; the note is the switch's aria-describedby. The browser spec restores save_foreign_runs on the shared server. TESTING.md moves D147 into order and records the monitor's review rules. * test(comfyui): each branch of a shared-prefix foreign run links to its own prompt (#247 CUJ 1) * fix(ingestion): a switched-off PromptManager node behind a pass-through stores nothing (#90) The #90 graph walk follows only prompt-like inputs, so a PromptManagerText with Save to library off reaching the encoder through another input name (easy showAnything.anything, a custom node's value) was invisible to it, and the inspector's resolve stored its text. The ladder now checks the positive every step names: a resolved or inspected positive whose path passes a node that is off, or a legacy answer that is such a node's own text, makes the file not_saved. * fix(ingestion): any switched-off node upstream of a positive stores nothing (#90) The ladder walks every input upstream of each sampler or guider positive (not negative, model, clip, latent or image inputs) for PromptManager nodes whose Save to library is off or wired from an unreadable node, so the sampler-less step, an off node with a prepend part and a PromptManagerPair behind a pass-through no longer store its text. The legacy-floor guard reads a node's resolved text. Every guard reports not_saved for a switch that is off and not_saved_wired for one it cannot read. * fix(ingestion): the switch walk skips negative inputs by #90's own rule The upstream walk treated only names containing "negative" as negative, so an off node on a neg, neg_text or text_neg input blocked an enabled positive. prompt_graph gains is_negative_input (the _NEGATIVE_KEY rule, also used by follows_input) and the walk uses it. The guards accept a node with null inputs and a side whose provenance is not an object. * fix(ingestion): the switch walk also skips any input named with "negative" #90's rule matches only whole underscore-separated words, so negative2, negativeprompt and NegativePrompt counted as positive inputs and an off node wired only to one of them blocked the file. The walk skips those too; follows_input is unchanged. * fix(monitor): a foreign not_saved decision logs its skip and never waits (#247, #90) The foreign path stored nothing for a ladder not_saved decision, but logged it as "No certain prompt" and, when only the legacy answer was a switched-off node's text, kept the file waiting for a seal that could only store nothing. Such a decision now ends the wait at settle, and both settle and the re-check log the opted-out path's own line (a wired switch says so). Tests cover an only-PromptManager node switched off (opted out, not foreign), a switched-off PromptManagerText behind a pass-through into a core CLIPTextEncode, a wired switch, a negative-only switched-off node, recorded history holding the off text, and foreign saving off. * fix(monitor): an undecided not_saved waits for its run's record (#247, #90) A not_saved from the ladder's undecided step is not final before a record exists: the recorded saver may still resolve another branch. The settle lookup now keeps such a file waiting; with the record it stores nothing and logs the opted-out line. An early not_saved (a switched-off node upstream of any sampler's positive) never reaches the lookup and stays final. Tests: the undecided case (literal and wired switch) waits, then skips; a switched-off node feeding one branch of a shared-prefix run never waits and stores nothing, not even the branch the recorded saver names. * docs(system): renumber the foreign-runs switch deviation to D158 (#247) #430 took D147 on main; the Save prompts from other workflows row is D158. * test(monitor): a switched-off node in the recorded saver's branch is never foreign (#247, #90) PR 3's repair skips a file whose recorded saver's branch reads a switched-off PromptManager node. On the monitor the same shape never reaches the foreign path: a literal switch is the opted-out path's and a wired one the node's own run's. Nothing is stored at settle or after the run, even from a recorded run holding the off text.
724 lines
29 KiB
Python
724 lines
29 KiB
Python
"""Settings API routes: GET and POST /prompt_manager/settings (#220).
|
||
|
||
A save validates the payload, commits it to config.json through the config
|
||
store and publishes it at runtime inside that commit; a save that cannot be
|
||
written changes nothing at runtime and says so. ``_config_commit_failure``
|
||
is shared with the LoRA integration's save.
|
||
|
||
GET also reports the image sources and the monitor (``sources.py``). A save
|
||
that changes the sources runs as a ``source_change`` registry hold, so it is
|
||
refused while a record-changing job (a scan) runs. ``monitoring_enabled``
|
||
takes effect at the next restart; ``save_foreign_runs`` (#247) at once, since
|
||
the monitor reads it for every file. ``POST /prompt_manager/settings/validate-source``
|
||
checks one path and writes nothing.
|
||
"""
|
||
|
||
import contextlib
|
||
import functools
|
||
import os
|
||
|
||
from aiohttp import web
|
||
|
||
from ..config_store import (
|
||
ConfigUnreadable,
|
||
RevisionConflict,
|
||
get_config_store,
|
||
)
|
||
from . import sources
|
||
from . import thumbnail_encode
|
||
from . import thumbnail_settings
|
||
from .admin import _current_image_monitor
|
||
from .job_routes import busy_response
|
||
from .jobs import THUMBNAILS_JOB_KIND, JobBusy
|
||
|
||
try:
|
||
from ...utils.validators import validate_result_timeout, validate_worker_threads
|
||
except ImportError:
|
||
from utils.validators import validate_result_timeout, validate_worker_threads
|
||
|
||
|
||
# Settings owned by POST /settings: config attribute -> its keys in config.json.
|
||
_SETTINGS_FILE_KEYS = {
|
||
"RESULT_TIMEOUT": ("web_ui", "result_timeout"),
|
||
"WEBUI_DISPLAY_MODE": ("web_ui", "webui_display_mode"),
|
||
"INFINITE_SCROLL": ("web_ui", "infinite_scroll"),
|
||
"WORKER_THREADS": ("performance", "worker_threads"),
|
||
"MONITORING_ENABLED": ("gallery", "monitoring", "enabled"),
|
||
"SAVE_FOREIGN_RUNS": ("gallery", "monitoring", "save_foreign_runs"),
|
||
"SAFETY_BACKUP": ("maintenance", "safety_backup"),
|
||
"THUMBNAIL_FORMAT": ("thumbnails", "format"),
|
||
"THUMBNAIL_QUALITY": ("thumbnails", "quality"),
|
||
"THUMBNAIL_EDGE": ("thumbnails", "edge"),
|
||
# The one tagging configuration (#328), published to AutotagConfig.
|
||
"AUTOTAG_MODEL_TYPE": ("autotag", "defaults", "model_type"),
|
||
"AUTOTAG_EXISTING": ("autotag", "defaults", "existing"),
|
||
"AUTOTAG_GENERAL_THRESHOLD": ("autotag", "defaults", "general_threshold"),
|
||
"AUTOTAG_CHARACTER_THRESHOLD": ("autotag", "defaults", "character_threshold"),
|
||
"AUTOTAG_TEMPLATE": ("autotag", "defaults", "template"),
|
||
"AUTOTAG_SUGGESTION_LIMIT": ("autotag", "defaults", "suggestion_limit"),
|
||
}
|
||
# The thumbnail settings a running Convert outdated job fixes (#317).
|
||
_THUMBNAIL_SETTINGS = ("THUMBNAIL_FORMAT", "THUMBNAIL_QUALITY", "THUMBNAIL_EDGE")
|
||
# Attributes that live on GalleryConfig; the others on PromptManagerConfig.
|
||
_GALLERY_SETTINGS = frozenset({"MONITORING_ENABLED", "SAVE_FOREIGN_RUNS"})
|
||
# Attributes that live on AutotagConfig, named without the AUTOTAG_ prefix.
|
||
_AUTOTAG_SETTINGS = frozenset(
|
||
name for name in _SETTINGS_FILE_KEYS if name.startswith("AUTOTAG_")
|
||
)
|
||
_AUTOTAG_PREFIX = "AUTOTAG_"
|
||
SOURCE_CHANGE_JOB_KIND = "source_change"
|
||
SOURCE_CHANGE_JOB_TITLE = "Source change"
|
||
|
||
|
||
def _source_identity(path):
|
||
"""The case-folded spelling two roots are the same directory by (Windows)."""
|
||
return os.path.normcase(path)
|
||
|
||
|
||
def _stat_identity(path):
|
||
"""``(st_dev, st_ino)`` of an existing directory, or None.
|
||
|
||
Catches case variants on a case-insensitive filesystem whose spelling
|
||
normcase keeps (macOS).
|
||
"""
|
||
try:
|
||
stat = os.stat(path)
|
||
except (OSError, ValueError):
|
||
return None
|
||
return (stat.st_dev, stat.st_ino) if stat.st_ino else None
|
||
|
||
|
||
# Refusals that a reconnected drive or folder can lift.
|
||
_RECONNECTABLE = frozenset({"not-found", "not-directory"})
|
||
|
||
|
||
def _root_key(root):
|
||
"""The directory a configured root names (resolved), else its spelling."""
|
||
from ..config import GalleryConfig
|
||
|
||
try:
|
||
return GalleryConfig.resolve_gallery_root(root)
|
||
except (OSError, TypeError, ValueError, AttributeError):
|
||
return root
|
||
|
||
|
||
def _request_error(message):
|
||
return {"code": "invalid-request", "error": message}
|
||
|
||
|
||
def _invalid_source(index, entry, code, reason):
|
||
"""The 400 body for the source at ``index`` that cannot be used.
|
||
|
||
Names it by its public spelling (computed as text: a refused path is
|
||
never resolved), so the page can mark that row and say why.
|
||
"""
|
||
source = sources.public_spelling(entry)
|
||
advice = (
|
||
"Remove it or reconnect it, then save."
|
||
if code in _RECONNECTABLE
|
||
else "Remove it, then save."
|
||
)
|
||
return {
|
||
"code": "invalid-source",
|
||
"source": source,
|
||
"index": index,
|
||
"reason": reason,
|
||
"error": f"{source} can't be used: {reason}. {advice}",
|
||
}
|
||
|
||
|
||
def _section(config, name):
|
||
"""``config[name]`` as a fresh dict (a non-object section starts empty)."""
|
||
value = config.get(name)
|
||
return dict(value) if isinstance(value, dict) else {}
|
||
|
||
|
||
def _settings_mutation(updates, new_roots):
|
||
"""The config commit for a settings save: only the submitted keys change.
|
||
|
||
Every other section and key (integrations and the CivitAI key, database,
|
||
unknown sections) is kept as it is on disk.
|
||
"""
|
||
|
||
def mutate(config):
|
||
for name, value in updates.items():
|
||
*sections, key = _SETTINGS_FILE_KEYS[name]
|
||
_set_nested(config, sections, key, value)
|
||
if new_roots is not None:
|
||
gallery = _section(config, "gallery")
|
||
monitoring = _section(gallery, "monitoring")
|
||
monitoring["directories"] = list(new_roots)
|
||
gallery["monitoring"] = monitoring
|
||
config["gallery"] = gallery
|
||
return config
|
||
|
||
return mutate
|
||
|
||
|
||
def _set_nested(config, sections, key, value):
|
||
"""``config[s1][s2]...[key] = value``, each section a fresh dict."""
|
||
if not sections:
|
||
config[key] = value
|
||
return
|
||
merged = _section(config, sections[0])
|
||
_set_nested(merged, sections[1:], key, value)
|
||
config[sections[0]] = merged
|
||
|
||
|
||
def _validate_autotag_settings(data):
|
||
"""The ``autotag_*`` settings as ``{AUTOTAG_ATTR: value}``.
|
||
|
||
The first bad value raises ValueError with a message that names the
|
||
setting by its label in System › Auto-tagging.
|
||
"""
|
||
from ..config import (
|
||
EXISTING_POLICIES,
|
||
MAX_SUGGESTION_LIMIT,
|
||
MODEL_TYPES,
|
||
validate_saved_threshold,
|
||
validate_template,
|
||
)
|
||
|
||
updates = {}
|
||
if "autotag_model_type" in data:
|
||
value = data["autotag_model_type"]
|
||
if not isinstance(value, str) or value not in MODEL_TYPES:
|
||
raise ValueError(
|
||
"Tagging model must be one of " + ", ".join(sorted(MODEL_TYPES)) + "."
|
||
)
|
||
updates["AUTOTAG_MODEL_TYPE"] = value
|
||
if "autotag_existing" in data:
|
||
value = data["autotag_existing"]
|
||
if not isinstance(value, str) or value not in EXISTING_POLICIES:
|
||
raise ValueError(
|
||
"Existing tags must be skip, merge or replace_after_review."
|
||
)
|
||
updates["AUTOTAG_EXISTING"] = value
|
||
for key, label in (
|
||
("autotag_general_threshold", "General-tag confidence"),
|
||
("autotag_character_threshold", "Character-tag confidence"),
|
||
):
|
||
if key in data:
|
||
try:
|
||
value = validate_saved_threshold(label, data[key])
|
||
except ValueError as error:
|
||
raise ValueError(f"{error}.") from None
|
||
updates[key.upper()] = value
|
||
if "autotag_template" in data:
|
||
try:
|
||
updates["AUTOTAG_TEMPLATE"] = validate_template(
|
||
data["autotag_template"], "LLM tag template"
|
||
)
|
||
except ValueError as error:
|
||
raise ValueError(f"{error}.") from None
|
||
if "autotag_suggestion_limit" in data:
|
||
value = data["autotag_suggestion_limit"]
|
||
if type(value) is not int or not 1 <= value <= MAX_SUGGESTION_LIMIT:
|
||
raise ValueError(
|
||
"Suggestions per image must be a whole number from 1 to "
|
||
f"{MAX_SUGGESTION_LIMIT}."
|
||
)
|
||
updates["AUTOTAG_SUGGESTION_LIMIT"] = value
|
||
return updates
|
||
|
||
|
||
async def _read_json(request):
|
||
"""Parse a JSON object body through the package's capped reader."""
|
||
from . import _read_json_body
|
||
|
||
return await _read_json_body(request)
|
||
|
||
|
||
class SettingsRoutesMixin:
|
||
"""Mixin providing the settings read and save endpoints."""
|
||
|
||
def _register_settings_routes(self, routes):
|
||
@routes.get("/prompt_manager/settings")
|
||
async def get_settings_route(request):
|
||
return await self.get_settings(request)
|
||
|
||
@routes.post("/prompt_manager/settings")
|
||
async def save_settings_route(request):
|
||
return await self.save_settings(request)
|
||
|
||
@routes.post("/prompt_manager/settings/validate-source")
|
||
async def validate_source_route(request):
|
||
return await self.validate_source(request)
|
||
|
||
async def get_settings(self, request):
|
||
"""Get current settings."""
|
||
try:
|
||
from ..config import AutotagConfig, PromptManagerConfig, GalleryConfig
|
||
|
||
root_paths = [
|
||
self._public_path(d) for d in GalleryConfig.MONITORING_DIRECTORIES
|
||
]
|
||
revision = await self._run_in_executor(self._config_revision)
|
||
source_status, monitor = await self._run_in_executor(self._source_status)
|
||
# #317: which thumbnail formats can be written (a cached probe).
|
||
encoders = await self._run_in_executor(thumbnail_encode.encoder_status)
|
||
return web.json_response(
|
||
{
|
||
"success": True,
|
||
**revision,
|
||
"sources": source_status,
|
||
"monitor": monitor,
|
||
"thumbnail_encoders": encoders,
|
||
"settings": {
|
||
"monitoring_enabled": GalleryConfig.MONITORING_ENABLED,
|
||
"save_foreign_runs": GalleryConfig.SAVE_FOREIGN_RUNS,
|
||
"result_timeout": PromptManagerConfig.RESULT_TIMEOUT,
|
||
"webui_display_mode": PromptManagerConfig.WEBUI_DISPLAY_MODE,
|
||
"infinite_scroll": PromptManagerConfig.INFINITE_SCROLL,
|
||
"worker_threads": PromptManagerConfig.WORKER_THREADS,
|
||
"safety_backup": PromptManagerConfig.SAFETY_BACKUP,
|
||
"thumbnail_format": PromptManagerConfig.THUMBNAIL_FORMAT,
|
||
"thumbnail_quality": PromptManagerConfig.THUMBNAIL_QUALITY,
|
||
"thumbnail_edge": PromptManagerConfig.THUMBNAIL_EDGE,
|
||
"autotag_model_type": AutotagConfig.MODEL_TYPE,
|
||
"autotag_existing": AutotagConfig.EXISTING,
|
||
"autotag_general_threshold": AutotagConfig.GENERAL_THRESHOLD,
|
||
"autotag_character_threshold": (
|
||
AutotagConfig.CHARACTER_THRESHOLD
|
||
),
|
||
"autotag_template": AutotagConfig.TEMPLATE,
|
||
"autotag_suggestion_limit": AutotagConfig.SUGGESTION_LIMIT,
|
||
"cpu_count": PromptManagerConfig.max_worker_threads(),
|
||
"gallery_root_paths": root_paths,
|
||
"gallery_root_path": root_paths[0] if root_paths else "",
|
||
"monitored_directories": [
|
||
self._public_path(d) for d in self._monitored_directories()
|
||
],
|
||
},
|
||
}
|
||
)
|
||
except Exception as e:
|
||
self.logger.error(f"Get settings error: {e}", exc_info=True)
|
||
return web.json_response(
|
||
{"success": False, "error": "Failed to get settings"},
|
||
status=500,
|
||
)
|
||
|
||
def _source_status(self):
|
||
"""``(sources, monitor)`` of GET /settings (blocking)."""
|
||
from ..config import GalleryConfig
|
||
|
||
output_dirs, auto_detected = self._output_dirs_with_origin()
|
||
return sources.describe_sources(
|
||
configured=list(GalleryConfig.MONITORING_DIRECTORIES),
|
||
output_dirs=output_dirs,
|
||
auto_detected=auto_detected,
|
||
monitor=_current_image_monitor(),
|
||
enabled=GalleryConfig.MONITORING_ENABLED,
|
||
)
|
||
|
||
async def validate_source(self, request):
|
||
"""Check one source path ``{path}``; writes nothing.
|
||
|
||
200 ``{success, valid, label, path, code, reason}``: a valid source
|
||
answers its label and public path, an invalid one its code and reason
|
||
only. A body without a string ``path`` is a 400 ``invalid-request``.
|
||
"""
|
||
data, error_response = await _read_json(request)
|
||
if error_response is not None:
|
||
too_large = error_response.status == 413
|
||
return web.json_response(
|
||
{
|
||
"success": False,
|
||
"code": "too-large" if too_large else "invalid-request",
|
||
"error": (
|
||
"Request body too large"
|
||
if too_large
|
||
else "Request body must be a JSON object"
|
||
),
|
||
},
|
||
status=error_response.status,
|
||
)
|
||
path = data.get("path")
|
||
if not isinstance(path, str):
|
||
return web.json_response(
|
||
{
|
||
"success": False,
|
||
"code": "invalid-request",
|
||
"error": "path must be a string",
|
||
},
|
||
status=400,
|
||
)
|
||
try:
|
||
result = await self._run_in_executor(sources.validate_source, path)
|
||
except Exception:
|
||
self.logger.exception("Source validation failed")
|
||
return web.json_response(
|
||
{"success": False, "code": None, "error": "Failed to check the source"},
|
||
status=500,
|
||
)
|
||
return web.json_response({"success": True, **result})
|
||
|
||
def _monitored_directories(self):
|
||
"""Directories the running image monitor watches, else the configured roots."""
|
||
from ..config import GalleryConfig
|
||
|
||
monitor = _current_image_monitor()
|
||
if monitor is not None:
|
||
return list(getattr(monitor, "monitored_directories", []))
|
||
return list(GalleryConfig.MONITORING_DIRECTORIES)
|
||
|
||
async def save_settings(self, request):
|
||
"""Save settings: validate, commit to config.json, then publish (#220).
|
||
|
||
Nothing changes at runtime until config.json holds the new values, so
|
||
a save that cannot be written reports ``persisted: false`` and leaves
|
||
the running settings as they were. ``expected_revision`` (the
|
||
``revision`` from GET) refuses to overwrite a file changed meanwhile;
|
||
without it the payload merges into what is on disk (legacy page).
|
||
"""
|
||
try:
|
||
data, error_response = await _read_json(request)
|
||
if error_response is not None:
|
||
return error_response
|
||
|
||
expected_revision = data.get("expected_revision")
|
||
if expected_revision is not None and not isinstance(expected_revision, str):
|
||
return web.json_response(
|
||
{"success": False, "error": "expected_revision must be a string"},
|
||
status=400,
|
||
)
|
||
try:
|
||
updates = self._validate_settings(data)
|
||
except ValueError as ve:
|
||
return web.json_response(
|
||
{"success": False, "error": str(ve)}, status=400
|
||
)
|
||
if updates.get("THUMBNAIL_FORMAT") == "jxl":
|
||
# #317: JPEG XL only with an encoder (a cached probe).
|
||
encoder = await self._run_in_executor(
|
||
functools.partial(
|
||
thumbnail_encode.detect_jxl_encoder, recheck_missing=True
|
||
)
|
||
)
|
||
if encoder is None:
|
||
return web.json_response(
|
||
{
|
||
"success": False,
|
||
"code": "jxl-unavailable",
|
||
"error": thumbnail_encode.JXL_UNAVAILABLE,
|
||
},
|
||
status=400,
|
||
)
|
||
|
||
refused = self._thumbnail_change_refused(updates)
|
||
if refused is not None:
|
||
return refused
|
||
|
||
# Off the loop: an accepted root is resolved (filesystem access).
|
||
new_roots, error = await self._run_in_executor(
|
||
self._parse_gallery_roots, data
|
||
)
|
||
if error:
|
||
return web.json_response({"success": False, **error}, status=400)
|
||
roots_change = new_roots is not None and await self._run_in_executor(
|
||
self._roots_change, new_roots
|
||
)
|
||
|
||
published = {}
|
||
|
||
def publish(_config):
|
||
# Under the commit lock: saves reach the runtime in the order
|
||
# they were written, so the runtime ends on the last one.
|
||
published.update(self._publish_settings(updates, new_roots))
|
||
|
||
async with contextlib.AsyncExitStack() as stack:
|
||
hold = None
|
||
if roots_change:
|
||
try:
|
||
hold = await stack.enter_async_context(
|
||
self._jobs.hold(
|
||
SOURCE_CHANGE_JOB_KIND,
|
||
SOURCE_CHANGE_JOB_TITLE,
|
||
admission="records",
|
||
)
|
||
)
|
||
except JobBusy as busy:
|
||
return busy_response(busy)
|
||
try:
|
||
_saved, revision = await self._run_in_executor(
|
||
get_config_store().commit,
|
||
_settings_mutation(updates, new_roots),
|
||
expected_revision=expected_revision,
|
||
publish=publish,
|
||
)
|
||
except (ConfigUnreadable, RevisionConflict, OSError) as exc:
|
||
if hold is not None:
|
||
hold.finish("failed")
|
||
return self._config_commit_failure(exc)
|
||
|
||
return web.json_response(
|
||
{
|
||
"success": True,
|
||
"message": "Settings saved successfully",
|
||
"restart_required": bool(published["restart_required_fields"]),
|
||
"persisted": True,
|
||
"revision": revision,
|
||
**published,
|
||
}
|
||
)
|
||
except Exception as e:
|
||
self.logger.error(f"Save settings error: {e}", exc_info=True)
|
||
return web.json_response(
|
||
{"success": False, "error": "Failed to save settings"},
|
||
status=500,
|
||
)
|
||
|
||
def _thumbnail_change_refused(self, updates):
|
||
"""409 ``busy`` for a thumbnail format, quality or size change while
|
||
Convert outdated runs (review I4): the job converts to the settings
|
||
it started with, and a change under it would make it remove previews
|
||
in the newly chosen format. Unchanged values pass."""
|
||
from ..config import PromptManagerConfig
|
||
|
||
changed = any(
|
||
key in updates and updates[key] != getattr(PromptManagerConfig, key)
|
||
for key in _THUMBNAIL_SETTINGS
|
||
)
|
||
job = self._jobs.active(THUMBNAILS_JOB_KIND) if changed else None
|
||
if job is None or job.scope.get("mode") != "convert":
|
||
return None
|
||
return web.json_response(
|
||
{
|
||
"success": False,
|
||
"code": "busy",
|
||
"error": (
|
||
f"{job.title} is running. Change the thumbnail settings "
|
||
"when it finishes, or cancel it first."
|
||
),
|
||
"running": {"id": job.id, "title": job.title},
|
||
},
|
||
status=409,
|
||
)
|
||
|
||
def _publish_settings(self, updates, new_roots):
|
||
"""Install committed settings at runtime (inside the config commit).
|
||
|
||
The values are already durable. A publication that fails is reported
|
||
as ``runtime_applied: false`` with the fields that need a restart;
|
||
nothing is retried or rolled back. Never raises.
|
||
"""
|
||
from ..config import GalleryConfig, PromptManagerConfig
|
||
|
||
from ..config import AutotagConfig
|
||
|
||
for name, value in updates.items():
|
||
if name in _AUTOTAG_SETTINGS:
|
||
setattr(AutotagConfig, name[len(_AUTOTAG_PREFIX) :], value)
|
||
continue
|
||
owner = GalleryConfig if name in _GALLERY_SETTINGS else PromptManagerConfig
|
||
setattr(owner, name, value)
|
||
restart_fields = []
|
||
runtime_applied = True
|
||
if new_roots is not None:
|
||
try:
|
||
if self._apply_gallery_roots(new_roots):
|
||
restart_fields.append("gallery_root_paths")
|
||
except Exception as e:
|
||
self.logger.error(
|
||
f"Saved gallery roots could not be applied: {e}", exc_info=True
|
||
)
|
||
runtime_applied = False
|
||
restart_fields.append("gallery_root_paths")
|
||
if "MONITORING_ENABLED" in updates:
|
||
# The monitor starts with the server: a restart applies the setting
|
||
# unless the observer already matches it.
|
||
if updates["MONITORING_ENABLED"] != self._observer_alive():
|
||
restart_fields.append("monitoring_enabled")
|
||
return {
|
||
"runtime_applied": runtime_applied,
|
||
"restart_required_fields": restart_fields,
|
||
}
|
||
|
||
@staticmethod
|
||
def _roots_change(new_roots):
|
||
"""Whether a save changes the sources (blocking: it resolves them).
|
||
|
||
Compared as directories, not spellings: the legacy page resends the
|
||
roots resolved, while config.json may hold them as hand-written
|
||
(relative, another case), and an unchanged resend is no change.
|
||
"""
|
||
from ..config import GalleryConfig
|
||
|
||
if new_roots is None:
|
||
return False
|
||
return [_root_key(root) for root in new_roots] != [
|
||
_root_key(root) for root in GalleryConfig.MONITORING_DIRECTORIES
|
||
]
|
||
|
||
@staticmethod
|
||
def _observer_alive():
|
||
"""Whether the image monitor's observer is running now. Never raises."""
|
||
try:
|
||
return sources.monitor_state(_current_image_monitor())[1]
|
||
except Exception:
|
||
return False
|
||
|
||
def _config_commit_failure(self, exc):
|
||
"""The response for a config commit that wrote nothing."""
|
||
not_saved = {"success": False, "persisted": False, "runtime_applied": False}
|
||
if isinstance(exc, ConfigUnreadable):
|
||
self.logger.warning(f"Settings not saved: {exc}")
|
||
return web.json_response(
|
||
{
|
||
**not_saved,
|
||
"code": "config-unreadable",
|
||
"error": (
|
||
"config.json cannot be read, so nothing was saved. "
|
||
"Fix or remove the file, then save again."
|
||
),
|
||
},
|
||
status=409,
|
||
)
|
||
if isinstance(exc, RevisionConflict):
|
||
return web.json_response(
|
||
{
|
||
**not_saved,
|
||
"code": "settings-changed",
|
||
"error": "Settings changed since they were loaded. Reload them.",
|
||
"revision": exc.current,
|
||
},
|
||
status=409,
|
||
)
|
||
self.logger.error(f"Could not write config.json: {exc}")
|
||
return web.json_response(
|
||
{
|
||
**not_saved,
|
||
"code": "config-write-failed",
|
||
"error": "Settings could not be written to config.json.",
|
||
},
|
||
status=500,
|
||
)
|
||
|
||
@staticmethod
|
||
def _config_revision():
|
||
"""``{"revision": ...}``, or a null revision with ``config_error``."""
|
||
try:
|
||
_data, revision = get_config_store().read()
|
||
except ConfigUnreadable:
|
||
return {"revision": None, "config_error": "config-unreadable"}
|
||
return {"revision": revision}
|
||
|
||
@staticmethod
|
||
def _validate_settings(data):
|
||
"""Scalar settings of a payload as ``{CONFIG_ATTR: value}``.
|
||
|
||
Raises ValueError with a user-facing message on the first bad value;
|
||
nothing is applied until every value passed.
|
||
"""
|
||
from ..config import PromptManagerConfig
|
||
|
||
updates = {}
|
||
if "result_timeout" in data:
|
||
updates["RESULT_TIMEOUT"] = validate_result_timeout(data["result_timeout"])
|
||
if "webui_display_mode" in data:
|
||
mode = data["webui_display_mode"]
|
||
if mode not in ("popup", "newtab"):
|
||
raise ValueError("webui_display_mode must be 'popup' or 'newtab'")
|
||
updates["WEBUI_DISPLAY_MODE"] = mode
|
||
if "infinite_scroll" in data:
|
||
if not isinstance(data["infinite_scroll"], bool):
|
||
raise ValueError("infinite_scroll must be true or false")
|
||
updates["INFINITE_SCROLL"] = data["infinite_scroll"]
|
||
if "monitoring_enabled" in data:
|
||
if not isinstance(data["monitoring_enabled"], bool):
|
||
raise ValueError("monitoring_enabled must be true or false")
|
||
updates["MONITORING_ENABLED"] = data["monitoring_enabled"]
|
||
if "save_foreign_runs" in data:
|
||
if not isinstance(data["save_foreign_runs"], bool):
|
||
raise ValueError("save_foreign_runs must be true or false")
|
||
updates["SAVE_FOREIGN_RUNS"] = data["save_foreign_runs"]
|
||
if "safety_backup" in data:
|
||
if not isinstance(data["safety_backup"], bool):
|
||
raise ValueError("safety_backup must be true or false")
|
||
updates["SAFETY_BACKUP"] = data["safety_backup"]
|
||
if "worker_threads" in data:
|
||
updates["WORKER_THREADS"] = validate_worker_threads(
|
||
data["worker_threads"], PromptManagerConfig.max_worker_threads()
|
||
)
|
||
if "thumbnail_format" in data:
|
||
updates["THUMBNAIL_FORMAT"] = thumbnail_settings.validate_format(
|
||
data["thumbnail_format"]
|
||
)
|
||
if "thumbnail_quality" in data:
|
||
updates["THUMBNAIL_QUALITY"] = thumbnail_settings.validate_quality(
|
||
data["thumbnail_quality"]
|
||
)
|
||
if "thumbnail_edge" in data:
|
||
updates["THUMBNAIL_EDGE"] = thumbnail_settings.validate_edge(
|
||
data["thumbnail_edge"]
|
||
)
|
||
updates.update(_validate_autotag_settings(data))
|
||
return updates
|
||
|
||
def _parse_gallery_roots(self, data):
|
||
"""Extract and validate gallery roots from a settings payload.
|
||
|
||
Accepts ``gallery_root_paths`` (list, preferred) or the legacy single
|
||
``gallery_root_path`` string. Blank entries are dropped.
|
||
|
||
Each entry passes the same checks as validate-source
|
||
(``sources.source_problem``): the form, then containment as text,
|
||
before anything is resolved. Blocking (an accepted root is resolved).
|
||
|
||
Returns:
|
||
(roots, error): ``roots`` is the validated list, or ``None`` when
|
||
the payload carries no gallery root key; ``error`` is the coded
|
||
body of the 400 when validation failed (``roots`` is then None).
|
||
An unusable source is ``invalid-source`` naming its public path
|
||
and its position in the list.
|
||
"""
|
||
if "gallery_root_paths" in data:
|
||
raw = data["gallery_root_paths"]
|
||
if not isinstance(raw, list):
|
||
return None, _request_error("gallery_root_paths must be a list")
|
||
elif "gallery_root_path" in data:
|
||
raw = [data["gallery_root_path"]]
|
||
else:
|
||
return None, None
|
||
|
||
from ..config import GalleryConfig
|
||
|
||
roots = []
|
||
seen = set()
|
||
for index, entry in enumerate(raw):
|
||
if not isinstance(entry, str):
|
||
return None, _request_error("Gallery root paths must be strings")
|
||
entry = entry.strip()
|
||
if not entry:
|
||
continue
|
||
code, reason = sources.source_problem(entry)
|
||
if code is not None:
|
||
return None, _invalid_source(index, entry, code, reason)
|
||
root = GalleryConfig.resolve_gallery_root(entry)
|
||
keys = {("path", _source_identity(root)), ("file", _stat_identity(root))}
|
||
keys.discard(("file", None))
|
||
if keys & seen:
|
||
continue # another spelling of a root already listed
|
||
seen |= keys
|
||
roots.append(root)
|
||
return roots, None
|
||
|
||
def _apply_gallery_roots(self, roots):
|
||
"""Install validated gallery roots; returns True when they changed.
|
||
|
||
Another spelling of the same directories installs the resolved
|
||
spelling and is no change (nothing to restart for).
|
||
"""
|
||
from ..config import GalleryConfig
|
||
|
||
if roots == list(GalleryConfig.MONITORING_DIRECTORIES):
|
||
return False
|
||
if not self._roots_change(roots):
|
||
GalleryConfig.MONITORING_DIRECTORIES = roots
|
||
return False
|
||
GalleryConfig.MONITORING_DIRECTORIES = roots
|
||
self._cached_output_dir = None
|
||
self.reset_gallery_roots_cache()
|
||
return True
|