Files
ComfyAssets-ComfyUI_PromptM…/tests/browser/workspace_integrations_fixture.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

217 lines
8.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""System › Integrations test hooks for the browser tests (#249 System S10).
A fake LoraManager install lives under this server's temp root; nothing ever
reaches a real LoraManager, ComfyUI install or the network:
- ``POST /__test__/integrations/reset`` turns the integration off (no path,
no key, no trigger words), removes the fake install, its LoRA folder and
the image cache, forgets every LoRA import and injected failure, and opens
the download gate;
- ``POST /__test__/integrations/lora-manager``
``{loras, civitai, preview, previous, settings}`` writes
``custom_nodes/ComfyUI-Lora-Manager`` (detected through the
``folder_paths`` stub's base path) and ``loras`` LoRAs under
``models/loras``: each a ``<stem>.safetensors`` model beside its
``<stem>.metadata.json`` sidecar (LoraManager's alongside layout, #355)
and, unless ``preview`` is false, a local preview PNG; ``civitai`` adds one
CivitAI example image per LoRA (served by the stub opener below; an import
downloads it only for a LoRA without a local preview); ``previous`` saves
that many earlier ``lora-manager`` imports with tags and image links;
``settings: "invalid"`` makes LoraManager's settings file unreadable JSON
(the server's own isolated settings folder, ``LORA_MANAGER_SETTINGS_DIR``);
- ``POST /__test__/integrations/gate`` ``{hold}`` holds every CivitAI
download until it is released (``{"hold": false}``), so a test sees the job
while it downloads;
- ``POST /__test__/integrations/fail-import`` makes the next collection
replacement fail (a database error after staging);
- ``POST /__test__/integrations/pair`` saves a pair whose positive is the first
imported prompt (a saved pair that blocks the replacement);
- ``GET /__test__/integrations/state`` answers the imported prompt texts,
whether a CivitAI key is saved and the downloads served.
CivitAI downloads are always answered by a stub opener (a small PNG), so no
test ever opens a network connection.
"""
import io
import json
import os
import shutil
import threading
from pathlib import Path
from aiohttp import web
from PIL import Image
MAX_LORAS = 20
CATEGORY = "lora-manager"
def _png():
buffer = io.BytesIO()
Image.new("RGB", (8, 8), "#3a6ea5").save(buffer, "PNG")
return buffer.getvalue()
class _Response:
def __init__(self, body):
self._body = io.BytesIO(body)
self.headers = {"Content-Length": str(len(body))}
def read(self, amount=-1):
return self._body.read(amount)
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def register_integrations_commands(app, routes, api, root: Path):
from py import lora_utils
from py.config import IntegrationConfig
from utils.hashing import generate_prompt_hash
lora_manager = root / "custom_nodes" / "ComfyUI-Lora-Manager"
loras = root / "models" / "loras"
gate = threading.Event()
gate.set()
served = []
failures = {"replace": 0}
pairs = [] # the blocking pairs this fixture saved
real_replace = type(api.db).replace_category_prompts
def stub_open(request, timeout=10):
served.append(request.full_url)
gate.wait(30)
return _Response(_png())
lora_utils._open_url = stub_open
def replace(db, *args, **kwargs):
if failures["replace"] > 0:
failures["replace"] -= 1
raise RuntimeError("Injected replacement failure")
return real_replace(db, *args, **kwargs)
type(api.db).replace_category_prompts = replace
def settings_file():
return Path(os.environ["LORA_MANAGER_SETTINGS_DIR"]) / "settings.json"
def reset():
settings_file().unlink(missing_ok=True)
IntegrationConfig.LORA_MANAGER_ENABLED = False
IntegrationConfig.LORA_MANAGER_PATH = ""
IntegrationConfig.LORA_TRIGGER_WORDS_ENABLED = False
IntegrationConfig.CIVITAI_API_KEY = ""
lora_utils.get_trigger_cache().clear()
gate.set()
served.clear()
failures["replace"] = 0
cache = Path(lora_utils.get_lora_image_cache_dir(create=False))
for folder in (lora_manager, loras, cache):
shutil.rmtree(folder, ignore_errors=True)
for pair_id in pairs:
api.db.delete_prompt_pair(pair_id)
pairs.clear()
real_replace(api.db, CATEGORY, [], allow_empty=True)
@routes.post("/__test__/integrations/reset")
async def integrations_reset(request):
reset()
return web.json_response({"success": True})
@routes.post("/__test__/integrations/lora-manager")
async def make_lora_manager(request):
data = await request.json() if request.can_read_body else {}
count = data.get("loras", 2)
previous = data.get("previous", 0)
preview = data.get("preview", True)
settings = data.get("settings")
for value in (count, previous):
if isinstance(value, bool) or not isinstance(value, int):
raise web.HTTPBadRequest()
if not 0 <= count <= MAX_LORAS or not 0 <= previous <= MAX_LORAS:
raise web.HTTPBadRequest()
if not isinstance(preview, bool) or settings not in (None, "invalid"):
raise web.HTTPBadRequest()
if settings == "invalid":
settings_file().write_text("{not json", encoding="utf-8")
(lora_manager / "py").mkdir(parents=True, exist_ok=True)
(lora_manager / "__init__.py").write_text("")
loras.mkdir(parents=True, exist_ok=True)
for number in range(count):
stem = f"style_{number + 1:02}"
civitai = {"trainedWords": [f"trigger{number + 1}"]}
if data.get("civitai") is True:
civitai["images"] = [
{
"url": f"https://image.civitai.com/x/{stem}.jpeg",
"meta": {"prompt": f"{stem} example prompt"},
}
]
meta = {
"file_name": f"{stem}.safetensors",
"model_name": f"Style {number + 1:02}",
"civitai": civitai,
}
(loras / f"{stem}.safetensors").write_bytes(b"model")
(loras / f"{stem}.metadata.json").write_text(json.dumps(meta))
if preview:
(loras / f"{stem}.png").write_bytes(_png())
for number in range(previous):
text = f"previous lora import {number + 1}"
prompt_id = api.db.save_prompt(
text=text,
category=CATEGORY,
tags=[CATEGORY, f"lora:previous-{number + 1}"],
prompt_hash=generate_prompt_hash(text),
)
api.db.link_image_to_prompt(str(prompt_id), str(loras / "old.png"))
return web.json_response({"success": True})
@routes.post("/__test__/integrations/gate")
async def download_gate(request):
data = await request.json()
if not isinstance(data.get("hold"), bool):
raise web.HTTPBadRequest()
if data["hold"]:
gate.clear()
else:
gate.set()
return web.json_response({"success": True})
@routes.post("/__test__/integrations/fail-import")
async def fail_import(request):
failures["replace"] = 1
return web.json_response({"success": True})
@routes.post("/__test__/integrations/pair")
async def pair(request):
with api.db.model.get_connection() as conn:
row = conn.execute(
"SELECT text FROM prompts WHERE category = ? ORDER BY id LIMIT 1",
(CATEGORY,),
).fetchone()
if row is None:
raise web.HTTPConflict()
pairs.append(api.db.save_prompt_pair(row[0], "blurry"))
return web.json_response({"success": True})
@routes.get("/__test__/integrations/state")
async def state(request):
imports = api.db.search_prompts(category=CATEGORY, limit=MAX_LORAS * 2)
return web.json_response(
{
"imports": sorted(prompt["text"] for prompt in imports),
"key_saved": bool(IntegrationConfig.CIVITAI_API_KEY),
"enabled": IntegrationConfig.LORA_MANAGER_ENABLED,
"trigger_words": IntegrationConfig.LORA_TRIGGER_WORDS_ENABLED,
"downloads": len(served),
}
)
return reset