Files
ComfyAssets-ComfyUI_PromptM…/database/category_import.py
T
Vito 80c6ec5340 fix(lora): find LoraManager's sidecars, previews and example images in every storage configuration (#355) (#358)
* fix(lora): read LoraManager's settings and storage layout the way it does (#355)

Add py/lora_manager_layout.py: the settings file in LoraManager's lookup
order (environment folder, portable plugin file, user config folder), only
the seven keys the import needs, the LoRA roots, the centralized sidecar
root, the example-images root and the active library, each folder through
one guard. Sidecar discovery for both storage modes and the local preview
and example-image lookup live there too.

The test runner and the browser test server point LoraManager's settings
lookup at a disposable folder, so no test reads the real settings.

* fix(lora): import the sidecars and local images LoraManager really uses (#355)

The import, the legacy scan, the trigger-word cache and the image server
now share LoraManager's layout: sidecars beside the models (alongside) or
under the sidecar root (centralized), kept only when their model exists
inside a LoRA root. Each LoRA links its LoraManager preview and example
images where they are; CivitAI downloads run only for a LoRA without any
local image. The review adds skipped, with_local_media and the layout, and
offers no token when LoraManager's settings cannot be used; the legacy scan
reports the same reason without replacing anything.

find_lora_directories becomes default_lora_roots (no scan of the
LoraManager install); the preview and example-folder helpers it replaced
are removed. The trigger cache never raises into a running node.

* fix(lora): never serve a LoraManager folder that holds the home folder (#355)

The folder guard also rejects ancestors of the home folder (/home,
C:\Users), compared in the realpath + normcase form, so a LoraManager
setting cannot widen the image server's allow-list to every user's files.

* fix(lora): show linked LoraManager videos as videos (#355)

_enrich_images marks every image without is_video by its extension, so an
.mp4 preview outside the output folders shows the Video preview label and
plays in the inspector. Tests cover serving the sidecar and example-image
folders only while the integration is on, and a filesystem root as the
sidecar folder adding nothing.

* feat(lora): the import review names the LoraManager settings it read (#355)

The review gains a first row, LoraManager ("<source> settings · <mode>
storage · library <name>", the settings file as its hover title), and its
Found row counts metadata files, LoRAs and LoRAs with local images. A plan
whose LoraManager settings cannot be used takes the close-only path:
"LoraManager settings: not usable: <reason>. Nothing was changed." The
browser fixture writes each LoRA's model file and can leave out the local
preview, so the download, gate and cancel specs still exercise CivitAI.

* docs(lora): describe how the import finds LoraManager's files (#355)

* test(lora): set the settings folder relative to the process folder (#355)

os.path.relpath fails across Windows drives (the temp folder on C:, the
checkout on D:); the test now changes into its temp folder instead.

* fix(lora): review findings for the LoraManager layout (#355)

- The example-images library subfolder goes through the folder guard like
  its root, so its canonical (normcased) form matches the media check on
  Windows for a library name with capitals.
- A failed trigger-word load is retried by a running node only after
  TRIGGER_RETRY_SECONDS, not on every prompt run.
- A review whose discovery cannot list a folder says so (folder-unreadable,
  the folder's name only) instead of a generic error.

* test(images): hold the listing clock in the deferred-walk test

test_a_deferred_walk_waits_at_least_half_a_second set the previous walk
29.99 s back against a 30 s interval and then read the real clock again:
a runner slower than 10 ms between the two lines passed the interval and
the walk started at once (failed on macOS 3.13 and Windows 3.11). The
module's clock is now held for the mark, so the deferred walk is always
the one measured.

* test(lora): write the unkept-settings fixture as raw text

CodeQL read the dict with a credential-named key flowing into write_text
as clear-text storage of a secret. The value is a marker, so the fixture
now writes the JSON text directly and names the value MARKER.

* fix(lora): link each LoRA's cover as its newest image (#355)

Workspace lists show a prompt's media newest link first, so the import
links a record's images last to first: the card shows the cover (a still
in front of a leading video) the import put first.

* fix(lora): show LoRA-linked media on the Library page and in the inspector (#355)

Library previews, the positive detail and the per-prompt images page list
a prompt's linked media under the output folders plus, while the LoRA
integration is on, LoraManager's guarded folders and the download cache
(_media_roots; output root indices keep their meaning). That media keeps
its rooted identity, so Info and the media viewer open it; the path-based
serve route answers for those roots only with a file the database records
(either path spelling), never serves or makes a preview there, and output
requests never read LoraManager's layout. Such media is marked
linked_only: no preview file, no favorite star, no Tag action. Show in
folder accepts those roots; the download cache is named, not created.

* fix(lora): expose only linked files under LoraManager's folders (#355)

Serve, inspect and Show in folder share one gate for a LoRA-linked root
(_media_roots past the output folders): a file the database does not
record as a linked image is refused with 403, checked by its given and
its real path. Before, inspect and reveal read any file under those
folders by path.

* fix(lora): check the file Show in folder would open under a LoRA root (#355)

reveal_image resolved the requested path through the client-path
resolver, which can fall back to a path anchor; under a LoRA-linked root
the file that would open now passes the same recorded-media gate, so only
a linked file is ever revealed there.
2026-10-26 21:21:33 -07:00

202 lines
8.4 KiB
Python

"""Atomic replacement of one imported category (#221, #249 System S10).
The LoRA reference import used to delete its whole category and then save
each record in its own transaction, so a failure part way left the previous
collection deleted and the new one partial. ``replace_category_prompts``
does both in one ``BEGIN IMMEDIATE`` transaction: the category's current
prompts (with their tags and image links) are replaced by the staged
records, or, on any error, nothing changes.
A staged record is ``{text, hash, tags, images}``. A record whose hash a
prompt outside the category already has links its images to that prompt
(the legacy import did the same); a second record with the hash of an
earlier one links its images to that one. Neither is a new prompt.
"""
from typing import Any, Dict, List, Optional, Sequence
try:
from .maintenance import PlanChanged
from .pairs import PairDependencyError
from .workflow_documents import documents_of_rows, release_documents
except ImportError: # pragma: no cover - flat test imports
from database.maintenance import PlanChanged
from database.pairs import PairDependencyError
from database.workflow_documents import documents_of_rows, release_documents
class EmptyReplacement(ValueError):
"""The replacement has no record and would remove every current import."""
# The category's prompt ids, as a subquery (one bound parameter).
_IN_CATEGORY = "SELECT id FROM prompts WHERE category = ?"
# Each record's outcome and the result counter it adds to.
_COUNTERS = {"imported": "imported", "linked": "linked", "duplicate": "duplicates"}
def _placeholders(values: Sequence[Any]) -> str:
return ",".join("?" * len(values))
class CategoryImportOperations:
"""Read the state of an imported category and replace it atomically."""
def category_import_state(self, category: str) -> Dict[str, Any]:
"""``{ids, paired}``: the category's prompt ids (ascending) and how
many of them a saved pair uses (those block a replacement)."""
with self.model.get_connection() as conn:
ids = [
row[0]
for row in conn.execute(
"SELECT id FROM prompts WHERE category = ? ORDER BY id",
(category,),
).fetchall()
]
paired = conn.execute(
"SELECT COUNT(*) FROM prompts WHERE category = ? AND id IN "
"(SELECT positive_prompt_id FROM prompt_pairs UNION "
"SELECT negative_prompt_id FROM prompt_pairs)",
(category,),
).fetchone()[0]
return {"ids": ids, "paired": paired}
def existing_prompt_hashes(
self, hashes: Sequence[str], exclude_category: str
) -> set:
"""The given hashes a prompt outside ``exclude_category`` already has."""
found = set()
wanted = list(dict.fromkeys(hashes))
with self.model.get_connection() as conn:
for start in range(0, len(wanted), 500):
chunk = wanted[start : start + 500]
rows = conn.execute(
f"SELECT hash FROM prompts WHERE hash IN ({_placeholders(chunk)}) "
"AND (category IS NULL OR category != ?)",
[*chunk, exclude_category],
).fetchall()
found.update(row[0] for row in rows)
return found
def replace_category_prompts(
self,
category: str,
records: List[Dict[str, Any]],
*,
expected_ids: Optional[List[int]] = None,
allow_empty: bool = False,
) -> Dict[str, Any]:
"""Replace every prompt of ``category`` with ``records`` in one transaction.
Raises (and changes nothing): ``PlanChanged`` when ``expected_ids`` is
given and the category's prompt ids differ from it;
``PairDependencyError`` when a saved pair uses one of its prompts;
``EmptyReplacement`` when ``records`` is empty while the category has
prompts, unless ``allow_empty`` (an empty replacement that was
reviewed). Any other error rolls everything back too.
Returns ``{removed, imported, linked, duplicates, images, rows}``:
prompts removed and created, records linked to an existing prompt or
to an earlier record with the same text, image links added, and per
record ``{name, outcome}`` (``imported``/``linked``/``duplicate``).
"""
with self._pair_transaction() as conn:
ids = [
row[0]
for row in conn.execute(
"SELECT id FROM prompts WHERE category = ? ORDER BY id",
(category,),
).fetchall()
]
if expected_ids is not None and ids != list(expected_ids):
raise PlanChanged("The imported prompts changed since the review")
if not records and ids and not allow_empty:
raise EmptyReplacement(
"Nothing to import; the previous imports were kept"
)
self._ensure_category_unpaired(conn, category)
removed = self._delete_category_rows(conn, category, ids)
result = {
"removed": removed,
"imported": 0,
"linked": 0,
"duplicates": 0,
"images": 0,
"rows": [],
}
created = {}
for record in records:
self._import_record(conn, category, record, created, result)
return result
def _delete_category_rows(self, conn, category: str, ids: List[int]) -> int:
"""Delete the category's prompts with their image links and tags.
No commit. The rows are selected by category (just verified against
``ids`` under the write lock), so no statement binds one parameter per
prompt and SQLite's variable limit never caps a collection.
"""
if not ids:
return 0
documents = documents_of_rows(conn, "prompt_id", ids) # chunked
conn.execute(
f"DELETE FROM generated_images WHERE prompt_id IN ({_IN_CATEGORY})",
(category,),
)
release_documents(conn, documents)
conn.execute(
f"DELETE FROM prompt_tags WHERE prompt_id IN ({_IN_CATEGORY})",
(category,),
)
return conn.execute(
"DELETE FROM prompts WHERE category = ?", (category,)
).rowcount
@staticmethod
def _ensure_category_unpaired(conn, category: str) -> None:
"""Raise PairDependencyError when a saved pair uses a category prompt."""
row = conn.execute(
f"SELECT id FROM prompt_pairs WHERE positive_prompt_id IN ({_IN_CATEGORY}) "
f"OR negative_prompt_id IN ({_IN_CATEGORY}) LIMIT 1",
(category, category),
).fetchone()
if row:
raise PairDependencyError(
f"Prompt belongs to saved pair {row[0]}; delete the pair first "
"or save changed text as a new prompt"
)
def _import_record(self, conn, category, record, created, result) -> None:
"""Save one staged record on ``conn``, or link it to the prompt it repeats."""
prompt_hash = record["hash"]
name = record.get("name") or record["text"]
if prompt_hash in created:
prompt_id, outcome = created[prompt_hash], "duplicate"
else:
row = conn.execute(
"SELECT id FROM prompts WHERE hash = ?", (prompt_hash,)
).fetchone()
if row is not None:
prompt_id, outcome = row[0], "linked"
else:
prompt_id = self._insert_prompt(
conn,
record["text"],
category,
list(record.get("tags") or []),
None,
None,
prompt_hash,
)
outcome = "imported"
created[prompt_hash] = prompt_id
result[_COUNTERS[outcome]] += 1
# Linked last to first: every workspace list shows a prompt's media
# newest link first, so the record's first image (the LoRA cover,
# #355) is the one a Library card shows.
for image in reversed(record.get("images") or []):
if self._insert_image_link(conn, prompt_id, image):
result["images"] += 1
result["rows"].append({"name": name, "outcome": outcome})