* fix(lora): detect LoraManager in ComfyUI's extra custom_nodes folders Auto-detection looked only in ComfyUI's main custom_nodes folder (#144). It now also searches every custom_nodes folder ComfyUI registers through folder_paths, main folder first, skipping folders that cannot be read. * fix(lora): stage imports before replacing the collection (#221) The LoRA import deleted the whole lora-manager category first and then saved each record in its own transaction, so a discovery, download or database failure left the previous collection gone or partial. The import now runs in three stages: discover and fingerprint the metadata files, stage every record (CivitAI downloads go into the image cache first, counted), then replace the category in one BEGIN IMMEDIATE transaction (replace_category_prompts). Any failure leaves the previous prompts, tags and image links exactly as they were. Prompts a saved pair uses block the replacement; an empty replacement of a non-empty collection needs a reviewed import. POST /prompt_manager/lora/import/preview reviews an import without writing or requesting anything; POST /lora/import/apply {token} runs it as the Activity job "LoRA reference import" (records admission, cancellable while it downloads, the safety backup policy before the replace, refused with plan-changed when the files changed since the review). The legacy POST /lora/scan runs the same stages with its SSE event shape. * feat(lora): the LoRA save takes the settings revision POST /prompt_manager/lora/enable accepts the optional expected_revision that GET /settings returns, so the System Save row refuses to write over a config.json changed elsewhere (settings-changed, nothing written). The legacy page sends none and still merges into what is on disk. * feat(system): configure ComfyUI and LoRA integrations natively System › Integrations replaces its hand-off with the concept's two surfaces. ComfyUI: only the send destination and renderer the bridge supports can be chosen; the other options and Return to canvas are disabled with the reason, and Host compatibility shows the renderer the open ComfyUI windows report (each bridge destination now carries renderer: classic or nodes2) (D106). LoRA & resources: detection, the enabled setting and the loaded trigger words read as separate facts, the read-only LoraManager path row follows the toggle (D106), and the CivitAI key is never filled in: typing drafts a new key, blank keeps the saved one and Clear saved key drafts its removal (D114). They save through the one Save row (/lora/enable with the settings revision). LoRA reference data → Review import shows the server's read-only review (replacement, what saved pairs block, downloads, backup box) and Start runs the LoRA reference import Activity job (D107), with its own Activity descriptor and Review again into Integrations when the files or pairs overtook it. * test(system): compare Integrations with the concept system-integrations-concept.spec compares System › Integrations (both themes, 1600 and 390 wide) with the concept, mapping only D106 and D114, and the LoRA import review with the concept's record-changing review, mapping D107; each comparison catches a removed row, a renamed label or option, a re-enabled unsupported option and a swapped token. On the real ComfyUI host, each bridge destination reports the renderer its window draws nodes with, before and after switching it, and System › Integrations shows it. * test(coverage): record the Integrations frontend floors coverage:update after the full frontend run: system-integrations.mjs at its measured floor, and the raised maintenance review, job view and maintenance floors. * test(system): wait for the renderer line before clicking Integrations rows CI Firefox (390 wide) clicked the LoraManager toggle while the renderer check's line above it changed text and moved the rows, so the click did not reach the switch. The specs now wait for that line to settle (a visible state) before interacting. * fix(lora): recheck the files before the replace and stop an abandoned scan Review fixes for the staged LoRA import (#221): - The metadata files are listed and fingerprinted again right before the replace transaction, so a file changed, removed or added while the downloads ran aborts the import with nothing deleted (System job: plan-changed, Review again; legacy scan: an error frame in its own words). The tests now change real files behind a held download. - A legacy scan whose page closes stops staging before its next LoRA and keeps its records hold until staging has stopped; CivitAI images are written to a temp file beside the cache entry and moved in place, so a half-written image is never seen as cached. - Start refuses with plan-changed when the integration was turned off or moved to another install since the review. - A failed job keeps the skipped count and the names of the LoRAs that could not be prepared. - The replace binds the category instead of one parameter per prompt (SQLite's variable limit), /lora/status says whether a detected install can be used, and the legacy scan logs expected refusals as warnings. * fix(system): partial saves, key focus and readable selects in Integrations A save that writes the LoRA part but not the settings part now keeps the saved part, adopts the new revision and highlights only what failed, so the next save needs no conflict. The CivitAI key status is a persistent live region, Clear saved key returns focus to the key field, and the key draft is dropped when the section is left. The send-destination and renderer selects keep their width on narrow screens. A detected LoraManager outside custom_nodes says it cannot be enabled. * fix(lora): keep the save outcome, honour the umask and sweep stale downloads Leaving Integrations drops the CivitAI key draft only when a key was typed, so the last Save's outcome survives and Sources still marks a refused source. The key status line is rewritten only when it changes. Cached CivitAI images are opened like a plain save, so they keep the umask's mode, and each import removes .pm-*.part files older than an hour from the image cache. A legacy scan stopped because its page left ends cancelled in Activity, and staging is awaited to the end even if the handler is cancelled again. * fix(lora): the import review takes a lease beside a restore The LoRA import review reads the library, so like the maintenance and restore previews it now runs under a request lease: it is refused with 409 busy while a restore runs, and a restore waits for it before it switches the file. Tests pin that a restore is refused while an import runs and that the review, the reviewed import and the admin page's scan are refused while a restore runs.
199 lines
8.2 KiB
Python
199 lines
8.2 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
|
|
for image in record.get("images") or []:
|
|
if self._insert_image_link(conn, prompt_id, image):
|
|
result["images"] += 1
|
|
result["rows"].append({"name": name, "outcome": outcome})
|