Compare commits

...
6 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 5.5 b81aa84898 release: v0.7.12 - restrict client-supplied backend URLs (SSRF)
Ollama chat, Tagger VLM, Eagle and the Unsloth relay accepted the target URL
from the request. Add py/services/url_guard.py: loopback or operator-listed
WFS_ALLOWED_BACKEND_HOSTS only, http(s) only, no credentials, no redirects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 06:49:16 +09:00
ketle-manandClaude Sonnet 5.5 4179511e1b fix(security): restrict preview downloads to CivitAI hosts, fix Host-header based origin
- download_image: https + CivitAI hosts only (also validates redirects, 50MB cap);
  sidecar-supplied image URLs could trigger SSRF / file:// reads
- Lora Manager bridge: connect to 127.0.0.1 with the real listening port instead
  of the request Host header
- safeHttpUrl for sample/fallback image URLs; DEVLOG

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:32:58 +09:00
ketle-manandClaude Sonnet 5.5 cb9f5eecc4 release: v0.7.11 - sanitize CivitAI description HTML (stored XSS), harden sidecar import
- util.js: allowlist sanitizeHtml() / safeHttpUrl() (absolute http(s) only);
  applied to the Models detail panel description, model URL and sample images
- cm-info/metadata sidecar import: numeric IDs only, type checks, 2MB size cap
- DEVLOG, README badge, version bump

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:26:31 +09:00
ketle-manandClaude Sonnet 5.5 3262e843cf release: v0.7.10 - Selector event loop switch, no-hash CivitAI batch, models folder, preview 404 fix
- Windows: optional Selector asyncio loop (settings toggle / WFS_SELECTOR_LOOP=1)
  to avoid ComfyUI freezing in closesocket on the Proactor loop
- Models: skip image requests for models without previews (preview-keys API),
  show previews of .disabled models, add extra Models folder setting
- CivitAI: batch fetch no longer hashes; reads .cm-info.json (Stability Matrix);
  unhashed models shown in red and hashed individually; drop file path display
- Help/i18n for the new settings; DEVLOG, README badge, version bump

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 21:26:31 +09:00
ketle-manandClaude Sonnet 5.5 68836b0166 feat: reuse Lora Manager sha256 to skip hashing in CivitAI batch fetch
Query /api/lm/{loras,checkpoints,embeddings}/list for already-computed
sha256 and use it (size-matched only) for models without a stored hash.
Falls back to the existing hashing path if Lora Manager is unavailable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 12:58:38 +09:00
ketle-manandClaude Sonnet 5.5 7b3d1f0bc3 feat: add Models folder setting and cancel CivitAI batch on disconnect
- Settings: new "Models Folder" (models_dir) to add extra model roots such as
  Stability Matrix's Models; subfolders (StableDiffusion/Lora/VAE/...) are
  merged into the Models tab list and folder resolution
- CivitAI batch: stop hashing/fetching when the client disconnects, keeping
  already computed hashes
- Lower load: hash workers 3->2, read chunk 1MB->512KB, preview download
  workers 4->2

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 10:14:21 +09:00
25 changed files with 928 additions and 150 deletions
+3
View File
@@ -2,6 +2,9 @@
Condensed version-by-version index of DEVLOG.md (each line: version + one-line summary of what changed and why). Full rationale, code details, and "How to apply" lessons live in the excluded DEVLOG.md itself; this index exists so graphify can extract a queryable semantic node per release without feeding the full log to the local Ollama model. Regenerate with `python tools/generate_doc_index.py devlog` whenever DEVLOG.md changes.
- **v0.7.12(2026-10-04)** — セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
- **v0.7.11(2026-10-02)** — セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- **v0.7.10(2026-10-02)** — Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
- **v0.7.9(2026-10-02)** — Models: CivitAIベースモデルからの自動バッジ作成
- **v0.7.8(2026-10-01)** — Video Edit: マルチトラック化(ビデオ/オーバーレイ/テキスト/オーディオ)
- **v0.7.7(2026-09-30)** — 意思決定モデル: Ollama 0.35+ バックエンド追加
+74
View File
@@ -2,6 +2,80 @@
---
## v0.7.12(2026-10-04)
### セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
ComfyUI-Manager登録PR(LiveChatStream、Comfy-Org/ComfyUI-Manager#3340)のレビューで指摘された「リクエストから接続先URLを受け取り、サーバーが接続する」問題が、WFSにも同じ構造で存在していたため修正。
- 対象: `POST /api/wfm/ollama/chat`(bodyの `url`。従来は**検証なし**で、任意ホスト・クラウドメタデータ・`file://` に接続できた)、Tagger VLM(`/wfm/tagger/vlm/models`・`vlm/predict`・`batch/start` の `api_url`。Unslothのみ制限されていた)、Eagle(`/api/wfm/eagle/add`・`/test` の `eagleUrl`)、Unslothプロキシ(`baseUrl`)。
- 新規 `py/services/url_guard.py` に共通化。許可は **loopback(localhost / 127.0.0.1 / ::1、ポート自由)** と、運用者が環境変数 `WFS_ALLOWED_BACKEND_HOSTS`(`host` または `host:port` のカンマ区切り)で指定したホストのみ。`http(s)` 以外(`file://` 等)、URL内の認証情報、`localhost.evil.com` のような偽装ホストは拒否。**リダイレクトは追従しない**(302は接続せずエラー)。
- **挙動変更**: LAN上の別マシンのOllama/Eagle等を使っている場合は `WFS_ALLOWED_BACKEND_HOSTS` の設定が必要(拒否時のエラーメッセージに案内を表示)。
- 実機(ComfyUI_5、ポート8189)で、メタデータIP・`file://`・公開IPの拒否、loopbackのOllama chat/Tagger一覧/Eagle test/Unsloth Decision APIの正常動作を確認。
- 注意: ComfyUIを `--listen` で公開すると、到達できる相手は引き続きこれらのルートを使える(接続先を変えられないだけ)。信頼できるネットワークでのみ使うこと。
---
## v0.7.11(2026-10-02)
### セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- Models詳細パネルのCivitAIタブは、説明文(`description`)をエスケープせずHTMLとして挿入していた。CivitAI APIの応答は従来から同じ扱いだったが、v0.7.10で追加した `.cm-info.json`(Stability Matrix)取り込みにより、**ローカルのサイドカーファイルからも同じ経路で入る**ようになった。細工されたファイルがモデルと一緒に配布された場合、詳細パネルを開いただけでスクリプトが実行され得る(ComfyUIと同一オリジンのため、ComfyUIのAPIを操作できる)。
- `static/js/util.js` に許可リスト方式の `sanitizeHtml()` と `safeHttpUrl()` を追加し、説明文・モデルURL・サンプル画像URLに適用。`script/style/iframe/svg/form` 等の要素、`on*` 属性、`style` 属性、`javascript:`/`data:` URL、**相対URL**(ComfyUI自身のURLへリクエストを送らせる経路)を除去する。許可するのは段落・見出し・リスト・強調・表・`code`・`a`/`img`(絶対http(s) URLのみ)など。
- Playwright(実ブラウザ)で攻撃文字列16種を検証し、スクリプトが一度も実行されないことを確認。
### セキュリティ: サイドカー経由のSSRF/ローカルファイル読み取りと、Hostヘッダ依存の接続先
取り込み経路の再点検で見つかった2件を修正。
- **プレビュー画像のダウンロード(`download_image`)のURLが無検証だった**。URLは `.metadata.json`(Lora Manager形式のローカルサイドカー)の `civitai.images` から来るため、細工されたサイドカーがあると、サーバーが任意のURLへ接続する(SSRF)。`file://` を指定すればローカルファイルを読んでプレビュー画像として保存でき、プレビューAPI経由で取り出せた。**https かつ CivitAI系ホスト(`civitai.com`/`civitai.red`/`civitai.green` とそのサブドメイン)のみ許可**し、リダイレクト先も同じ条件で検証、サイズ上限50MBを設定。正規のCivitAI画像の取得は実環境で確認済み。
- **Lora Manager連携(`lora_manager_bridge`)の接続先を、リクエストのHostヘッダから組み立てていた**。Hostの偽装(DNSリバインディング等)で任意のホストへ接続させられるため、**ループバック(`127.0.0.1`)+実際に待ち受けているポート**に固定。
- サンプル画像・フォールバック画像のURLにも `safeHttpUrl()`(絶対http(s)のみ)を適用。
### `.cm-info.json` / `.metadata.json` 取り込みの堅牢化
- `ModelId`/`VersionId` は正の整数のみ受け付ける(URLに文字列を埋め込まない)。不正なら情報は採用せず、sha256のみ利用。
- タグ・トリガーワードは文字列/数値のみ・件数上限あり。JSONのトップレベルがオブジェクトでない場合は無視。
- サイドカーJSONのサイズ上限を2MBに設定(巨大ファイルでメモリを使い切らない)。
---
## v0.7.10(2026-10-02)
### Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
v0.7.9で「原因未特定」としていたComfyUIの無応答は、ほぼ素の環境(ComfyUI 0.34 / Workflow Studio 0.7.2〜0.7.9、ComfyUI Desktop・Stability Matrix両方)でも再現し、`/system_stats` すら応答しなかった。py-spy(`dump --native`)でメインスレッド(イベントループ)が `asyncio proactor _call_connection_lost → socket.close → closesocket → NtClose` で停止していることを確認。ハッシュ計算・モデルファイル・CivitAI取得・Windows更新(26H2を戻しても再現)・ComfyUI/WSL/Windows Firewall Controlのいずれも原因ではなかった。
- きっかけは「プレビュー画像の多い一覧を開き、続けて他の一覧へ切り替える」操作。ブラウザが読み込み中の画像リクエストを一斉に中止し、短時間に多数の接続が開閉する。
- **対策**: `prestartup_script.py` でWindowsのasyncioループをProactorからSelectorへ切り替えるスイッチを追加(既定オフ)。設定画面の「Windowsの安定性(イベントループ)」のチェック、または環境変数 `WFS_SELECTOR_LOOP=1` で有効化(ComfyUI再起動後に反映)。有効化すると同じ操作で再現しなくなった。
- トレードオフ: asyncioのサブプロセス機能が使えない/同時接続数の上限が約512。ComfyUI-Managerの閲覧・CivitAI取得は問題なし。
- 固まったプロセスは `taskkill` しても終了せずポートを握り続けるため、再起動が必要になる。固まったときは `py-spy dump --native --pid <PID>` でメインスレッドの位置を確認する。
### Models: プレビュー画像の404削減
- プレビューが無いモデルにも画像リクエストを出しており、一覧の切り替えごとに大量の404と接続の開閉が発生していた。
- 新API `GET /api/wfm/models/preview-keys?type=` がフォルダを1回走査して「プレビューを持つモデル」の一覧を返し、画面側は無いモデルへ画像リクエストを出さない(取得失敗時は従来動作)。サムネ変更・CivitAI取得でのプレビュー保存・一括取得後は一覧を更新。
- **無効化(`.disabled`)されたモデルのプレビューが表示されなかった問題を修正**(`find_preview_image` が `<名前>.disabled` を見ていなかった)。
### Models: モデルフォルダ設定(Stability Matrix対応)
- 設定に「モデルフォルダ」を追加。追加のモデルルート(例: Stability Matrixの `Models`、`;` 区切りで複数可)直下の `StableDiffusion/Lora/VAE/ControlNet/TextEncoders/DiffusionModels/Embeddings/HyperNetworks`(またはComfyUI名 `checkpoints/loras` …)をModelsタブの一覧とフォルダ解決に追加する。
- Modelsタブの一覧はComfyUIの `/object_info` 由来で追加フォルダを含まないため、`/api/wfm/models/files?extra_only=1` の結果を合流させている。
### CivitAI取得: ハッシュ計算を行わない運用へ
- 一括取得は**ハッシュ計算をしない**。保存済みsha256、`.metadata.json`(Lora Manager)、`.cm-info.json`(Stability Matrix)、Lora Managerの `/api/lm/{loras,checkpoints,embeddings}/list` のsha256から解決できる分だけを取得し、未確定のモデルは「ハッシュ未計算」として件数を表示する(大きなモデルを多数ハッシュするとディスクが飽和するため)。
- **`.cm-info.json` 取り込み**: `Hashes.SHA256` とCivitAI情報を読む。ファイルサイズが無いため `ImportedAt` より後にモデルが更新されていたら不採用。画像一覧を持たないので `source: "cm-info"` を付け、個別の取得/更新でAPIの完全な情報に置き換える。
- 詳細パネルのCivitAIタブで、ハッシュ未計算のモデルは赤字「未計算」を表示。取得/更新ボタンでハッシュ計算して取得する(ファイルサイズ/更新日時も保存)。
- クライアント切断(再読み込み・タブ遷移)で一括取得を中断し、計算済みのハッシュだけ保存して終了。ハッシュ計算を3→2並列、読み込み1MB→512KB、プレビュー保存4→2並列に抑制。
- 詳細パネルの「ファイルパス」表示を削除。
### ヘルプ・i18n
- 設定のヘルプに「モデルフォルダ」「Windowsの安定性」を追加(英日中)。
---
## v0.7.9(2026-10-02)
### Models: CivitAIベースモデルからの自動バッジ作成
+5 -1
View File
@@ -26,7 +26,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.9-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Features (tab -> feature names)
@@ -162,6 +162,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+5 -1
View File
@@ -22,7 +22,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.9-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Screenshots
@@ -584,6 +584,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+45
View File
@@ -11,6 +11,51 @@ from pathlib import Path
PLUGIN_DIR = Path(__file__).resolve().parent
ENV_FILE = PLUGIN_DIR / ".env"
def _maybe_use_selector_event_loop():
"""Windows: ProactorEventLoop(IOCP) を SelectorEventLoop に切り替える(既定はオフ)。
環境によっては、ソケットclose(closesocket/NtClose)でイベントループがOSカーネル内で停止し、
ComfyUI全体が無応答になる(再起動するまでポートも解放されない)。Selector方式はIOCPを使わず、
この停止を避けられる可能性がある。副作用: asyncioのサブプロセス機能が使えない、
同時接続数の上限(約512)がある。
有効化: 環境変数 WFS_SELECTOR_LOOP=1、または
user/default/Workflow-Studio/settings.json に "windows_selector_event_loop": true
ComfyUIがイベントループを作成する前に呼ぶ必要があるため、ここ(prestartup)で設定する。
"""
import os
import sys
if sys.platform != "win32":
return
enabled = os.environ.get("WFS_SELECTOR_LOOP", "").strip().lower() in ("1", "true", "yes")
if not enabled:
try:
import json
candidates = [
PLUGIN_DIR.parent.parent / "user" / "default" / "Workflow-Studio" / "settings.json",
PLUGIN_DIR / "data" / "settings.json", # config.py fallback when user/default is absent
]
for settings in candidates:
if settings.is_file():
with open(settings, "r", encoding="utf-8") as f:
enabled = bool(json.load(f).get("windows_selector_event_loop", False))
break
except Exception:
enabled = False
if not enabled:
return
try:
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
print("[Workflow Studio] Using WindowsSelectorEventLoopPolicy (windows_selector_event_loop enabled)")
except Exception as e:
print(f"[WARNING] Workflow Studio: failed to switch to selector event loop: {e}")
_maybe_use_selector_event_loop()
if ENV_FILE.exists():
try:
from dotenv import load_dotenv
+7 -5
View File
@@ -9,6 +9,8 @@ import urllib.error
from aiohttp import web
from ..services.url_guard import require_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
@@ -92,7 +94,7 @@ def _eagle_add_from_path(eagle_url, file_path, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -127,7 +129,7 @@ def _eagle_add(eagle_url, image_url, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -138,7 +140,7 @@ def _eagle_test(eagle_url):
f"{eagle_url}/api/application/info",
method="GET",
)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -146,7 +148,7 @@ async def handle_add(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/add - Add image to Eagle."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
image_url = body.get("url", "")
name = body.get("name", "image.png")
tags = body.get("tags", [])
@@ -193,7 +195,7 @@ async def handle_test(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/test - Test Eagle connection."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
result = await asyncio.to_thread(_eagle_test, eagle_url)
return web.json_response({
"status": "success",
+72 -17
View File
@@ -20,6 +20,7 @@ def setup_routes(app: web.Application):
app.router.add_get("/api/wfm/models/metadata", handle_get_metadata)
app.router.add_post("/api/wfm/models/metadata", handle_save_metadata)
app.router.add_get("/api/wfm/models/preview", handle_get_preview)
app.router.add_get("/api/wfm/models/preview-keys", handle_get_preview_keys)
app.router.add_get("/api/wfm/models/groups", handle_get_groups)
app.router.add_post("/api/wfm/models/groups", handle_save_groups)
app.router.add_post("/api/wfm/models/civitai/fetch", handle_civitai_fetch)
@@ -139,10 +140,13 @@ async def handle_civitai_fetch(request: web.Request) -> web.Response:
)
if not sha256:
return web.json_response({"error": "Failed to calculate hash"}, status=500)
# Cache the hash in model metadata
await asyncio.to_thread(
_service.update_metadata, model_name, {"sha256": sha256}
)
# Cache the hash (+ size/mtime so a replaced file invalidates it) in model metadata
try:
st = file_path.stat()
hash_meta = {"sha256": sha256, "sha256Size": st.st_size, "sha256Mtime": st.st_mtime}
except OSError:
hash_meta = {"sha256": sha256}
await asyncio.to_thread(_service.update_metadata, model_name, hash_meta)
# Fetch from CivitAI
info = await asyncio.to_thread(_civitai.fetch_by_hash, sha256)
@@ -260,6 +264,24 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
if m.get("sha256"):
known[n] = {"sha256": m["sha256"], "size": m.get("sha256Size"), "mtime": m.get("sha256Mtime")}
# 未計算のものは Lora Manager が保持済みのsha256を借りる(サイズ一致時のみ。ハッシュ計算を省く)
if len(known) < len(model_files):
from ..services.lora_manager_bridge import fetch_lm_hashes, _norm
# Hostヘッダは信用せず、自分自身のループバック+実際のポートへ接続する(Host偽装/DNSリバインディング対策)
sockname = request.transport.get_extra_info("sockname") if request.transport else None
port = sockname[1] if sockname else (request.url.port or 8188)
origin = f"http://127.0.0.1:{port}"
lm = await asyncio.to_thread(fetch_lm_hashes, origin, model_type)
for n, p in model_files:
if n in known:
continue
e = lm.get(_norm(p))
try:
if e and e.get("size") is not None and int(e["size"]) == p.stat().st_size:
known[n] = {"sha256": e["sha256"], "size": int(e["size"]), "mtime": None}
except OSError:
pass
# ハッシュ確定ごとに溜め、5秒おきにメタデータへ書き出す(途中で止めても計算済み分が残る)
pending_hashes = {}
last_flush = [_time.monotonic()]
@@ -286,29 +308,44 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
flush_hashes()
# Start batch in background thread
import threading
cancel = threading.Event()
loop = asyncio.get_event_loop()
fetch_task = loop.run_in_executor(
None, lambda: _civitai.batch_fetch(model_files, on_progress, known, on_hash)
None, lambda: _civitai.batch_fetch(model_files, on_progress, known, on_hash, cancel=cancel)
)
# Stream progress events
while not fetch_task.done():
# Drain queue
try:
while not fetch_task.done():
# Drain queue
while not progress_q.empty():
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.sleep(0.1)
# Drain remaining events
while not progress_q.empty():
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.sleep(0.1)
# Drain remaining events
while not progress_q.empty():
except (ConnectionResetError, asyncio.CancelledError) as e:
# クライアント切断(再読み込み・タブ遷移): 重いハッシュ計算を打ち切り、計算済み分だけ保存して終了
logger.info("civitai batch: client disconnected, cancelling (%s)", type(e).__name__)
cancel.set()
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.shield(fetch_task)
except Exception:
pass
await asyncio.to_thread(flush_hashes)
if isinstance(e, asyncio.CancelledError):
raise
return response
# Get results and update metadata
try:
@@ -363,7 +400,7 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
if not jobs:
return 0
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as pool:
with ThreadPoolExecutor(max_workers=2) as pool:
oks = list(pool.map(lambda j: CivitaiService.download_image(j[1], j[2]), jobs))
for (mname, _u, _p), ok in zip(jobs, oks):
if ok:
@@ -378,6 +415,7 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
"found": sum(1 for r in results.values() if r.get("civitai")),
"not_found": sum(1 for r in results.values() if r.get("sha256") and not r.get("civitai")),
"errors": sum(1 for r in results.values() if r.get("error")),
"needs_hash": sum(1 for r in results.values() if r.get("needs_hash")),
"hashes": {name: r.get("sha256") for name, r in results.items() if r.get("sha256")},
"preview_saved": preview_saved_count,
}
@@ -389,6 +427,22 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
# ── Model Preview Image ───────────────────────────────────
async def handle_get_preview_keys(request: web.Request) -> web.Response:
"""GET /api/wfm/models/preview-keys?type=checkpoint
プレビュー画像を持つモデルのキー一覧を返す(無いモデルへの画像リクエスト=404を避けるため)。
"""
model_type = request.query.get("type", "")
if not model_type:
return web.json_response({"error": "type required"}, status=400)
try:
keys = await asyncio.to_thread(_service.list_preview_keys, model_type)
return web.json_response({"keys": keys})
except Exception as e:
logger.error("Error listing preview keys: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_preview(request: web.Request) -> web.Response:
"""GET /api/wfm/models/preview?type=checkpoint&name=model.safetensors"""
model_type = request.query.get("type", "")
@@ -696,7 +750,8 @@ async def handle_list_model_files(request: web.Request) -> web.Response:
if not model_type or model_type not in MODEL_TYPE_FOLDER_KEYS:
return web.json_response({"error": "invalid type"}, status=400)
try:
result = await asyncio.to_thread(_service.list_model_files, model_type)
extra_only = request.query.get("extra_only") == "1"
result = await asyncio.to_thread(_service.list_model_files, model_type, extra_only)
return web.json_response(result)
except Exception as e:
logger.error("Error listing model files for %s: %s", model_type, e)
+9 -6
View File
@@ -7,6 +7,7 @@ import urllib.request
from aiohttp import web
from ..services.settings_service import SettingsService
from ..services.url_guard import require_backend_url, urlopen
logger = logging.getLogger(__name__)
@@ -39,11 +40,12 @@ async def handle_models(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _fetch():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
@@ -61,11 +63,12 @@ async def handle_test(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _test():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return resp.status == 200
ok = await asyncio.to_thread(_test)
@@ -83,7 +86,7 @@ async def handle_chat(request: web.Request) -> web.Response:
body = await request.json()
cfg = _get_ollama_config()
model = body.get("model") or cfg["model"]
base_url = (body.get("url") or cfg["url"]).rstrip("/")
base_url = require_backend_url(body.get("url") or cfg["url"])
messages = body.get("messages", [])
def _chat():
@@ -100,7 +103,7 @@ async def handle_chat(request: web.Request) -> web.Response:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
with urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
resp_data = await asyncio.to_thread(_chat)
+43
View File
@@ -38,6 +38,8 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/settings", handle_post)
app.router.add_get("/api/wfm/settings/workflows-dir", handle_get_workflows_dir)
app.router.add_post("/api/wfm/settings/workflows-dir", handle_set_workflows_dir)
app.router.add_get("/api/wfm/settings/models-dir", handle_get_models_dir)
app.router.add_post("/api/wfm/settings/models-dir", handle_set_models_dir)
app.router.add_get("/api/wfm/settings/output-dir", handle_get_output_dir)
app.router.add_post("/api/wfm/settings/output-dir", handle_set_output_dir)
app.router.add_get("/api/wfm/settings/export", handle_export)
@@ -122,6 +124,47 @@ async def handle_set_workflows_dir(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def handle_get_models_dir(request: web.Request) -> web.Response:
"""GET /api/wfm/settings/models-dir - 追加モデルフォルダ設定と現在有効な探索先を返す。"""
try:
from ..services.models_service import (
MODEL_TYPE_FOLDER_KEYS, _get_model_dirs, parse_extra_model_roots,
)
saved = (await asyncio.to_thread(_service.load)).get("models_dir", "")
effective = await asyncio.to_thread(
lambda: {t: [str(d) for d in _get_model_dirs(t)] for t in MODEL_TYPE_FOLDER_KEYS}
)
return web.json_response({
"saved": saved,
"roots": parse_extra_model_roots(saved),
"effective": effective,
})
except Exception as e:
logger.error("Error getting models dir: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_set_models_dir(request: web.Request) -> web.Response:
"""POST /api/wfm/settings/models-dir - 追加モデルフォルダを保存(`;`/改行区切りで複数可、空でリセット)。"""
try:
from ..services.models_service import parse_extra_model_roots
body = await request.json()
roots = parse_extra_model_roots(body.get("models_dir", ""))
missing = [r for r in roots if not Path(r).is_dir()]
if missing:
return web.json_response(
{"error": f"Folder not found: {', '.join(missing)}"}, status=400)
saved = ";".join(roots)
await asyncio.to_thread(_service.update, {"models_dir": saved})
from ..routes.models_routes import _service as models_service
models_service._scan_cache.clear()
return await handle_get_models_dir(request)
except Exception as e:
logger.error("Error setting models dir: %s", e)
return web.json_response({"error": str(e)}, status=500)
def _get_comfyui_output_dir() -> str:
"""ComfyUIのデフォルトoutputフォルダを取得する。"""
try:
+8 -19
View File
@@ -19,19 +19,19 @@ import logging
import os
import urllib.request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from aiohttp import web
from ..services.url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
UNSLOTH_DEFAULT_URL = "http://localhost:8888"
_ALLOWED_PATHS = {"/v1/models", "/v1/chat/completions", "/v1/systemone"}
# baseUrl is client-supplied (so a custom Unsloth port works), but the
# Authorization header carries a real secret — restrict the host to loopback
# so this proxy can't be used to exfiltrate UNSLOTH_API_KEY to an arbitrary
# server (SSRF). Port is unrestricted.
_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
# Authorization header carries a real secret — restrict the host (loopback, or
# WFS_ALLOWED_BACKEND_HOSTS set by the operator) so this proxy can't be used to
# exfiltrate UNSLOTH_API_KEY to an arbitrary server (SSRF). Redirects are not followed.
def _get_api_key():
@@ -47,15 +47,6 @@ KEYLESS_REJECTED_MESSAGE = (
)
def _is_allowed_base_url(base_url):
"""Only relay (and attach the API key) to a loopback host."""
try:
parsed = urlparse(base_url)
return parsed.scheme in ("http", "https") and parsed.hostname in _ALLOWED_HOSTS
except Exception:
return False
def setup_routes(app: web.Application):
"""Register Unsloth API routes."""
app.router.add_post("/api/wfm/unsloth/proxy", handle_proxy)
@@ -78,10 +69,8 @@ async def handle_proxy(request: web.Request) -> web.Response:
if path not in _ALLOWED_PATHS or method not in ("GET", "POST"):
return web.json_response({"message": "Unsupported proxy target"}, status=400)
if not _is_allowed_base_url(base_url):
return web.json_response({
"message": "Unsloth backend URL must point to localhost/127.0.0.1/::1",
}, status=400)
if not is_allowed_backend_url(base_url):
return web.json_response({"message": _URL_HINT}, status=400)
# No key → relay without Authorization (Unsloth's Keyless API access); if Unsloth
# still demands one, the 401 below explains both ways to fix it.
@@ -93,7 +82,7 @@ async def handle_proxy(request: web.Request) -> web.Response:
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base_url}{path}", data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=120) as resp:
with _guarded_urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
+182 -10
View File
@@ -56,6 +56,38 @@ _MAX_RETRIES = 3
_BATCH_CHUNK_SIZE = 100
# サイドカーJSON(.metadata.json / .cm-info.json)の最大サイズ。巨大ファイルでメモリを使い切らないための上限
_SIDECAR_MAX_BYTES = 2 * 1024 * 1024
def _as_int(v):
"""数値IDだけを受け付ける(文字列に細工されたIDをURL等に埋め込まないため)。不正ならNone。"""
try:
if isinstance(v, bool):
return None
n = int(v)
return n if n > 0 else None
except (TypeError, ValueError):
return None
# プレビュー画像のダウンロード許可ホスト(サイドカーJSON由来のURLでSSRF/ローカルファイル読み取りをさせない)
_IMAGE_HOST_SUFFIXES = (".civitai.com", ".civitai.red", ".civitai.green")
_IMAGE_HOST_EXACT = ("civitai.com", "civitai.red", "civitai.green")
_IMAGE_MAX_BYTES = 50 * 1024 * 1024
def _is_allowed_image_url(url):
"""https かつ CivitAI 系ホストのURLだけ許可する(file:// や内部アドレス、他ホストは拒否)。"""
try:
from urllib.parse import urlparse
u = urlparse(str(url).strip())
host = (u.hostname or "").lower()
return u.scheme == "https" and (host in _IMAGE_HOST_EXACT or host.endswith(_IMAGE_HOST_SUFFIXES))
except Exception:
return False
class CivitaiService:
"""Fetch and cache CivitAI model metadata."""
@@ -117,14 +149,16 @@ class CivitaiService:
# ── ハッシュ計算 ──────────────────────────────────────────
@staticmethod
def calculate_sha256(file_path, chunk_size=1024 * 1024):
"""Calculate SHA256 hash of a file."""
def calculate_sha256(file_path, chunk_size=512 * 1024, cancel=None):
"""Calculate SHA256 hash of a file. cancel(threading.Event)がセットされたらNoneを返して中断。"""
h = hashlib.sha256()
path = Path(file_path)
if not path.is_file():
return None
with open(path, "rb") as f:
while True:
if cancel is not None and cancel.is_set():
return None
chunk = f.read(chunk_size)
if not chunk:
break
@@ -142,8 +176,11 @@ class CivitaiService:
"""
sha256_lower = sha256_hash.lower()
cache = self._load_cache()
if sha256_lower in cache:
return cache[sha256_lower]
cached = cache.get(sha256_lower)
# Stability Matrix(.cm-info.json)由来の簡易情報は画像一覧を持たないため、
# 明示的な取得/更新ではAPIから完全な情報で上書きする
if cached is not None and cached.get("source") != "cm-info":
return cached
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash.upper()}"
@@ -364,15 +401,112 @@ class CivitaiService:
return str(sha).lower()
def _read_sidecar(self, file_path, size):
"""`<stem>.metadata.json` サイドカーからsha256とCivitAI情報を読む(ハッシュ計算・通信不要)。
"""サイドカーからsha256とCivitAI情報を読む(ハッシュ計算・通信不要)。
Lora Manager の `<stem>.metadata.json` → Stability Matrix の `<stem>.cm-info.json` の順に試す。
Returns: (sha256_lower or None, extracted_info or None)
"""
sha, info = self._read_lm_sidecar(file_path, size)
if sha:
return sha, info
return self._read_cm_info(file_path)
@staticmethod
def _parse_iso_ts(value):
"""ISO8601文字列→epoch秒。.NETの7桁小数秒にも対応。失敗時はNone。"""
try:
import re
from datetime import datetime
s = str(value).replace("Z", "+00:00")
s = re.sub(r"(\.\d{6})\d+", r"\1", s)
return datetime.fromisoformat(s).timestamp()
except Exception:
return None
def _read_cm_info(self, file_path):
"""Stability Matrix の `<stem>.cm-info.json` から sha256 とCivitAI簡易情報を読む。
ファイルサイズ情報が無いため、ImportedAt より後にモデルファイルが更新されていたら不採用。
画像一覧は持たないので info には "source": "cm-info" を付け、個別取得で完全情報に置き換えられる。
"""
sc = file_path.with_name(file_path.stem + ".cm-info.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES: # 巨大ファイルによるメモリ消費を避ける
return None, None
with open(sc, "r", encoding="utf-8-sig") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str((d.get("Hashes") or {}).get("SHA256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
imported = self._parse_iso_ts(d.get("ImportedAt"))
if imported is None or file_path.stat().st_mtime > imported + 2:
return None, None
except Exception:
return None, None
info = None
try:
if d.get("Source", 0) == 0 and _as_int(d.get("VersionId")): # 0 = Civitai
info = self._info_from_cm_info(d)
except Exception:
info = None
return sha, info
@staticmethod
def _info_from_cm_info(d):
"""cm-info.json を _extract_info と同じ形式のdictに変換する。"""
model_id, version_id = _as_int(d.get("ModelId")), _as_int(d.get("VersionId"))
stats = d.get("Stats") or {}
return {
"versionId": version_id,
"modelId": model_id,
"modelName": d.get("ModelName", ""),
"versionName": d.get("VersionName", ""),
"type": d.get("ModelType", ""),
"description": d.get("VersionDescription") or d.get("ModelDescription", ""),
"tags": [str(x) for x in (d.get("Tags") or []) if isinstance(x, (str, int, float))][:100],
"nsfw": bool(d.get("Nsfw", False)),
"nsfwLevel": 0,
"air": "",
"creator": d.get("AuthorUsername") or "",
"images": [],
"imageDetails": [],
"trainedWords": [str(x) for x in (d.get("TrainedWords") or []) if isinstance(x, (str, int, float))][:200],
"baseModel": d.get("BaseModel") or "",
"fileSize": 0,
"fileMeta": d.get("FileMetadata") or {},
"fileHashes": d.get("Hashes") or {},
"downloadUrl": "",
"modelUrl": (
f"https://civitai.com/models/{model_id}?modelVersionId={version_id}"
if model_id else f"https://civitai.com/model-versions/{version_id}"
),
"stats": {
"downloadCount": stats.get("downloadCount", 0),
"thumbsUpCount": stats.get("thumbsUpCount", 0),
"thumbsDownCount": stats.get("thumbsDownCount", 0),
},
"updatedAt": "",
"publishedAt": "",
"source": "cm-info",
}
def _read_lm_sidecar(self, file_path, size):
"""`<stem>.metadata.json` (Lora Manager) サイドカーからsha256とCivitAI情報を読む。
サイドカーのsizeがファイルサイズと一致する場合のみ採用する。
Returns: (sha256_lower or None, extracted_info or None)
"""
sc = file_path.with_name(file_path.stem + ".metadata.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES:
return None, None
with open(sc, "r", encoding="utf-8") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str(d.get("sha256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
@@ -396,11 +530,12 @@ class CivitaiService:
info = None
return sha, info
def batch_fetch(self, model_files, progress_callback=None, known=None, on_hash=None, workers=3):
def batch_fetch(self, model_files, progress_callback=None, known=None, on_hash=None, workers=2, cancel=None, hash_missing=False):
"""Batch fetch CivitAI info for multiple model files.
Phase 0: 保存済みsha256 / サイドカーから解決(ハッシュ計算・通信なし)
Phase 1: 残りのSHA256を並列計算("hashing")
Phase 1: 残りのSHA256を並列計算("hashing")— hash_missing=True のときのみ。
既定では計算せず needs_hash を返す
Phase 2: POST で一括取得("fetching")— キャッシュ済みはスキップ
Args:
@@ -409,6 +544,7 @@ class CivitaiService:
known: { model_name: {"sha256", "size", "mtime"} } メタデータ保存済みハッシュ
on_hash: fn(model_name, sha256, size, mtime) ハッシュが新たに確定するたびに呼ばれる
workers: ハッシュ計算の並列数
cancel: threading.Event。セットされると未処理分を打ち切って戻る(クライアント切断時)
Returns: dict of { model_name: { sha256, civitai_info_or_none } }
"""
@@ -465,16 +601,32 @@ class CivitaiService:
if cache_dirty:
self._save_cache()
logger.info("CivitAI batch: total=%d resolved_without_hash=%d need_hash=%d hash_missing=%s",
total, len(results), len(to_hash), hash_missing)
# ハッシュ未確定のものは、hash_missing=False(既定)なら計算せず "needs_hash" として返す
# (個別取得でハッシュ計算する運用。全件ハッシュ計算は負荷が高いため行わない)
if to_hash and not hash_missing:
for model_name, _fp, _st in to_hash:
results[model_name] = {"sha256": None, "civitai": None, "needs_hash": True}
finished += 1
if progress_callback:
progress_callback(finished, total, model_name, "needs_hash")
to_hash = []
# Phase 1: 残りを並列でハッシュ計算(hashlibは大きなチャンクでGILを解放する)
if to_hash:
from concurrent.futures import ThreadPoolExecutor, as_completed
def _hash(item):
return self.calculate_sha256(item[1])
return self.calculate_sha256(item[1], cancel=cancel)
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = {pool.submit(_hash, item): item for item in to_hash}
for fut in as_completed(futures):
if cancel is not None and cancel.is_set():
for f in futures:
f.cancel()
break
model_name, _fp, st = futures[fut]
try:
sha = fut.result()
@@ -490,6 +642,9 @@ class CivitaiService:
progress_callback(finished, total, model_name, "hashing")
_resolved(model_name, sha.lower(), st, new_hash=True)
if cancel is not None and cancel.is_set():
return results
# Phase 2: POST で一括取得(未キャッシュ分)
if hashes_needed:
if progress_callback:
@@ -500,7 +655,9 @@ class CivitaiService:
for name, sha256_lower in hashes_needed:
sha256_to_names.setdefault(sha256_lower, []).append(name)
logger.info("CivitAI batch: POST %d hashes", len(sha256_to_names))
batch_results = self._batch_fetch_post(list(sha256_to_names.keys()))
logger.info("CivitAI batch: POST done")
failed = getattr(self, "last_failed_hashes", set())
for sha256_lower, info in batch_results.items():
@@ -523,10 +680,25 @@ class CivitaiService:
@staticmethod
def download_image(url, save_path, timeout=15):
"""Download an image from URL and save to save_path. Returns True on success."""
if not _is_allowed_image_url(url):
logger.warning("Refusing to download preview from non-CivitAI URL: %s", str(url)[:120])
return False
try:
from urllib.request import HTTPRedirectHandler, HTTPSHandler, build_opener
class _SafeRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
if not _is_allowed_image_url(newurl): # リダイレクト先も検証
raise ValueError("redirect to disallowed host")
return super().redirect_request(req, fp, code, msg, headers, newurl)
opener = build_opener(_SafeRedirect, HTTPSHandler(context=_get_ssl_context()))
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=timeout, context=_get_ssl_context()) as resp:
data = resp.read()
with opener.open(req, timeout=timeout) as resp:
data = resp.read(_IMAGE_MAX_BYTES + 1)
if len(data) > _IMAGE_MAX_BYTES:
logger.warning("Preview too large, skipped: %s", str(url)[:120])
return False
with open(save_path, "wb") as f:
f.write(data)
return True
+48
View File
@@ -0,0 +1,48 @@
"""ComfyUI-Lora-Manager 連携: LMが保持済みのsha256を再利用してハッシュ計算を省く。
LMの `/api/lm/{prefix}/list` は sha256 / file_path / file_size を返す(CivitAI詳細は薄いので
情報そのものは使わず、重いハッシュ計算の省略にのみ利用する)。LM未導入・失敗時は空を返す。
"""
import json
import logging
import os
from urllib.request import urlopen
logger = logging.getLogger(__name__)
# 当アプリのモデルタイプ → LMのルート接頭辞
_LM_PREFIX = {"checkpoint": "checkpoints", "lora": "loras", "embedding": "embeddings"}
_PAGE_SIZE = 100 # LM側の上限
_MAX_PAGES = 200
_TIMEOUT = 5
def _norm(path):
return os.path.normcase(os.path.abspath(path))
def fetch_lm_hashes(origin, model_type):
"""Returns { normalized_file_path: {"sha256", "size"} }。LMが使えなければ {}。"""
prefix = _LM_PREFIX.get(model_type)
if not prefix:
return {}
out = {}
try:
page = 1
while page <= _MAX_PAGES:
url = f"{origin}/api/lm/{prefix}/list?page={page}&page_size={_PAGE_SIZE}"
with urlopen(url, timeout=_TIMEOUT) as resp:
data = json.loads(resp.read().decode("utf-8"))
for it in data.get("items", []):
sha, fp = it.get("sha256"), it.get("file_path")
if sha and fp and len(str(sha)) == 64:
out[_norm(fp)] = {"sha256": str(sha).lower(), "size": it.get("file_size")}
if page >= int(data.get("total_pages", 1) or 1):
break
page += 1
except Exception as e:
logger.info("Lora Manager hashes unavailable (%s): %s", prefix, e)
return {}
return out
+98 -13
View File
@@ -79,32 +79,89 @@ def _is_within(path, root):
return False
# 追加モデルルート配下で探すサブフォルダ名(大小無視)。ComfyUI標準名 + Stability Matrix名
_EXTRA_ROOT_SUBDIRS = {
"checkpoint": ["checkpoints", "StableDiffusion"],
"lora": ["loras", "Lora"],
"vae": ["vae", "VAE"],
"controlnet": ["controlnet", "ControlNet"],
"unet": ["diffusion_models", "DiffusionModels", "unet"],
"textencoder": ["text_encoders", "TextEncoders", "clip"],
"hypernetwork": ["hypernetworks", "HyperNetworks"],
"embedding": ["embeddings", "Embeddings"],
}
def parse_extra_model_roots(value):
"""設定値(`;` または改行区切りの文字列)を重複なしのパス文字列リストにする。"""
if isinstance(value, (list, tuple)):
value = ";".join(str(v) for v in value)
parts = str(value or "").replace("\n", ";").split(";")
seen, out = set(), []
for p in parts:
p = p.strip().strip('"')
if p and p not in seen:
seen.add(p)
out.append(p)
return out
def _get_extra_model_dirs(model_type):
"""設定 `models_dir` で追加指定されたルート配下の、該当タイプのフォルダを返す。"""
names = _EXTRA_ROOT_SUBDIRS.get(model_type)
if not names:
return []
try:
from .settings_service import SettingsService
roots = parse_extra_model_roots(SettingsService().load().get("models_dir", ""))
except Exception:
return []
wanted = {n.lower() for n in names}
found = []
for root in roots:
try:
for e in os.scandir(root):
if e.is_dir() and e.name.lower() in wanted:
found.append(Path(e.path))
except OSError:
logger.warning("Configured models_dir not accessible: %s", root)
return found
def _get_model_dirs(model_type):
"""Get all model directories for a type using ComfyUI's folder_paths.
Returns a list of Path objects for all configured model directories
(includes extra_model_paths.yaml settings).
(includes extra_model_paths.yaml settings and the `models_dir` setting).
Falls back to plugin-relative path if folder_paths is unavailable.
"""
folder_key = MODEL_TYPE_FOLDER_KEYS.get(model_type)
if not folder_key:
return []
result = []
try:
import folder_paths # type: ignore # ComfyUI module
paths = folder_paths.get_folder_paths(folder_key)
result = [Path(p) for p in paths if Path(p).is_dir()]
if result:
return result
except Exception as e:
logger.debug("folder_paths unavailable (%s), using fallback", e)
# Fallback: custom_nodes/../../models/{folder_key}
plugin_dir = Path(__file__).resolve().parent.parent.parent
models_dir = plugin_dir.parent.parent / "models" / folder_key
if models_dir.is_dir():
return [models_dir]
return []
if not result:
# Fallback: custom_nodes/../../models/{folder_key}
plugin_dir = Path(__file__).resolve().parent.parent.parent
models_dir = plugin_dir.parent.parent / "models" / folder_key
if models_dir.is_dir():
result = [models_dir]
# 設定で追加されたルート(既存と同一実体は除外)
known = {os.path.normcase(os.path.realpath(p)) for p in result}
for d in _get_extra_model_dirs(model_type):
key = os.path.normcase(os.path.realpath(d))
if key not in known:
known.add(key)
result.append(d)
return result
class ModelsService:
@@ -187,10 +244,11 @@ class ModelsService:
self._scan_cache[model_type] = (now, names)
return names
def list_model_files(self, model_type: str) -> list:
def list_model_files(self, model_type: str, extra_only: bool = False) -> list:
"""モデルタイプのモデルファイル名をソートして返す(拡張子付き、/区切り)。
プレビュー画像やサイドカーファイルを除外し、モデル拡張子のみを返す。"""
dirs = _get_model_dirs(model_type)
プレビュー画像やサイドカーファイルを除外し、モデル拡張子のみを返す。
extra_only=True なら設定 models_dir で追加されたフォルダのみ対象。"""
dirs = _get_extra_model_dirs(model_type) if extra_only else _get_model_dirs(model_type)
seen = set()
for d in dirs:
if not d.is_dir():
@@ -331,6 +389,32 @@ class ModelsService:
pass
return disabled
def list_preview_keys(self, model_type):
"""プレビュー画像を持つモデルのキー(`サブフォルダ/ファイル名(拡張子なし)`、小文字・/区切り)を返す。
一覧表示で「プレビューが無いモデルには画像リクエストを出さない」ために、フォルダを1回走査して求める
(画像ごとの404リクエストと接続の開閉を避ける)。判定は find_preview_image と同じ拡張子・サイズ条件。
"""
keys = set()
for d in _get_model_dirs(model_type):
if not d.is_dir():
continue
for f in _iter_files(d):
lname = f.name.lower()
exts = [e for e in _PREVIEW_EXTENSIONS if lname.endswith(e)]
if not exts:
continue
try:
if f.stat().st_size < 100:
continue
parent = str(f.parent.relative_to(d)).replace("\\", "/")
except (OSError, ValueError):
continue
prefix = "" if parent == "." else parent.lower() + "/"
for e in exts:
keys.add(prefix + lname[: -len(e)])
return sorted(keys)
def find_preview_image(self, model_type, model_name):
"""Find preview image for a model file.
@@ -351,7 +435,8 @@ class ModelsService:
for type_dir in dirs:
# model_name can include subdirectory (e.g., "subdir/model.safetensors")
model_path = type_dir / model_name
if not model_path.is_file():
# 無効化されたモデル(<name>.disabled)でも、隣のプレビュー画像は探す
if not model_path.is_file() and not (type_dir / (model_name + _DISABLED_SUFFIX)).is_file():
continue
stem = model_path.stem
+13 -23
View File
@@ -13,7 +13,7 @@ import urllib.error
import urllib.request
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from .url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
import numpy as np
from PIL import Image, ImageOps, PngImagePlugin
@@ -22,19 +22,9 @@ logger = logging.getLogger(__name__)
_model_lock = threading.Lock()
# Unsloth requires an Authorization: Bearer <UNSLOTH_API_KEY> header even for
# local access. api_url is client-supplied per request, so without a host
# check a client could point it at an arbitrary server and exfiltrate the key
# (SSRF). Mirrors unsloth_routes.py's _is_allowed_base_url/_ALLOWED_HOSTS.
_UNSLOTH_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
def _is_allowed_unsloth_url(api_url: str) -> bool:
try:
parsed = urlparse(api_url)
return parsed.scheme in ("http", "https") and parsed.hostname in _UNSLOTH_ALLOWED_HOSTS
except Exception:
return False
# api_url is client-supplied per request, so every backend (Ollama / OpenAI-compatible / Unsloth)
# goes through url_guard: loopback or WFS_ALLOWED_BACKEND_HOSTS only, no redirects. This also
# stops the Unsloth API key (Authorization header) from being sent to an arbitrary server.
class TaggerService:
@@ -279,22 +269,22 @@ class TaggerService:
def vlm_models(self, backend: str, api_url: str) -> list:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
logger.error("vlm_models: %s", _URL_HINT)
return []
if backend == "ollama":
req = urllib.request.Request(api_url.rstrip("/") + "/api/tags")
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["name"] for m in data.get("models", []))
headers = {}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
logger.error("vlm_models: Unsloth backend URL must point to localhost/127.0.0.1/::1")
return []
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
req = urllib.request.Request(api_url.rstrip("/") + "/v1/models", headers=headers)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["id"] for m in data.get("data", []))
except Exception as e:
@@ -309,6 +299,8 @@ class TaggerService:
thinking_mode: bool = False, max_tokens: int = 0) -> dict:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
return {"error": _URL_HINT}
if backend == "ollama":
body = {
"model": model,
@@ -326,14 +318,12 @@ class TaggerService:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
content = data.get("message", {}).get("content", "")
else:
headers = {"Content-Type": "application/json"}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
return {"error": "Unsloth backend URL must point to localhost/127.0.0.1/::1"}
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
@@ -354,7 +344,7 @@ class TaggerService:
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
message = data.get("choices", [{}])[0].get("message", {})
content = message.get("content", "")
+68
View File
@@ -0,0 +1,68 @@
"""Outbound URL guard for backend proxies (SSRF mitigation).
Several routes (Ollama chat, Tagger VLM, Eagle, Unsloth relay) connect to a backend whose
address is supplied by the browser. Without a check, any caller that can reach ComfyUI could
make the server connect to an arbitrary host (cloud metadata, LAN services, file://).
Allowed targets:
- loopback hosts (localhost / 127.0.0.1 / ::1), any port
- hosts listed by the operator in the WFS_ALLOWED_BACKEND_HOSTS environment variable
(comma-separated "host" or "host:port"; e.g. "192.168.1.20:11434,gpu-box")
Only http(s) URLs without credentials are accepted, and redirects are never followed.
"""
import os
import urllib.request
from urllib.parse import urlparse
LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
ALLOWED_HOSTS_ENV = "WFS_ALLOWED_BACKEND_HOSTS"
HINT = (
"Backend URL must point to localhost/127.0.0.1/::1. To use another host, list it in the "
f"{ALLOWED_HOSTS_ENV} environment variable (e.g. 192.168.1.20:11434) and restart ComfyUI."
)
def _operator_allowlist():
raw = os.environ.get(ALLOWED_HOSTS_ENV, "")
return {item.strip().lower() for item in raw.split(",") if item.strip()}
def is_allowed_backend_url(url):
"""True if url is an http(s) URL without credentials whose host[:port] is permitted."""
try:
parsed = urlparse((url or "").strip())
if parsed.scheme not in ("http", "https") or not parsed.hostname:
return False
if parsed.username or parsed.password:
return False
host = parsed.hostname.lower()
if host in LOOPBACK_HOSTS:
return True
allow = _operator_allowlist()
return host in allow or (parsed.port is not None and f"{host}:{parsed.port}" in allow)
except Exception:
return False
def require_backend_url(url):
"""Return url stripped of trailing slashes, or raise ValueError(HINT)."""
url = (url or "").strip()
if not is_allowed_backend_url(url):
raise ValueError(HINT)
return url.rstrip("/")
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
_opener = urllib.request.build_opener(_NoRedirect)
def urlopen(req, timeout):
"""urllib urlopen that never follows redirects (a 3xx surfaces as HTTPError)."""
return _opener.open(req, timeout=timeout)
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
version = "0.7.9"
version = "0.7.12"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+1
View File
@@ -557,6 +557,7 @@ function applyI18nToHtml() {
"wfm-help-settings-18": "helpSettings18", "wfm-help-settings-19": "helpSettings19",
"wfm-help-settings-20": "helpSettings20", "wfm-help-settings-21": "helpSettings21",
"wfm-help-settings-22": "helpSettings22",
"wfm-help-settings-23": "helpSettings23", "wfm-help-settings-24": "helpSettings24",
"wfm-help-nodes-1": "helpNodes1", "wfm-help-nodes-2": "helpNodes2",
"wfm-help-nodes-3": "helpNodes3", "wfm-help-nodes-4": "helpNodes4",
"wfm-help-nodes-5": "helpNodes5", "wfm-help-nodes-6": "helpNodes6",
+36 -3
View File
@@ -562,7 +562,8 @@ const LANGUAGES = {
civitaiSavingPreviews: "Saving previews...",
civitaiHashing2: "Hashing...",
civitaiFetching: "Fetching...",
civitaiBatchDone: (found, notFound) => `CivitAI: ${found} found, ${notFound} not found`,
civitaiBatchDone: (found, notFound, needsHash) => `CivitAI: ${found} found, ${notFound} not found` + (needsHash ? `, ${needsHash} need hash (fetch individually)` : ""),
civitaiHashNotCalculated: "Not calculated",
civitaiApiKeySetting: "CivitAI API Key",
civitaiApiKeyHint: "Optional. Enables authenticated access. Obtain at civitai.com → Account Settings → API Keys.",
civitaiApiKeyPlaceholder: "Paste your CivitAI API key here",
@@ -942,6 +943,8 @@ const LANGUAGES = {
helpSettings20: "Default Checkpoint: when \"Force default checkpoint on workflow load\" is on, every checkpoint loader node's model is replaced with the chosen checkpoint whenever a workflow is loaded into GenerateUI (a toast shows when it's applied) — avoids errors or garbled images caused by a model name saved in the workflow that you don't have; Refresh reloads the checkpoint list, Save stores the setting",
helpSettings21: "CivitAI API Key: optional key for authenticated CivitAI access from the Models tab (get it at civitai.com → Account Settings → API Keys); stored in settings.json but left out of the JSON export and Full Backup, and the CIVITAI_API_KEY environment variable takes priority when set",
helpSettings22: "G'MIC-Qt Integration: path to the G'MIC-Qt executable (gmic_qt.exe) used by the Image Edit tab's G'MIC filter (Edit with G'MIC); Save stores it — see the Image Edit help for installing G'MIC-Qt",
helpSettings23: "Models Folder: add extra model root folders (e.g. Stability Matrix's Models) — their subfolders (StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks, or ComfyUI names like checkpoints / loras) are listed in the Models tab in addition to ComfyUI's own folders; separate several roots with ; — Apply saves, Default clears",
helpSettings24: "Windows Stability: \"Use the Selector event loop on Windows\" switches ComfyUI's asyncio loop from Proactor to Selector (applied at the next ComfyUI start). Turn it on if ComfyUI freezes entirely after switching Models lists that load many preview images; the trade-offs are no asyncio subprocess support and a connection limit of about 512. The same switch is available through the WFS_SELECTOR_LOOP=1 environment variable",
helpSettings9: "All sections are collapsible accordion panels",
helpSettings10: "Wildcard Integration: link WFS wildcard dir to ComfyUI-Impact-Pack wildcards (directory junction on Windows / symlink on other OS); existing files migrated automatically",
helpSettings11: "Text Size: one slider (10–28 px) adjusts font size for all prompt and chat textareas at once — Generate UI positive/negative prompts, AI Assistant chat input, Preset positive/negative, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings",
@@ -1220,6 +1223,14 @@ const LANGUAGES = {
workflowsDirChanged: "Workflow folder changed. Refresh the workflow list.",
workflowsDirError: "Folder change error",
workflowsDirBrowseHint: "Enter the full path to the folder containing workflow JSON files.",
modelsDir: "Models Folder",
modelsDirLabel: "Additional Models Folder Path",
modelsDirHint: "Models root folder (e.g. Stability Matrix's Models). Subfolders such as StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks (or ComfyUI names like checkpoints / loras) are added to the Models tab. Separate multiple folders with ;. Empty to reset.",
modelsDirChanged: "Models folder changed. Reload the Models tab.",
selectorLoop: "Windows Stability (Event Loop)",
selectorLoopLabel: "Use the Selector event loop on Windows (restart required)",
selectorLoopHint: "Turn this on if ComfyUI freezes (all tabs stop responding, even generation) after switching Models lists with many previews. Switches the Windows asyncio loop from Proactor to Selector. Takes effect after restarting ComfyUI; asyncio subprocess features are unavailable and the connection limit is about 512. Leave off if you have no problem.",
selectorLoopSaved: "Saved. Restart ComfyUI to apply.",
settingsTitle: "Settings",
langLabel: "UI Language",
summaryLangLabel: "Summary Language",
@@ -2096,7 +2107,8 @@ const LANGUAGES = {
civitaiSavingPreviews: "プレビュー保存中...",
civitaiHashing2: "ハッシュ計算中...",
civitaiFetching: "取得中...",
civitaiBatchDone: (found, notFound) => `CivitAI: ${found}件取得, ${notFound}件未登録`,
civitaiBatchDone: (found, notFound, needsHash) => `CivitAI: ${found}件取得, ${notFound}件未登録` + (needsHash ? `, ${needsHash}件はハッシュ未計算(個別に取得)` : ""),
civitaiHashNotCalculated: "未計算",
civitaiApiKeySetting: "CivitAI APIキー",
civitaiApiKeyHint: "省略可。認証済みアクセスが有効になります。civitai.com → アカウント設定 → API Keys で取得。",
civitaiApiKeyPlaceholder: "CivitAI APIキーを貼り付けてください",
@@ -2476,6 +2488,8 @@ const LANGUAGES = {
helpSettings20: "デフォルトCheckpoint:「ワークフロー読み込み時にデフォルトCheckpointを強制」をオンにすると、GenerateUIへワークフローを読み込むたびに全てのCheckpointローダーノードのモデルが選択したCheckpointに置き換わります(適用時にトーストで通知)。ワークフローに保存された手元に無いモデル名によるエラーや画像の崩れを防げます。「更新」で一覧を再取得、「保存」で設定を保存します",
helpSettings21: "CivitAI APIキー:ModelsタブからCivitAIへ認証付きでアクセスするための任意のキー(civitai.com → Account Settings → API Keys で取得)。settings.jsonに保存されますが、JSONエクスポートとフルバックアップには含まれません。環境変数CIVITAI_API_KEYが設定されている場合はそちらが優先されます",
helpSettings22: "G'MIC-Qt連携:Image EditタブのG'MICフィルター(Edit with G'MIC)が使うG'MIC-Qt実行ファイル(gmic_qt.exe)のパス。「Save」で保存します。G'MIC-Qtのインストール方法はImage Editのヘルプを参照してください",
helpSettings23: "モデルフォルダ:追加のモデルルートフォルダ(例: Stability Matrix の Models)を指定すると、その中のサブフォルダ(StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks、またはcheckpoints / lorasなどComfyUI名)がComfyUI本来のフォルダに加えてModelsタブに表示されます。複数のルートは ; 区切り。「適用」で保存、「デフォルト」でクリア",
helpSettings24: "Windowsの安定性:「WindowsでSelectorイベントループを使用する」をオンにすると、ComfyUIのasyncioループがProactorからSelectorに切り替わります(次回のComfyUI起動時に反映)。プレビュー画像を多数読み込むModelsの一覧を切り替えたあとにComfyUIが完全に固まる場合にオンにしてください。トレードオフとして、asyncioのサブプロセス機能が使えず、同時接続数は約512が上限です。環境変数 WFS_SELECTOR_LOOP=1 でも同じ切り替えができます",
helpSettings9: "各セクションはアコーディオン式で折りたたみ可能",
helpSettings10: "Wildcard Integration:WFSのワイルドカードディレクトリをComfyUI-Impact-Packのwildcardsディレクトリへリンク(Windowsはジャンクション、他OSはシンボリックリンク)。既存ファイルは自動で移行されます",
helpSettings11: "テキストサイズ:スライダー1本(10〜28px)でプロンプト・チャット全テキストエリアのフォントサイズを一括調整 — GenerateUI ポジティブ/ネガティブプロンプト、AIアシスタントチャット入力、プリセット ポジティブ/ネガティブ、ワイルドカードプロンプト・ファイルエディタ、メタデータプロンプト全文プレビュー;即時反映・保存で確定",
@@ -2754,6 +2768,14 @@ const LANGUAGES = {
workflowsDirChanged: "ワークフローフォルダを変更しました。ワークフロー一覧を更新してください。",
workflowsDirError: "フォルダ変更エラー",
workflowsDirBrowseHint: "ワークフローJSONファイルが含まれるフォルダのフルパスを入力してください。",
modelsDir: "モデルフォルダ",
modelsDirLabel: "追加モデルフォルダのパス",
modelsDirHint: "モデルのルートフォルダ(例: Stability Matrix の Models)。StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks(またはcheckpoints / lorasなどComfyUI名)のサブフォルダがModelsタブに追加されます。複数指定は ; 区切り。空欄でリセット。",
modelsDirChanged: "モデルフォルダを変更しました。Modelsタブを更新してください。",
selectorLoop: "Windowsの安定性(イベントループ)",
selectorLoopLabel: "WindowsでSelectorイベントループを使用する(要再起動)",
selectorLoopHint: "プレビュー画像が多いModelsの一覧を切り替えたあと、ComfyUIが固まる(全タブが無応答になり、生成もできなくなる)場合にオンにしてください。WindowsのasyncioループをProactorからSelectorに切り替えます。ComfyUIの再起動後に有効になります。asyncioのサブプロセス機能は使えなくなり、同時接続数は約512が上限です。問題が出ていなければオフのままで構いません。",
selectorLoopSaved: "保存しました。反映にはComfyUIの再起動が必要です。",
settingsTitle: "設定",
langLabel: "UI言語",
summaryLangLabel: "要約言語",
@@ -3630,7 +3652,8 @@ const LANGUAGES = {
civitaiSavingPreviews: "正在保存预览...",
civitaiHashing2: "计算哈希中...",
civitaiFetching: "获取中...",
civitaiBatchDone: (found, notFound) => `CivitAI: ${found}个已找到, ${notFound}个未找到`,
civitaiBatchDone: (found, notFound, needsHash) => `CivitAI: ${found}个已找到, ${notFound}个未找到` + (needsHash ? `, ${needsHash}个未计算哈希(请单独获取)` : ""),
civitaiHashNotCalculated: "未计算",
civitaiApiKeySetting: "CivitAI API密钥",
civitaiApiKeyHint: "可选。启用认证访问。在 civitai.com → 账户设置 → API Keys 获取。",
civitaiApiKeyPlaceholder: "在此粘贴您的CivitAI API密钥",
@@ -4010,6 +4033,8 @@ const LANGUAGES = {
helpSettings20: "默认 Checkpoint:开启「加载工作流时强制使用默认 Checkpoint」后,每次将工作流加载到 GenerateUI 时,所有 Checkpoint 加载节点的模型都会替换为所选的 Checkpoint(应用时会弹出提示)——可避免工作流中保存的本地不存在的模型名导致的错误或图像异常;「刷新」重新获取列表,「保存」保存设置",
helpSettings21: "CivitAI API 密钥:用于从 Models 标签以认证方式访问 CivitAI 的可选密钥(在 civitai.com → Account Settings → API Keys 获取);保存在 settings.json 中,但不包含在 JSON 导出和完整备份中;若设置了环境变量 CIVITAI_API_KEY,则优先使用该变量",
helpSettings22: "G'MIC-Qt 集成:Image Edit 标签的 G'MIC 滤镜(Edit with G'MIC)所使用的 G'MIC-Qt 可执行文件(gmic_qt.exe)路径;点击「Save」保存——G'MIC-Qt 的安装方法请参阅 Image Edit 帮助",
helpSettings23: "模型文件夹:可添加额外的模型根文件夹(例如 Stability Matrix 的 Models),其中的子文件夹(StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks,或 checkpoints / loras 等ComfyUI名称)会与ComfyUI自带文件夹一起显示在Models标签页;多个根文件夹用 ; 分隔,“应用”保存,“默认”清除",
helpSettings24: "Windows 稳定性:开启“在Windows上使用Selector事件循环”会把ComfyUI的asyncio循环从Proactor切换为Selector(下次启动ComfyUI时生效)。如果切换加载大量预览图的Models列表后ComfyUI完全卡死,请开启。代价是不支持asyncio子进程,并发连接数上限约为512。也可通过环境变量 WFS_SELECTOR_LOOP=1 切换",
helpSettings9: "各部分可折叠展开",
helpSettings10: "Wildcard Integration:将WFS通配符目录链接到ComfyUI-Impact-Pack的wildcards目录(Windows为目录联结,其他OS为符号链接);现有文件自动迁移",
helpSettings11: "文字大小:单个滑块(10–28 px)可一次性调整所有提示词和聊天文本框的字体大小 — GenerateUI正/负向提示词、AI助手聊天输入、预设正/负向提示、通配符提示和文件编辑器、元数据提示词全文预览;即时生效并通过「保存设置」保存",
@@ -4288,6 +4313,14 @@ const LANGUAGES = {
workflowsDirChanged: "工作流文件夹已更改。请刷新工作流列表。",
workflowsDirError: "文件夹更改错误",
workflowsDirBrowseHint: "输入包含工作流JSON文件的文件夹完整路径。",
modelsDir: "模型文件夹",
modelsDirLabel: "附加模型文件夹路径",
modelsDirHint: "模型根文件夹(例如 Stability Matrix 的 Models)。其中的 StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks(或 checkpoints / loras 等ComfyUI名称)子文件夹会添加到Models标签页。多个文件夹用 ; 分隔。留空重置。",
modelsDirChanged: "模型文件夹已更改。请刷新Models标签页。",
selectorLoop: "Windows 稳定性(事件循环)",
selectorLoopLabel: "在Windows上使用Selector事件循环(需重启)",
selectorLoopHint: "如果在切换含大量预览图的Models列表后ComfyUI卡死(所有标签页无响应,也无法生成),请开启此项。它会把Windows的asyncio循环从Proactor切换为Selector。重启ComfyUI后生效;asyncio子进程功能将不可用,并发连接数上限约为512。没有问题时请保持关闭。",
selectorLoopSaved: "已保存。重启ComfyUI后生效。",
settingsTitle: "设置",
langLabel: "UI语言",
summaryLangLabel: "摘要语言",
+2 -1
View File
@@ -13,6 +13,7 @@ import { openBadgeEditModal, renderBadgeFilter, setGridChangeCallback } from "./
import { isModelDisabled, renderTagFilter, renderGroupFilter, renderDirFilter } from "./models/filters.js";
import { renderModelGrid, clearBatchGroup, clearStackGroup } from "./models/grid-view.js";
import { toggleSelectMode, renderBulkActionBar, fetchSubdirs } from "./models/selection-bulk.js";
import { fetchPreviewKeys } from "./models/helpers.js";
import { closeSidePanel, renderSideCivitai, renderSideInfo, batchFetchCivitai, fetchCivitaiCache } from "./models/detail-panel.js";
export { openBadgeEditModal };
@@ -302,7 +303,7 @@ async function loadModelsForCurrentType() {
if (!fetchFn) throw new Error("Unknown model type: " + type);
const [models, disabledList, groups] = await Promise.all([
fetchFn(), fetchDisabledModels(type), fetchModelGroups(),
fetchFn(), fetchDisabledModels(type), fetchModelGroups(), fetchPreviewKeys(type),
]);
const disabledSet = new Set(Array.isArray(disabledList) ? disabledList : []);
state.disabledModels[type] = disabledSet;
+26 -42
View File
@@ -8,11 +8,11 @@
import { showToast, openModal, closeModal } from "../app.js";
import { t } from "../i18n.js";
import { escapeHtml } from "../util.js";
import { escapeHtml, sanitizeHtml, safeHttpUrl } from "../util.js";
import { state, RESERVED_GROUPS, GENUI_TYPE_MAP } from "./state.js";
import { getCurrentModels, renderTagFilter, renderDirFilter } from "./filters.js";
import { getBadgePalette, modelBadgesHtml, openBadgeEditModal } from "./badges.js";
import { parseModelPath, getExtension, getStem, loadPreviewImage, previewUrl } from "./helpers.js";
import { parseModelPath, getExtension, getStem, loadPreviewImage, previewUrl, markHasPreview, fetchPreviewKeys } from "./helpers.js";
import { renderModelGrid } from "./grid-view.js";
import {
applyToGenUI, applyEmbeddingToPrompt, saveModelMetadata, toggleGroupEnable,
@@ -200,6 +200,7 @@ export function openDetailModal(modelName) {
const res = await fetch("/api/wfm/models/change-preview", { method: "POST", body: fd });
const data = await res.json();
if (data.error) throw new Error(data.error);
markHasPreview(modelName);
// Reload preview in modal
const newUrl = previewUrl(modelName) + "&t=" + Date.now();
const mImg = document.querySelector(".wfm-modal-thumb-img");
@@ -308,12 +309,6 @@ export function renderSideInfo(modelName) {
</div>
</div>
</div>
<div class="wfm-node-detail-section">
<div class="wfm-node-detail-label">${t("modelsFilePath")}</div>
<div class="wfm-node-detail-value">
<span id="wfm-models-side-filepath" class="wfm-model-filepath" title="${t("modelsCopyPath")}" style="cursor:pointer;word-break:break-all;font-size:0.85em;color:#aaa;">${t("modelsLoading")}...</span>
</div>
</div>
<div class="wfm-node-detail-section">
<div class="wfm-node-detail-label">${t("modelsTags")}</div>
<div class="wfm-node-detail-value">
@@ -348,33 +343,6 @@ export function renderSideInfo(modelName) {
});
});
// Fetch and display file path
fetch(`/api/wfm/models/filepath?type=${encodeURIComponent(state.activeModelType)}&name=${encodeURIComponent(modelName)}`)
.then((r) => r.json())
.then((data) => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl && data.path) {
fpEl.textContent = data.path;
fpEl.title = t("modelsCopyPath");
} else if (fpEl) {
fpEl.textContent = modelName;
}
})
.catch(() => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl) fpEl.textContent = modelName;
});
// Copy file path on click
el.querySelector("#wfm-models-side-filepath")?.addEventListener("click", () => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl) {
navigator.clipboard.writeText(fpEl.textContent).then(() => {
showToast(t("modelsCopiedPath"), "success");
});
}
});
// Save button
el.querySelector("#wfm-models-side-save-btn")?.addEventListener("click", () => {
const tagsInput = document.getElementById("wfm-models-side-tags");
@@ -564,6 +532,15 @@ export function renderSideGroup(modelName) {
// ── Side Panel: CivitAI Tab ───────────────────────────────
// ハッシュ未計算を示す赤字の行(CivitAIタブ)。更新/取得ボタンでハッシュ計算して取得する
function hashMissingRowHtml() {
return `
<div style="display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:10px;">
<span style="color:var(--wfm-text-secondary);margin-right:8px;">${t("civitaiHashLabel")}</span>
<span id="wfm-civitai-hash-missing" style="color:#e53935;font-weight:600;">${t("civitaiHashNotCalculated")}</span>
</div>`;
}
export function renderSideCivitai(modelName) {
const el = document.getElementById("wfm-models-side-civitai");
if (!el) return;
@@ -593,6 +570,7 @@ export function renderSideCivitai(modelName) {
} else {
el.innerHTML = `
<div style="padding:0 4px;text-align:center;">
${hashMissingRowHtml()}
<p style="color:var(--wfm-text-secondary);font-size:13px;margin-bottom:12px;">
${t("civitaiFetchDesc")}
</p>
@@ -629,6 +607,7 @@ export async function fetchCivitaiForModel(modelName, el) {
if (!state.modelMetadata[modelName]) state.modelMetadata[modelName] = {};
state.modelMetadata[modelName].sha256 = data.sha256;
}
if (data.preview_saved) markHasPreview(modelName);
renderCivitaiInfo(el, data.civitai, modelName);
showToast(t("civitaiFound"), "success");
// Always refresh preview: local file if saved, otherwise civitai image as fallback
@@ -640,7 +619,7 @@ export async function fetchCivitaiForModel(modelName, el) {
if (data.preview_saved) {
sideImg.src = previewUrl(modelName) + "&t=" + Date.now();
} else {
const civitaiImg = data.civitai.images && data.civitai.images[0];
const civitaiImg = safeHttpUrl(data.civitai.images && data.civitai.images[0]);
if (civitaiImg) sideImg.src = civitaiImg;
}
sideImg.style.display = "";
@@ -669,7 +648,7 @@ export function renderCivitaiInfo(el, info, modelName) {
? `https://${civitaiHost}/models/${info.modelId}?modelVersionId=${info.versionId}`
: info.versionId
? `https://${civitaiHost}/model-versions/${info.versionId}`
: (info.modelUrl || "#");
: safeHttpUrl(info.modelUrl, "#");
// Hash: BLAKE3 優先、なければ SHA256
const fileHashes = info.fileHashes || {};
@@ -700,7 +679,11 @@ export function renderCivitaiInfo(el, info, modelName) {
<code class="wfm-hash-value" data-hash="${escapeHtml(hashFull)}"
style="background:var(--wfm-bg-secondary);padding:2px 6px;border-radius:3px;cursor:pointer;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:calc(100% - 84px);"
title="${t("civitaiCopyHash")}">${escapeHtml(hashType)}: ${escapeHtml(hashFull.substring(0, 16).toUpperCase())}…</code>
</div>` : "";
</div>` : `
<div style="${ROW}">
<span style="${LABEL}">${t("civitaiHashLabel")}</span>
<span style="color:#e53935;font-weight:600;">${t("civitaiHashNotCalculated")}</span>
</div>`;
const detailSection = (typeRow || baseModelRow || hashRow)
? `<div style="margin-bottom:10px;">${typeRow}${baseModelRow}${hashRow}</div>` : "";
@@ -714,7 +697,7 @@ export function renderCivitaiInfo(el, info, modelName) {
).join(" ");
// Sample images — all go to Sample pane
const images = info.images || [];
const images = (info.images || []).filter((u) => safeHttpUrl(u));
const sampleImagesHtml = images.map((url) =>
`<a href="${escapeHtml(url)}" target="_blank" rel="noopener" title="${t("civitaiOpenImage")}"><img src="${escapeHtml(url)}" style="width:100%;border-radius:4px;margin-bottom:6px;cursor:pointer;display:block;" loading="lazy" /></a>`
).join("");
@@ -744,7 +727,7 @@ export function renderCivitaiInfo(el, info, modelName) {
${detailSection}
${tagsHtml ? `<div style="margin-bottom:8px;">${tagsHtml}</div>` : ""}
${trainedWordsHtml ? `<div style="margin-bottom:10px;"><div style="font-weight:600;font-size:12px;margin-bottom:4px;">${t("civitaiTriggerWords")}</div>${trainedWordsHtml}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${info.description}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${sanitizeHtml(info.description)}</div>` : ""}
<div style="margin-top:10px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-civitai-refresh-btn">${t("civitaiRefresh")}</button>
</div>
@@ -866,13 +849,13 @@ export async function batchFetchCivitai() {
: data.status === "previews" ? t("civitaiSavingPreviews")
: data.status === "cached" ? "✓"
: data.status === "found" ? "✓"
: data.status === "not_found" ? "—"
: data.status === "not_found" || data.status === "needs_hash" ? "—"
: "";
if (progressEl) progressEl.textContent = `${pct}% (${data.current}/${data.total}) ${statusText}`;
} else if (eventType === "done") {
if (progressEl) progressEl.textContent = "";
const previewNote = data.preview_saved > 0 ? ` (+${data.preview_saved} preview)` : "";
showToast(t("civitaiBatchDone", data.found, data.not_found) + previewNote, "success");
showToast(t("civitaiBatchDone", data.found, data.not_found, data.needs_hash || 0) + previewNote, "success");
// Reload caches
const [newMeta, newCache] = await Promise.all([fetchModelMetadata(), fetchCivitaiCache()]);
// Apply sha256 hashes from batch result directly in case fetchModelMetadata
@@ -883,6 +866,7 @@ export async function batchFetchCivitai() {
if (!newMeta[modelName].sha256) newMeta[modelName].sha256 = sha256;
}
}
if (data.preview_saved > 0) await fetchPreviewKeys(state.activeModelType);
state.modelMetadata = newMeta;
state.civitaiCache = newCache;
renderModelGrid();
+30 -1
View File
@@ -3,6 +3,7 @@
*/
import { state } from "./state.js";
import { safeHttpUrl } from "../util.js";
export function parseModelPath(fullName) {
const lastSlash = Math.max(fullName.lastIndexOf("/"), fullName.lastIndexOf("\\"));
@@ -30,8 +31,35 @@ export function previewUrl(modelName, modelType) {
* (aiohttp add_get does not auto-handle HEAD method).
* Falls back to CivitAI cached image if no local preview exists.
*/
/** モデル名 → previewKeys のキー(`サブフォルダ/拡張子なし名`、小文字・/区切り) */
export function previewKey(modelName) {
const n = modelName.replace(/\\/g, "/");
const dot = n.lastIndexOf(".");
const slash = n.lastIndexOf("/");
return (dot > slash ? n.substring(0, dot) : n).toLowerCase();
}
/** プレビュー画像を持つモデルのキー一覧をサーバから取得してstateに保存。失敗時は保存せず従来動作に戻る */
export async function fetchPreviewKeys(modelType) {
const type = modelType || state.activeModelType;
try {
const res = await fetch(`/api/wfm/models/preview-keys?type=${encodeURIComponent(type)}`);
if (!res.ok) return;
const data = await res.json();
if (Array.isArray(data.keys)) state.previewKeys[type] = new Set(data.keys);
} catch { /* 従来動作(都度リクエスト)にフォールバック */ }
}
/** 新しくプレビューが作られた/変更されたモデルを登録する */
export function markHasPreview(modelName, modelType) {
const set = state.previewKeys[modelType || state.activeModelType];
if (set) set.add(previewKey(modelName));
}
export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
const url = previewUrl(modelName, modelType);
const keys = state.previewKeys[modelType || state.activeModelType];
const noLocalPreview = !!keys && !keys.has(previewKey(modelName));
imgEl.onload = () => {
imgEl.style.display = "";
if (placeholderEl) placeholderEl.style.display = "none";
@@ -41,7 +69,7 @@ export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
const meta = state.modelMetadata[modelName] || {};
const sha256 = meta.sha256;
const civitai = sha256 && state.civitaiCache[sha256];
const civitaiImg = civitai && civitai.images && civitai.images[0];
const civitaiImg = safeHttpUrl(civitai && civitai.images && civitai.images[0]);
if (civitaiImg) {
imgEl.onerror = () => {
imgEl.style.display = "none";
@@ -55,5 +83,6 @@ export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
if (placeholderEl) placeholderEl.style.display = "";
}
};
if (noLocalPreview) { imgEl.onerror(); return; }
imgEl.src = url;
}
+25 -7
View File
@@ -27,6 +27,7 @@ export const state = {
allModelGroups: {}, // { type: { groupName: [models] } } — all types
civitaiCache: {},
disabledModels: {}, // { type: Set<modelName> }
previewKeys: {}, // { type: Set<"subdir/stem"(小文字)> } プレビュー画像を持つモデル。未取得の型は従来どおり都度リクエスト
subdirs: [],
selectMode: false,
selectedModels: new Set(),
@@ -48,14 +49,31 @@ export const state = {
};
// 設定「モデルフォルダ」で追加されたフォルダのモデル(ComfyUIのobject_infoには出ない)
async function fetchExtraModels(type) {
try {
const res = await fetch(`/api/wfm/models/files?type=${encodeURIComponent(type)}&extra_only=1`);
if (res.ok) {
const list = await res.json();
return Array.isArray(list) ? list : [];
}
} catch {}
return [];
}
const withExtra = (type, fn) => async () => {
const [base, extra] = await Promise.all([fn(), fetchExtraModels(type)]);
return extra.length ? [...new Set([...base, ...extra])] : base;
};
export const FETCH_MAP = {
checkpoint: () => comfyUI.fetchCheckpoints(),
lora: () => comfyUI.fetchLoras(),
vae: () => comfyUI.fetchVaes(),
controlnet: () => comfyUI.fetchControlNets(),
unet: () => comfyUI.fetchDiffusionModels(),
textencoder: () => comfyUI.fetchTextEncoders(),
hypernetwork: () => comfyUI.fetchHypernetworks(),
checkpoint: withExtra("checkpoint", () => comfyUI.fetchCheckpoints()),
lora: withExtra("lora", () => comfyUI.fetchLoras()),
vae: withExtra("vae", () => comfyUI.fetchVaes()),
controlnet: withExtra("controlnet", () => comfyUI.fetchControlNets()),
unet: withExtra("unet", () => comfyUI.fetchDiffusionModels()),
textencoder: withExtra("textencoder", () => comfyUI.fetchTextEncoders()),
hypernetwork: withExtra("hypernetwork", () => comfyUI.fetchHypernetworks()),
embedding: () => comfyUI.fetchEmbeddings(),
};
+74
View File
@@ -676,6 +676,38 @@ export async function initSettingsTab() {
</div>
</details>
<!-- Models Folder -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("modelsDir")}</summary>
<div class="wfm-form-group">
<label>${t("modelsDirLabel")}</label>
<div style="display:flex;gap:8px;">
<input type="text" class="wfm-input" id="wfm-settings-models-dir"
value="${serverSettings.models_dir || ""}"
placeholder="C:\\Users\\...\\StabilityMatrix\\Models">
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-settings-models-dir-apply">${t("workflowsDirApply")}</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-models-dir-reset">${t("workflowsDirDefault")}</button>
</div>
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("modelsDirHint")}
</small>
</div>
</details>
<!-- Windows Event Loop (stability) -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("selectorLoop")}</summary>
<div class="wfm-form-group">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-settings-selector-loop" ${serverSettings.windows_selector_event_loop ? "checked" : ""}>
<span>${t("selectorLoopLabel")}</span>
</label>
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("selectorLoopHint")}
</small>
</div>
</details>
<!-- Gallery Output Folder -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("galleryOutputDir")}</summary>
@@ -1171,6 +1203,48 @@ export async function initSettingsTab() {
}
});
// --- Windows selector event loop (needs ComfyUI restart) ---
document.getElementById("wfm-settings-selector-loop")?.addEventListener("change", async (e) => {
const enabled = !!e.target.checked;
try {
await saveServerSettings({ windows_selector_event_loop: enabled });
serverSettings.windows_selector_event_loop = enabled;
showToast(t("selectorLoopSaved"), "success");
} catch (err) {
e.target.checked = !enabled;
showToast(`${t("saveError")}: ${err.message}`, "error");
}
});
// --- Models dir handlers ---
const saveModelsDir = async (value) => {
try {
const res = await fetch("/api/wfm/settings/models-dir", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ models_dir: value }),
});
const data = await res.json();
if (data.error) {
showToast(`${t("workflowsDirError")}: ${data.error}`, "error");
return;
}
const input = document.getElementById("wfm-settings-models-dir");
if (input) input.value = data.saved || "";
showToast(t("modelsDirChanged"), "success");
window.dispatchEvent(new CustomEvent("wfm-models-dir-changed"));
} catch (err) {
showToast(`${t("workflowsDirError")}: ${err.message}`, "error");
}
};
document.getElementById("wfm-settings-models-dir-apply")?.addEventListener("click", () => {
saveModelsDir(document.getElementById("wfm-settings-models-dir").value.trim());
});
document.getElementById("wfm-settings-models-dir-reset")?.addEventListener("click", () => {
document.getElementById("wfm-settings-models-dir").value = "";
saveModelsDir("");
});
// --- Gallery output dir handlers ---
document.getElementById("wfm-settings-output-dir-apply")?.addEventListener("click", async () => {
const dirInput = document.getElementById("wfm-settings-output-dir");
+51
View File
@@ -82,6 +82,57 @@ export function escapeHtml(s) {
.replace(/'/g, "&#x27;");
}
// http(s) 以外(javascript: / data: など)を拒否して安全なURLだけ返す。不正なら fallback
export function safeHttpUrl(url, fallback = "") {
// 絶対URLのhttp(s)のみ許可(相対URLだとComfyUI自身のURLへリクエストを送らせられるため不可)
const s = String(url ?? "").trim();
if (!/^https?:\/\/[^\s]+$/i.test(s)) return fallback;
try {
new URL(s);
return s;
} catch {
return fallback;
}
}
// 外部由来のHTML(CivitAIの説明文など)を許可リスト方式で無害化して返す。
// スクリプト・イベント属性・style・javascript:/data: URL・iframe等は除去する。
const _SAN_DROP = new Set(["script", "style", "iframe", "frame", "frameset", "object", "embed", "applet",
"link", "meta", "base", "form", "input", "button", "textarea", "select", "svg", "math", "template",
"noscript", "audio", "video", "source", "track", "canvas", "title", "head"]);
const _SAN_KEEP = new Set(["p", "br", "hr", "strong", "b", "em", "i", "u", "s", "del", "ins", "mark", "small",
"sub", "sup", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "code", "pre", "kbd",
"span", "div", "a", "img", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "details", "summary"]);
export function sanitizeHtml(html) {
if (html == null || html === "") return "";
const doc = new DOMParser().parseFromString(String(html), "text/html"); // 不活性ドキュメント(スクリプト非実行)
const walk = (node) => {
let out = "";
for (const child of node.childNodes) {
if (child.nodeType === 3) { // text
out += escapeHtml(child.nodeValue);
} else if (child.nodeType === 1) { // element
const tag = child.tagName.toLowerCase();
if (_SAN_DROP.has(tag)) continue;
if (!_SAN_KEEP.has(tag)) { out += walk(child); continue; } // 未知タグは中身だけ残す
if (tag === "br" || tag === "hr") { out += `<${tag}>`; continue; }
if (tag === "a") {
const href = safeHttpUrl(child.getAttribute("href") || "", "");
out += `<a${href ? ` href="${escapeHtml(href)}"` : ""} target="_blank" rel="noopener noreferrer">${walk(child)}</a>`;
} else if (tag === "img") {
const src = safeHttpUrl(child.getAttribute("src") || "", "");
if (src) out += `<img src="${escapeHtml(src)}" alt="${escapeHtml(child.getAttribute("alt") || "")}" loading="lazy" style="max-width:100%;">`;
} else {
out += `<${tag}>${walk(child)}</${tag}>`;
}
}
}
return out;
};
return walk(doc.body);
}
// localStorage からJSONを安全に読む(不正JSON・未設定時はfallback)
export function readJsonStorage(key, fallback = {}) {
try {
+2
View File
@@ -1682,6 +1682,7 @@
<h3 id="wfm-help-settings-card-workflow-title">Workflow Defaults</h3>
<ul>
<li id="wfm-help-settings-3">Workflow data folder path</li>
<li id="wfm-help-settings-23">Models Folder: add extra model root folders (e.g. Stability Matrix's Models) — their subfolders (StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks, or ComfyUI names like checkpoints / loras) are listed in the Models tab in addition to ComfyUI's own folders; separate several roots with ; — Apply saves, Default clears</li>
<li id="wfm-help-settings-19">Gallery Output Folder: the ComfyUI output folder the Gallery tab browses — leave blank to use ComfyUI's default output directory; Apply takes effect immediately, Default resets it, and the folder currently in use is shown below the field</li>
<li id="wfm-help-settings-6">Default workflow setting</li>
<li id="wfm-help-settings-20">Default Checkpoint: when "Force default checkpoint on workflow load" is on, every checkpoint loader node's model is replaced with the chosen checkpoint whenever a workflow is loaded into GenerateUI (a toast shows when it's applied) — avoids errors or garbled images caused by a model name saved in the workflow that you don't have; Refresh reloads the checkpoint list, Save stores the setting</li>
@@ -1705,6 +1706,7 @@
<li id="wfm-help-settings-16">Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them. A third checkbox includes the clips, BGM, sounds and overlay clips referenced by saved Video Edit projects (projects only store references to files in ComfyUI's input folder) — unlike the other two, these are restored into the input folder, skipping any file that already exists there.</li>
<li id="wfm-help-settings-13">CivitAI Host: choose between civitai.com (SFW only) and civitai.red (unrestricted) — determines which site opens when clicking a model link in the Models tab CivitAI panel</li>
<li id="wfm-help-settings-21">CivitAI API Key: optional key for authenticated CivitAI access from the Models tab (get it at civitai.com → Account Settings → API Keys); stored in settings.json but left out of the JSON export and Full Backup, and the CIVITAI_API_KEY environment variable takes priority when set</li>
<li id="wfm-help-settings-24">Windows Stability: "Use the Selector event loop on Windows" switches ComfyUI's asyncio loop from Proactor to Selector (applied at the next ComfyUI start). Turn it on if ComfyUI freezes entirely after switching Models lists that load many preview images; the trade-offs are no asyncio subprocess support and a connection limit of about 512. The same switch is available through the WFS_SELECTOR_LOOP=1 environment variable</li>
</ul>
</div>
</div>