Compare commits

...
10 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 4.6 8c98eabf59 fix: GenUI ModelでLoRA適用後にModelサブタブ再表示で値がリセットされるバグ修正 (v0.3.52)
renderLoraPaneがModelサブタブ切替のたびにel.innerHTMLを再構築する際、
currentValをcurrentAnalysis(古いanalysis)から取得していたため、
applyToGenUIでcurrentWorkflowを更新してもサブタブ再表示時に元の値に戻っていた。
currentWorkflowから直接読み取るよう修正し、syntax/trigger wordsも保存・復元する。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 21:45:39 +09:00
ketle-manandClaude Sonnet 4.6 8b3be02600 chore: bump version to v0.3.51; update README and DEVLOG
- pyproject.toml: 0.3.50 → 0.3.51
- README: version badge updated, Input/Model tab and GenUI Model button
  descriptions updated; v0.3.51 Changelog entry added
- DEVLOG: v0.3.50 → v0.3.51 for all new-feature entries added this session

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 18:57:16 +09:00
ketle-manandClaude Sonnet 4.6 e82808e16a docs(help): update help for Embedding GenUI PP/NP and Hypernetwork in Gen UI
- gen-4: describe Embeddings selector + Paste button in Prompt tab
- gen-5: add Hypernetwork (with Strength field) to Model tab list
- models-8: add Hypernetwork to GenUI Model list; add Embedding GenUI PP/NP button description
- All three languages updated (EN/JP/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 18:53:40 +09:00
ketle-manandClaude Sonnet 4.6 751f507f91 fix(genui): reduce Positive Prompt textarea height by 2 rows (~45px)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 18:49:50 +09:00
ketle-manandClaude Sonnet 4.6 9ece4b3549 feat(embedding): add GenUI PP/NP buttons for Embeddings + Paste in Prompt tab
- Models tab: show GenUI PP / GenUI NP buttons for Embedding type in side panel nav, info panel, and detail modal
- Generate UI > Prompt tab: add Embeddings section with filter/select/weight + Paste button (inserts at cursor position of last focused textarea)
- comfyEditor: appendEmbeddingToPrompt() updates both workflow JSON and textarea
- closeSidePanel(): hides nav buttons to prevent stale state on model type switch

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 18:34:25 +09:00
ketle-manandClaude Sonnet 4.6 8af4a05a48 feat(genui): add Hypernetwork support to GenerateUI Model tab
GenerateUIのModelタブ最下部にHypernetworkセクションを追加。
ワークフロー解析でHypernetworkLoaderを検出し、
strength入力フィールドも含めてApply対応。
ModelsタブGenUI ModelボタンもHypernetworkタイプで有効化。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 17:59:33 +09:00
ketle-manandClaude Sonnet 4.6 87c805c51d fix(models): fix Embedding not showing via WFS backend API
ComfyUIの/embeddingsエンドポイントへの直接fetchがHTMLを返す問題を修正。
WFSバックエンドの/api/wfm/models/files?type=embeddingを新設し、
folder_pathsからモデルファイルを確実に取得するよう変更。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 17:29:59 +09:00
ketle-manandClaude Sonnet 4.6 22ed57efb3 fix(models): support V3 ComfyNode Combo format in _fetchModelList
HypernetworkLoaderがV3形式(options)でComboを返すため
Hypernetworkモデルが空になっていたバグを修正。
fetchEmbeddingsにエラーログを追加しデバッグを容易にした。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 17:15:11 +09:00
ketle-manandClaude Sonnet 4.6 070015ea3d feat(models): add GenUI Model button to side panel tab nav
CivitAIタブ横のタブナビゲーション右端にGenUI Modelボタンを追加。
GenUI非対応タイプでは自動的に非表示になる。モーダルの既存ボタンは維持。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 15:01:03 +09:00
ketle-manandClaude Sonnet 4.6 474dea9e7f fix: gallery prompt search hang — background indexer + asyncio.to_thread (v0.3.50)
- Remove on-demand metadata read from list_images() (root cause of hang)
- Wrap list_images() route in asyncio.to_thread() to free the event loop
- Add background indexer (start_background_index / _bg_index_folder):
  processes uncached images 10 at a time with 50ms sleep between batches;
  auto-starts on folder load; cancellable on folder switch

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 12:36:33 +09:00
13 changed files with 570 additions and 56 deletions
+152
View File
@@ -1,5 +1,157 @@
# DEVLOG - ComfyUI-Workflow-Studio
## 2026-06-24: GenUI ModelでLoRA適用後、Modelサブタブ再表示時に値がリセットされるバグ修正
**変更ファイル**: `static/js/comfyui-editor.js`
### 問題
ModelsタブのGenUI ModelボタンでLoRAをGenerate UIタブのLORA Singleに適用後、別サブタブ(Prompt/Image/Settings等)に移動してModelサブタブに戻ると、LoRAセレクトが元のワークフロー読み込み時の値にリセットされていた。
### 原因
`renderLoraPane()`はModelサブタブに切り替えるたびに`el.innerHTML`を完全再構築する(Stackグループ変更を反映するため)。その際に`currentVal`を`analysis.lora_nodes[0]?.lora_name`(ワークフロー読み込み時点の`currentAnalysis`の値)から取得していた。`applyToGenUI()`は`currentWorkflow`を更新するが`currentAnalysis`は更新しないため、再描画時に古い値が使われて元に戻っていた。syntax表示とtrigger wordsも`innerHTML`リセットで消えていた。
### 修正
- **currentVal取得ロジックを修正**: `analysis.lora_nodes[0]?.lora_name`の代わりに`comfyUI.currentWorkflow`から直接読み取る。標準LoraLoaderは`inputs.lora_name`、LoraManagerは`inputs.loras.__value__[0].name`からstemを取得してフルパスに復元。
- **syntax/trigger wordsを再描画をまたいで保持**: `el.innerHTML`設定前に`wfm-lora-single-syntax`と`wfm-lora-single-triggers`の現在値を保存し、HTML再構築後に復元。
---
## 2026-06-24: v0.3.51 — Embedding GenUI PP/NP対応 + GenerateUIプロンプトタブEmbeddingセレクタ追加
**変更ファイル**: `templates/index.html`, `static/js/comfyui-editor.js`, `static/js/models-tab.js`
### 変更内容
**ModelsタブEmbeddingタイプにGenUI PP / GenUI NPボタンを追加**
- `templates/index.html`: サイドパネルナビに `#wfm-side-genui-np-btn` を追加(Embeddingタイプ時のNP用ボタン)
- `models-tab.js`:
- `applyEmbeddingToPrompt(modelName, promptType)` 関数を追加。モデルstemから `(embedding:Stem:1.0)` を生成し `comfyEditor.appendEmbeddingToPrompt()` を呼ぶ
- サイドパネルナビ: Embeddingタイプ時は "GenUI PP" / "GenUI NP" を表示、他タイプは従来の "GenUI Model" のみ表示
- `renderSideInfo()`: Embeddingタイプ時は PP/NP ボタンを表示
- `openDetailModal()`: Embeddingタイプ時は PP/NP ボタンを表示
- `closeSidePanel()`: ナビボタンをすべて非表示にする(タイプ切替時の残留防止)
**GenerateUI PrompタブにEmbeddingセレクタ追加**
- `comfyui-editor.js`:
- `models.embeddings: []` を追加、`loadModelLists()` に `fetchEmbeddings()` を追加
- `_lastPromptFocus` モジュール変数を追加(最後にフォーカスしたpromptテキストエリアのIDと選択位置を保持)
- `renderPromptTab()`: PromptタブのPositive/Negativeの下にEmbeddingsセクションを追加
- Filter入力 + Selectドロップダウン(埋め込みモデル一覧)+ Weight入力(デフォルト1.0) + Pasteボタン
- Pasteボタン: 最後にフォーカスしたテキストエリアのカーソル位置に `(embedding:Stem:weight)` を挿入
- テキストエリアにblur/click/keyupリスナーを追加してカーソル位置を追跡
- `appendEmbeddingToPrompt(syntax, promptType)` メソッドを追加: ワークフローの対応ノードとテキストエリア両方を更新してプロンプト末尾に追加
---
## 2026-06-24: v0.3.51 — GenerateUIタブ Hypernetwork対応 + ModelsタブGenUI Modelボタン追加
**変更ファイル**: `static/js/comfyui-workflow.js`, `static/js/comfyui-editor.js`, `static/js/models-tab.js`
### 変更内容
**GenerateUI → Model タブに Hypernetwork セクション追加**
- `comfyui-workflow.js` `analyzeWorkflow()`: `hypernetwork_nodes: []` を追加。`HypernetworkLoader` ノードを検出し `hypernetwork_name` / `strength` を収集。
- `comfyui-editor.js`:
- `models.hypernetworks: []` を追加、`loadModelLists()` に `fetchHypernetworks()` を追加
- `renderModelTab()` の `sections` 末尾に Hypernetwork を追加。`extras` プロパティで `strength`(数値フィールド)を表示・Apply 時に反映
- `models-tab.js` `GENUI_TYPE_MAP`: `hypernetwork: { key: "hypernetworks", inputKey: "hypernetwork_name" }` を追加。これにより詳細パネル・モーダルの GenUI Model ボタンが Hypernetwork タイプでも有効になる。
---
## 2026-06-24: v0.3.51 — Hypernetwork/Embeddingモデル未表示バグ修正
**変更ファイル**: `static/js/comfyui-client.js`
### 原因
`_fetchModelList` が ComfyUI V3ノード(`IO.ComfyNode`)の `object_info` レスポンス形式に未対応だった。
- V1形式: `[["model1.pt", ...], {}]` → 配列チェックで対応済み
- V2形式: `["COMBO", {"values": [...]}]` → `values`キーで対応済み
- **V3形式**: `["COMBO", {"options": [...]}]` → **未対応** ← `HypernetworkLoader` がこの形式
`HypernetworkLoader` は V3 `IO.ComfyNode` で実装されており、`options` キーを使う。`_fetchModelList` が `values` しか見ていなかったため、常に空配列を返してHypernetworkモデルが一切表示されなかった。
### 修正内容
**`comfyui-client.js`**
- `_fetchModelList`: V3形式 `inputDef[1]?.options` の取得ケースを追加
- `fetchEmbeddings`: ComfyUIの `/embeddings` エンドポイントへの直接アクセスをやめ、WFSバックエンドAPI `/api/wfm/models/files?type=embedding` を使うよう変更(SPAのURLによっては `/embeddings` がHTMLを返す問題があったため)
**`py/services/models_service.py`**
- `_MODEL_EXTENSIONS` 定数を追加(`.safetensors`, `.ckpt`, `.pt`, `.pth`, `.bin`, `.gguf`, `.pt2`)
- `list_model_files(model_type)` メソッドを追加: モデルファイルのみをフィルタリングしてソート済みリストを返す
**`py/routes/models_routes.py`**
- `GET /api/wfm/models/files?type=<type>` エンドポイントを追加
---
## 2026-06-24: v0.3.51 — ModelsタブサイドパネルにGenUI Modelボタン追加
**変更ファイル**: `templates/index.html`, `static/js/models-tab.js`
### 変更内容
モデルタブのサイドパネル(詳細パネル)のタブナビゲーション(Info / Group / CivitAI)に、CivitAIタブの右横へ **GenUI Model** ボタンを追加した。
- `index.html`: `wfm-side-tab-nav` 内にボタン(`#wfm-side-genui-nav-btn`)を追加。`margin-left:auto` で右端寄せ、初期状態は非表示。
- `models-tab.js` `showSidePanel()`: モデル選択時に `GENUI_TYPE_MAP` で対応タイプ(checkpoint / lora / vae 等)なら表示、非対応なら非表示に切り替え。ボタンテキストとtitleもi18nで設定。
- `models-tab.js` init: ボタンクリックで `applyToGenUI(selectedModel, activeModelType)` を呼び出すイベントを追加。
モーダル内の既存 GenUI Model ボタン(`#wfm-modal-genui-model`)はそのまま維持。
---
## 2026-06-22: v0.3.50 — ギャラリータブ プロンプト検索負荷改善(バックグラウンドインデックス)
**変更ファイル**: `py/services/gallery_service.py`, `py/routes/gallery_routes.py`
### 問題
v0.3.49で導入したプロンプト検索の未キャッシュ画像オンデマンド読み込みが、大量の画像フォルダで深刻な負荷問題を引き起こしていた。
- `list_images()`が`asyncio.to_thread()`なしでaiohttpイベントループ上で同期実行されていたため、全未キャッシュ画像のファイルI/O+DB書き込みがComfyUIのイベントループをブロックし、ハングアップが発生していた。
### 修正内容
**`gallery_routes.py`**
- `list_images`ルートで`_service.list_images()`を`asyncio.to_thread()`でスレッドプールに投げるよう変更(イベントループブロック解消)
- 検索なしのフォルダロード時に`_service.start_background_index()`を呼び出してバックグラウンドインデックスを自動起動
**`gallery_service.py`**
- `import threading`を追加
- `__init__`にバックグラウンドインデックス用キャンセルイベント(`_bg_cancel`)を追加
- `list_images()`からオンデマンド読み込みを完全に削除(`prompt_cache`が空の場合の読み込み処理を除去)
- `start_background_index(folder_path)`メソッドを追加:前回のスレッドをキャンセルして新しいdaemonスレッドを起動
- `_bg_index_folder(folder_path, cancel)`メソッドを追加:
- 未キャッシュ画像のみを対象(`prompt_cache`が存在する画像はスキップ)
- 10枚処理するたびにバッチDB保存 + 50msスリープでメインスレッドへの影響を最小化
- キャンセルイベントで即座に中断可能(フォルダ切替時など)
### 新しい動作フロー
```
フォルダ選択(検索なし)
→ asyncio.to_thread で list_images() をスレッド実行(ノンブロッキング)
→ 画像一覧を即返却
→ バックグラウンドスレッドが自動起動
→ 未キャッシュ画像を10枚ずつ処理、50msスリープを挟んで低負荷で順次インデックス
→ インデックス完了後の検索でA1111画像等もヒットするようになる
プロンプト検索
→ asyncio.to_thread で list_images() をスレッド実行(ノンブロッキング)
→ キャッシュ済み画像のみ検索(重いI/O処理なし)
```
---
## 2026-06-22: v0.3.49 — 生成UIタブ A1111風ワイルドカード展開・ギャラリータブ バグ修正2件
**変更ファイル**: `static/js/generate-tab.js`, `static/js/app.js`, `py/services/gallery_service.py`, `static/js/i18n.js`, `templates/index.html`
+17 -4
View File
@@ -18,7 +18,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.3.49-green)
![Version](https://img.shields.io/badge/version-0.3.52-green)
## Screenshots
@@ -70,8 +70,8 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
### GenerateUI Tab (v0.3.5)
- **5-tab layout** — Input / Model / Settings / Feeder / Batch tabs; Input, Model, and Settings each include a Raw JSON column on the right for instant preview and direct editing
- **Save button** — located at the right end of the subtab row; opens a filename dialog (default: current workflow name) and saves the current workflow as a `.json` file to the Workflow tab via the import API
- **Input tab** — Prompt (top) and Image drag-and-drop (bottom) in the left column; Raw JSON (540px) in the right column
- **Model tab** — Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; Raw JSON on the right
- **Input tab** — Prompt and Image inner tabs (drag-and-drop upload); Prompt tab shows Positive Prompt and Negative Prompt textareas, plus an **Embeddings selector** at the bottom (Filter + Select + Weight input + Paste button); Paste inserts `(embedding:Name:weight)` at the cursor position of the last focused textarea (defaults to Positive when neither is focused); Raw JSON (540px) in the right column
- **Model tab** — Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder, **Hypernetwork** (with Strength field) selectors with filter; Raw JSON on the right
- **Settings tab** — KSampler and Latent Image side by side at 50% width each; Raw JSON on the right
- **Always-visible Raw JSON** — edit the API-format JSON directly from any tab with syntax highlighting; Apply button reloads the workflow; built-in **search bar** (always shown) finds all matches as you type with count display (`3/12`); navigate with ↑/↓ buttons or Enter / Shift+Enter; Escape or ✕ clears; current match highlighted in orange, other matches in yellow
- **One-click generation** — queue prompts to ComfyUI without leaving the studio
@@ -187,7 +187,7 @@ Two independent modes selectable via **[Image Loop] / [Gallery]** toggle buttons
- **CivitAI panel states** — three distinct states: not yet checked (fetch button), checked but not found on CivitAI (re-check button with notice), and found (full info display); clicking the CivitAI tab always refreshes to the latest state
- **Batch CivitAI fetch** — one-click batch fetch using `POST /model-versions/by-hash` (up to 100 models per request) with SSE progress streaming; previews are auto-saved for models without one
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload; **Delete** button permanently removes the model file and all associated sidecar files (preview images, `.json`, `.civitai.info`, `.metadata.json`, `.cm-info.json`)
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder)
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork); **Embedding** type shows **GenUI PP** / **GenUI NP** buttons instead — appends `(embedding:Name:1.0)` to the Positive or Negative prompt of the loaded workflow; also accessible from the side panel nav bar and the detail modal
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab); Checkpoint and LoRA tabs include **B (Batch)** and **S (Stack)** quick-assign buttons per card/row for one-click group membership toggle without grid re-render
- **Table view memo** — memo column displayed in table view for quick reference
- **Preview images** — auto-detect `{model_stem}.preview.png` next to model files
@@ -334,6 +334,19 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
## Changelog
### v0.3.52
- **GenerateUI Model tab — fix LoRA selection reset when switching subtabs** — applying a LoRA via "GenUI Model" button and then switching to another subTab (Prompt/Image/Settings) and back to Model caused the LoRA selector, syntax display, and trigger words to revert to the original workflow values; fixed by reading `currentVal` directly from `currentWorkflow` instead of the stale `currentAnalysis`, and by saving/restoring the Single tab's syntax and trigger words across re-renders
### v0.3.51
- **Models tab — Embedding type: GenUI PP / GenUI NP buttons** — Embedding models now show two buttons ("GenUI PP" and "GenUI NP") in the side panel nav, detail side panel, and detail modal (replacing the single "GenUI Model" button); clicking either appends `(embedding:Name:1.0)` to the Positive or Negative prompt of the loaded workflow
- **GenerateUI Prompt tab — Embeddings selector** — new section at the bottom of the Prompt tab: Filter input, model select dropdown, Weight input (default 1.0), and Paste button; Paste inserts `(embedding:Stem:weight)` at the cursor position of the last focused textarea (Positive or Negative); focus state is tracked on click/keyup/blur so the button works even after clicking away
- **GenerateUI Model tab — Hypernetwork support** — Hypernetwork section added with model selector (filter) and Strength field; applies to `HypernetworkLoader` nodes in the workflow; GenUI Model button in Models tab also triggers Hypernetwork apply
- **Models tab — fix Embedding and Hypernetwork models not shown** — `_fetchModelList` now handles the ComfyUI V3 node format (`options` key) in addition to V1/V2 formats; `fetchEmbeddings` switched from the `/embeddings` ComfyUI endpoint to the WFS backend API (`/api/wfm/models/files?type=embedding`) to avoid SPA URL routing conflicts
- **Models tab — GenUI Model button in side panel nav** — "GenUI Model" button added to the tab navigation bar (Info / Group / CivitAI) of the side panel; appears for supported model types (Checkpoint, LoRA, VAE, etc.) and hides for unsupported types; Embedding type shows PP/NP nav buttons instead
### v0.3.50
- **Gallery tab — fix prompt search causing ComfyUI hang under large folders** — the v0.3.49 on-demand metadata read ran synchronously on the aiohttp event loop, blocking ComfyUI when folders contained many uncached images; fixed by: (1) removing on-demand reads from `list_images()`; (2) wrapping `list_images()` in `asyncio.to_thread()` to keep the event loop free; (3) adding a background indexer (`start_background_index`) that automatically indexes uncached images after a folder is loaded — processes 10 images per batch with a 50 ms sleep between batches; cancellable on folder switch
### v0.3.49
- **GenerateUI tab — A1111-style SPA-side wildcard expansion** — when prompt text in non-ImpactWildcard nodes (e.g. CLIPTextEncode) contains `__name__` syntax, the SPA expands it at generation time by randomly picking a line from the matching file in the WFS wildcard folder; nested wildcards are re-expanded up to 5 passes; unresolved wildcards are passed through unchanged; ImpactWildcardEncode/Processor nodes are skipped (handled server-side by Impact Pack); works in both single and batch generation
- **Gallery tab — fix Export button missing label** — the bulk action bar's Export button had no text label because the `textContent` assignment was missing from `updateUITexts()`; fixed by adding the `galleryBulkExport` i18n key assignment alongside the existing Move/Delete entries
+6 -1
View File
@@ -1,6 +1,7 @@
"""
Gallery Routes - ギャラリータブ用APIエンドポイント
"""
import asyncio
import json
import mimetypes
import logging
@@ -105,7 +106,8 @@ async def list_images(request: web.Request) -> web.Response:
return web.json_response({"error": "folder parameter required"}, status=400)
try:
images = _service.list_images(
images = await asyncio.to_thread(
_service.list_images,
folder,
search=search,
sort_by=sort_by,
@@ -113,6 +115,9 @@ async def list_images(request: web.Request) -> web.Response:
tag_filter=tag_filter,
group_filter=group_filter,
)
# 検索なしのフォルダロード時にバックグラウンドインデックスを起動
if not search:
_service.start_background_index(folder)
return web.json_response({"images": images, "total": len(images)})
except Exception as e:
logger.error("list_images error: %s", e)
+21
View File
@@ -33,6 +33,7 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/models/delete", handle_delete_models)
app.router.add_get("/api/wfm/models/subdirs", handle_get_subdirs)
app.router.add_post("/api/wfm/models/move", handle_move_models)
app.router.add_get("/api/wfm/models/files", handle_list_model_files)
# ── Model Metadata ─────────────────────────────────────────
@@ -616,3 +617,23 @@ async def handle_move_models(request: web.Request) -> web.Response:
except Exception as e:
logger.error("Error in move_models: %s", e)
return web.json_response({"error": str(e)}, status=500)
# ── Model File List ───────────────────────────────────────
async def handle_list_model_files(request: web.Request) -> web.Response:
"""GET /api/wfm/models/files?type=<model_type>
Returns sorted list of model file names (with extension) for the given type.
Used as a fallback when ComfyUI's /embeddings endpoint is not accessible.
"""
from ..services.models_service import MODEL_TYPE_FOLDER_KEYS
model_type = request.query.get("type", "")
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)
return web.json_response(result)
except Exception as e:
logger.error("Error listing model files for %s: %s", model_type, e)
return web.json_response({"error": str(e)}, status=500)
+68 -16
View File
@@ -8,6 +8,7 @@ import mimetypes
import os
import re
import struct
import threading
import time
from pathlib import Path
from typing import Any
@@ -73,12 +74,78 @@ class GalleryService:
self.metadata_store = GalleryMetadataStore(data_dir / "gallery_metadata.json")
self._allowed_root: Path | None = None
self._folder_cache = _FolderCache()
self._bg_cancel = threading.Event()
self._bg_cancel.set() # 初期状態: キャンセル済み
def update_output_root(self, root_path: str) -> None:
"""許可するルートパスを更新する(Settings変更時に呼ぶ)"""
p = Path(root_path).resolve() if root_path else None
self._allowed_root = p
# ──────────────────────────────────────────────────────────────
# バックグラウンドインデックス
# ──────────────────────────────────────────────────────────────
def start_background_index(self, folder_path: str) -> None:
"""フォルダ内の未キャッシュ画像をバックグラウンドでインデックスする。
フォルダロード時に呼び出す。前回のインデックス処理は自動キャンセル。"""
self._bg_cancel.set() # 前のスレッドをキャンセル
cancel = threading.Event()
self._bg_cancel = cancel
t = threading.Thread(
target=self._bg_index_folder,
args=(folder_path, cancel),
daemon=True,
)
t.start()
def _bg_index_folder(self, folder_path: str, cancel: threading.Event) -> None:
"""バックグラウンドスレッドで未キャッシュ画像のprompt_cacheを構築する。
10枚処理するたびに50msスリープしてメインスレッドへの影響を最小化。"""
try:
folder = Path(folder_path).resolve()
if not folder.is_dir() or not self._check_path_allowed(folder):
return
entries = self._scan_folder(folder)
batch: dict[str, dict] = {}
processed = 0
for name, abs_path, _, _ in entries:
if cancel.is_set():
return
ext = Path(name).suffix.lower()
if ext not in (".png", ".jpg", ".jpeg"):
continue
meta = self.metadata_store.get(abs_path)
if meta.get("prompt_cache"):
continue
embedded: dict = {}
if ext == ".png":
embedded = self._read_png_metadata(Path(abs_path))
else:
embedded = self._read_jpeg_metadata(Path(abs_path))
if not embedded:
continue
prompt_cache = " ".join(
str(v) for k, v in embedded.items()
if k != "workflow" and isinstance(v, str) and len(v) < 50_000
).strip()
if not prompt_cache:
continue
batch[abs_path] = {"prompt_cache": prompt_cache}
processed += 1
if len(batch) >= 10:
for p, d in batch.items():
self.metadata_store.save(p, d)
batch = {}
time.sleep(0.05) # 50ms 他の処理に譲る
if batch and not cancel.is_set():
for p, d in batch.items():
self.metadata_store.save(p, d)
if processed:
logger.debug("BG index done: %s (%d indexed)", folder_path, processed)
except Exception as e:
logger.debug("BG index error: %s", e)
def _check_path_allowed(self, path: Path) -> bool:
"""パスが許可ルート配下かチェック(パストラバーサル防止)"""
if self._allowed_root is None:
@@ -225,26 +292,11 @@ class GalleryService:
# 検索フィルタ(ファイル名・メモ・タグ・キャッシュ済みプロンプト)
if search:
s = search.lower()
prompt_cache = meta.get("prompt_cache", "")
# prompt_cache未構築の場合は画像から直接読み込んでキャッシュする
if not prompt_cache and ext in (".png", ".jpg", ".jpeg"):
embedded = {}
if ext == ".png":
embedded = self._read_png_metadata(Path(abs_path))
else:
embedded = self._read_jpeg_metadata(Path(abs_path))
if embedded:
prompt_cache = " ".join(
str(v) for k, v in embedded.items()
if k != "workflow" and isinstance(v, str) and len(v) < 50_000
).strip()
if prompt_cache:
self.metadata_store.save(abs_path, {"prompt_cache": prompt_cache})
if not (
s in name.lower()
or s in item["memo"].lower()
or any(s in t.lower() for t in tags)
or s in prompt_cache.lower()
or s in meta.get("prompt_cache", "").lower()
):
continue
+27
View File
@@ -23,6 +23,8 @@ _SIDECAR_EXTENSIONS = [
_DISABLED_SUFFIX = ".disabled"
_MODEL_EXTENSIONS = {".safetensors", ".ckpt", ".pt", ".pth", ".bin", ".gguf", ".pt2"}
# ComfyUI model type → folder_paths key mapping
MODEL_TYPE_FOLDER_KEYS = {
"checkpoint": "checkpoints",
@@ -129,6 +131,31 @@ class ModelsService:
pass
return names
def list_model_files(self, model_type: str) -> list:
"""モデルタイプのモデルファイル名をソートして返す(拡張子付き、/区切り)。
プレビュー画像やサイドカーファイルを除外し、モデル拡張子のみを返す。"""
dirs = _get_model_dirs(model_type)
seen = set()
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if not f.is_file():
continue
name = f.name
if name.endswith(_DISABLED_SUFFIX):
name = name[: -len(_DISABLED_SUFFIX)]
if Path(name).suffix.lower() not in _MODEL_EXTENSIONS:
continue
try:
rel = str(f.relative_to(d)).replace("\\", "/")
if rel.endswith(_DISABLED_SUFFIX):
rel = rel[: -len(_DISABLED_SUFFIX)]
seen.add(rel)
except ValueError:
pass
return sorted(seen)
def get_model_groups(self, model_type=None):
data = self._load_metadata()
raw = data.get("_groups", {})
+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.3.49"
version = "0.3.52"
license = "MIT"
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+12 -4
View File
@@ -90,11 +90,16 @@ export const comfyUI = {
if (info?.[cls]?.input?.required?.[inputKey]) {
const inputDef = info[cls].input.required[inputKey];
const first = inputDef[0];
// V1: [["model1", "model2"], {}]
if (Array.isArray(first)) return first;
// Newer ComfyUI format: ["COMBO", { "values": [...] }]
// V2: ["COMBO", { "values": [...] }]
if (typeof first === "string" && Array.isArray(inputDef[1]?.values)) {
return inputDef[1].values;
}
// V3 ComfyNode: ["COMBO", { "options": [...] }]
if (typeof first === "string" && Array.isArray(inputDef[1]?.options)) {
return inputDef[1].options;
}
}
} catch {}
}
@@ -148,14 +153,17 @@ export const comfyUI = {
},
async fetchEmbeddings() {
// ComfyUI exposes embeddings via /embeddings endpoint
// Use WFS backend API (reliable, goes through same aiohttp server)
try {
const res = await fetch(`${this.baseUrl}/embeddings`);
const res = await fetch("/api/wfm/models/files?type=embedding");
if (res.ok) {
const list = await res.json();
return Array.isArray(list) ? list : [];
}
} catch {}
console.warn("[WFS] /api/wfm/models/files?type=embedding returned", res.status);
} catch (e) {
console.error("[WFS] fetchEmbeddings error:", e);
}
return [];
},
+158 -4
View File
@@ -10,6 +10,8 @@ import { syncJsonHighlight } from "./json-highlight.js";
let _stackStrengths = {};
// { modelFullPath: boolean } — true = active (default)
let _stackActive = {};
// { id: string|null, selStart: number, selEnd: number }
let _lastPromptFocus = { id: null, selStart: 0, selEnd: 0 };
function _loraBasename(fullPath) {
const name = (fullPath || "").replace(/\\/g, "/").split("/").pop() || fullPath;
@@ -123,6 +125,8 @@ export const comfyEditor = {
diffusionModels: [],
textEncoders: [],
controlNets: [],
hypernetworks: [],
embeddings: [],
samplers: [],
schedulers: [],
lastError: null,
@@ -130,13 +134,15 @@ export const comfyEditor = {
async loadModelLists() {
try {
const [ckpt, vae, lora, diff, enc, cn, samp, sched] = await Promise.all([
const [ckpt, vae, lora, diff, enc, cn, hn, emb, samp, sched] = await Promise.all([
comfyUI.fetchCheckpoints(),
comfyUI.fetchVaes(),
comfyUI.fetchLoras(),
comfyUI.fetchDiffusionModels(),
comfyUI.fetchTextEncoders(),
comfyUI.fetchControlNets(),
comfyUI.fetchHypernetworks(),
comfyUI.fetchEmbeddings(),
comfyUI.fetchSamplers(),
comfyUI.fetchSchedulers(),
]);
@@ -146,6 +152,8 @@ export const comfyEditor = {
this.models.diffusionModels = diff;
this.models.textEncoders = enc;
this.models.controlNets = cn;
this.models.hypernetworks = hn;
this.models.embeddings = emb;
this.models.samplers = samp;
this.models.schedulers = sched;
this.models.lastError = null;
@@ -171,6 +179,7 @@ export const comfyEditor = {
const positiveNodes = (analysis.prompt_nodes || []).filter((n) => n.role === "positive");
const negativeNodes = (analysis.prompt_nodes || []).filter((n) => n.role === "negative");
const nodeOpts = _nodeOptions(analysis.all_nodes);
const embeddings = this.models.embeddings || [];
el.innerHTML = `
<div class="wfm-form-group">
@@ -182,7 +191,7 @@ export const comfyEditor = {
</select>
<button class="wfm-btn wfm-btn-sm" id="wfm-prompt-pos-apply">Apply</button>
</div>
<textarea class="wfm-textarea" id="wfm-prompt-pos-text" rows="8">${positiveNodes[0]?.text || ""}</textarea>
<textarea class="wfm-textarea" id="wfm-prompt-pos-text" rows="6">${positiveNodes[0]?.text || ""}</textarea>
</div>
<div class="wfm-form-group">
<label>Negative Prompt</label>
@@ -195,6 +204,18 @@ export const comfyEditor = {
</div>
<textarea class="wfm-textarea" id="wfm-prompt-neg-text" rows="6">${negativeNodes[0]?.text || ""}</textarea>
</div>
<div class="wfm-form-group" style="border-top:1px solid var(--wfm-border);margin-top:12px;padding-top:12px;">
<label>Embeddings</label>
<input type="text" class="wfm-input" id="wfm-embedding-filter" placeholder="Filter..." style="margin-bottom:4px;">
<select class="wfm-select" id="wfm-embedding-select" style="margin-bottom:4px;">
${embeddings.map((m) => `<option value="${m}">${m}</option>`).join("")}
</select>
<div style="display:flex;gap:6px;align-items:center;margin-top:4px;">
<label style="font-size:12px;white-space:nowrap;color:var(--wfm-text-secondary);">Weight</label>
<input type="number" class="wfm-input" id="wfm-embedding-weight" value="1.0" step="0.1" min="-10" max="10" style="width:70px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-embedding-paste">Paste</button>
</div>
</div>
`;
document.getElementById("wfm-prompt-pos-apply")?.addEventListener("click", () => {
@@ -218,6 +239,63 @@ export const comfyEditor = {
_syncRawJson();
}
});
// Track last focused prompt textarea for Paste button
["wfm-prompt-pos-text", "wfm-prompt-neg-text"].forEach((taId) => {
const ta = document.getElementById(taId);
if (!ta) return;
["click", "keyup", "blur"].forEach((evt) => {
ta.addEventListener(evt, () => {
_lastPromptFocus = { id: taId, selStart: ta.selectionStart, selEnd: ta.selectionEnd };
});
});
});
// Embedding filter
document.getElementById("wfm-embedding-filter")?.addEventListener("input", (e) => {
const filter = e.target.value.toLowerCase();
const select = document.getElementById("wfm-embedding-select");
if (!select) return;
select.innerHTML = (this.models.embeddings || [])
.filter((m) => m.toLowerCase().includes(filter))
.map((m) => `<option value="${m}">${m}</option>`)
.join("");
});
// Embedding Paste button — inserts at cursor position of last focused prompt textarea
document.getElementById("wfm-embedding-paste")?.addEventListener("click", () => {
const select = document.getElementById("wfm-embedding-select");
if (!select?.value) return;
const rawWeight = parseFloat(document.getElementById("wfm-embedding-weight")?.value);
const weight = isNaN(rawWeight) ? 1.0 : rawWeight;
const stem = select.value.replace(/\\/g, "/").split("/").pop().replace(/\.[^.]+$/, "");
const weightStr = Number.isInteger(weight) ? `${weight}.0` : String(weight);
const syntax = `(embedding:${stem}:${weightStr})`;
const targetId = _lastPromptFocus.id === "wfm-prompt-neg-text" ? "wfm-prompt-neg-text" : "wfm-prompt-pos-text";
const promptType = targetId === "wfm-prompt-neg-text" ? "negative" : "positive";
const ta = document.getElementById(targetId);
if (!ta) return;
const selStart = _lastPromptFocus.id === targetId ? _lastPromptFocus.selStart : ta.value.length;
const selEnd = _lastPromptFocus.id === targetId ? _lastPromptFocus.selEnd : ta.value.length;
const before = ta.value.substring(0, selStart);
const after = ta.value.substring(selEnd);
const sep = before && !/[,\s]$/.test(before) ? ", " : "";
const newText = before + sep + syntax + after;
ta.value = newText;
const newCursor = selStart + sep.length + syntax.length;
ta.focus();
ta.setSelectionRange(newCursor, newCursor);
_lastPromptFocus = { id: targetId, selStart: newCursor, selEnd: newCursor };
const wfNode = (comfyUI.currentAnalysis?.prompt_nodes || []).find((n) => n.role === promptType);
if (wfNode && comfyUI.currentWorkflow?.[wfNode.id]) {
comfyUI.currentWorkflow[wfNode.id].inputs[wfNode.textKey || "text"] = newText;
_syncRawJson();
}
});
},
renderModelTab(analysis, containerId) {
@@ -230,6 +308,10 @@ export const comfyEditor = {
{ label: "Diffusion Model", key: "diffusionModels", nodes: analysis.diffusion_model_nodes, inputKey: "unet_name" },
{ label: "Text Encoder", key: "textEncoders", nodes: analysis.text_encoder_nodes, inputKey: "clip_name1" },
{ label: "ControlNet", key: "controlNets", nodes: analysis.controlnet_nodes, inputKey: "control_net_name" },
{
label: "Hypernetwork", key: "hypernetworks", nodes: analysis.hypernetwork_nodes, inputKey: "hypernetwork_name",
extras: [{ label: "Strength", inputKey: "strength", type: "number", defaultVal: 1.0, step: 0.01, min: -10, max: 10 }],
},
];
el.innerHTML = sections
@@ -239,6 +321,16 @@ export const comfyEditor = {
const targetOpts = s.nodes
.map((n) => `<option value="${n.id}">ID:${n.id} (${n.title})</option>`)
.join("");
const extrasHtml = (s.extras || []).map((ex) => {
const curVal = s.nodes?.[0]?.[ex.inputKey] ?? ex.defaultVal;
return `<div style="display:flex;gap:6px;align-items:center;margin-top:4px;">
<label style="font-size:12px;white-space:nowrap;color:var(--wfm-text-secondary);">${ex.label}</label>
<input type="${ex.type}" class="wfm-input wfm-model-extra" id="wfm-model-${s.key}-${ex.inputKey}"
data-key="${s.key}" data-input-key="${ex.inputKey}"
value="${curVal}" step="${ex.step}" min="${ex.min}" max="${ex.max}"
style="width:80px;">
</div>`;
}).join("");
return `
<div class="wfm-form-group" style="border-bottom:1px solid var(--wfm-border);padding-bottom:12px;">
@@ -247,7 +339,8 @@ export const comfyEditor = {
<select class="wfm-select" id="wfm-model-${s.key}" style="margin-bottom:4px;">
${models.map((m) => `<option value="${m}" ${m === currentVal ? "selected" : ""}>${m}</option>`).join("")}
</select>
<div style="display:flex;gap:8px;align-items:center;">
${extrasHtml}
<div style="display:flex;gap:8px;align-items:center;margin-top:4px;">
<select class="wfm-select" id="wfm-model-${s.key}-target" style="flex:1;">${targetOpts}</select>
<button class="wfm-btn wfm-btn-sm wfm-model-apply" data-key="${s.key}" data-input="${s.inputKey}">Apply</button>
</div>
@@ -284,6 +377,12 @@ export const comfyEditor = {
const nodeId = targetSelect.value;
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
comfyUI.currentWorkflow[nodeId].inputs[inputKey] = value;
// Apply extras (e.g. strength for Hypernetwork)
el.querySelectorAll(`.wfm-model-extra[data-key="${key}"]`).forEach((ex) => {
const exInputKey = ex.dataset.inputKey;
const exVal = parseFloat(ex.value);
if (!isNaN(exVal)) comfyUI.currentWorkflow[nodeId].inputs[exInputKey] = exVal;
});
_syncRawJson();
}
});
@@ -303,7 +402,23 @@ export const comfyEditor = {
const stackTargetOpts = loraNodes
.map((n) => `<option value="${n.id}" ${String(n.id) === String(defaultStackTarget) ? "selected" : ""}>ID:${n.id} (${n.title})</option>`)
.join("");
const currentVal = loraNodes[0]?.lora_name || "";
// currentWorkflowから直接取得(applyToGenUIによる変更を正確に反映)
let currentVal = loraNodes[0]?.lora_name || "";
const _firstLoraNode = loraNodes[0];
if (_firstLoraNode && comfyUI.currentWorkflow?.[_firstLoraNode.id]) {
const _wfNode = comfyUI.currentWorkflow[_firstLoraNode.id];
if (!_firstLoraNode.is_lora_manager) {
currentVal = _wfNode.inputs?.lora_name || currentVal;
} else {
// LoraManager: loras.__value__[0].nameからフルパスを復元
const _wfLoras = _wfNode.inputs?.loras?.__value__;
if (Array.isArray(_wfLoras) && _wfLoras.length > 0) {
const _stem = _wfLoras[0].name;
const _found = (this.models.loras || []).find(m => _loraBasename(m) === _stem);
currentVal = _found || _stem;
}
}
}
// Fetch Stack group, metadata, CivitAI cache in parallel
let stackModels = [];
@@ -360,6 +475,9 @@ export const comfyEditor = {
}).join("");
const _prevActiveTab = el.querySelector(".wfm-lora-tab-btn.active")?.dataset?.tab || "single";
// applyToGenUIで設定したSingle表示の状態を保存(再描画後に復元)
const _prevSingleSyntax = document.getElementById("wfm-lora-single-syntax")?.textContent || "";
const _prevSingleTriggers = document.getElementById("wfm-lora-single-triggers")?.innerHTML || "";
el.innerHTML = `
<div class="wfm-lora-tab-header">
@@ -439,6 +557,16 @@ export const comfyEditor = {
const _synEl = document.getElementById("wfm-lora-stack-syntax");
if (_synEl) _synEl.textContent = stackLoraSyntax || "—";
// Single: applyToGenUIで設定したsyntax/triggersを復元
if (_prevSingleSyntax && _prevSingleSyntax !== "—") {
const _sEl = document.getElementById("wfm-lora-single-syntax");
if (_sEl) _sEl.textContent = _prevSingleSyntax;
}
if (_prevSingleTriggers) {
const _tEl = document.getElementById("wfm-lora-single-triggers");
if (_tEl && !_prevSingleTriggers.includes(">—<")) _tEl.innerHTML = _prevSingleTriggers;
}
// ── Tab switching ────────────────────────────────────
el.querySelectorAll(".wfm-lora-tab-btn").forEach((btn) => {
btn.addEventListener("click", () => {
@@ -917,6 +1045,32 @@ export const comfyEditor = {
});
},
appendEmbeddingToPrompt(syntax, promptType) {
const promptNodes = (comfyUI.currentAnalysis?.prompt_nodes || []).filter((n) => n.role === promptType);
const textareaId = promptType === "positive" ? "wfm-prompt-pos-text" : "wfm-prompt-neg-text";
const textarea = document.getElementById(textareaId);
if (promptNodes.length > 0 && comfyUI.currentWorkflow) {
const node = promptNodes[0];
const wfNode = comfyUI.currentWorkflow[node.id];
if (wfNode) {
const textKey = node.textKey || "text";
const current = wfNode.inputs[textKey] || "";
const newText = current ? `${current}, ${syntax}` : syntax;
wfNode.inputs[textKey] = newText;
if (textarea) textarea.value = newText;
_syncRawJson();
return;
}
}
// Fallback: update textarea only
if (textarea) {
const current = textarea.value;
textarea.value = current ? `${current}, ${syntax}` : syntax;
}
},
switchLoraSingleTab() {
const container = document.getElementById("wfm-gen-lora-fields");
if (!container) return;
+10
View File
@@ -490,6 +490,7 @@ export const comfyWorkflow = {
text_encoder_nodes: [],
diffusion_model_nodes: [],
controlnet_nodes: [],
hypernetwork_nodes: [],
all_nodes: [],
};
@@ -815,6 +816,15 @@ export const comfyWorkflow = {
control_net_name: inputs.control_net_name,
});
}
// --- Hypernetwork loader nodes ---
if (ct === "HypernetworkLoader") {
result.hypernetwork_nodes.push({
id, type: ct, title,
hypernetwork_name: inputs.hypernetwork_name,
strength: inputs.strength ?? 1.0,
});
}
}
result.all_nodes.sort((a, b) => Number(a.id) - Number(b.id));
+9 -9
View File
@@ -601,8 +601,8 @@ const LANGUAGES = {
helpGen1: "Connect/disconnect ComfyUI and check connection status",
helpGen2: "Load workflows from Workflow tab (App format .app.json not supported); Reset Workflow button re-reads the current workflow file from disk and reloads the editor; Save button (right end of the tab bar) saves the current workflow — including any edits made in the editor — as a new .json file to the Workflow tab; a filename dialog appears with the current workflow name as the default",
helpGen3: "5-tab layout — Input (Prompt + Image), Model, Settings, Feeder, Batch — Input/Model/Settings each include a Raw JSON column for instant preview and direct editing",
helpGen4: "Input tab: Prompt (top) and Image drag-and-drop (bottom) in the left column",
helpGen5: "Model tab: Checkpoint, VAE, LoRA (Single/Stack tabs), ControlNet, UNET, TextEncoder selectors with filter",
helpGen4: "Input tab: inner tabs — Prompt and Image (drag-and-drop upload); Prompt tab has Positive Prompt, Negative Prompt, and an Embeddings selector at the bottom — select a model, set Weight (default 1.0), then click Paste to insert (embedding:Name:weight) at the cursor position of the last focused textarea (defaults to Positive if neither is focused)",
helpGen5: "Model tab: Checkpoint, VAE, LoRA (Single/Stack tabs), ControlNet, UNET, TextEncoder, Hypernetwork (with Strength field) selectors with filter",
helpGen6: "Settings tab: KSampler and Latent Image side by side, each at 50% width",
helpGen7: "Raw JSON always visible in the right column of each tab — edit directly and Apply to reload the workflow",
helpGen8: "Seed control: random, fixed, increment, decrement",
@@ -671,7 +671,7 @@ const LANGUAGES = {
helpModels5: "CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type; preview image is automatically downloaded and saved if none exists",
helpModels6: "Detail modal: preview image, CivitAI info (base model, trained words, tags), thumbnail change — upload any image format; changes take effect immediately; broken/empty preview files are automatically skipped",
helpModels7: "Group management: create, rename, delete groups and assign/remove models",
helpModels8: "GenUI Model button: applies the selected model to the workflow node; LoRA additionally switches to the Single tab, disables all Stack models, and shows LORA SYNTAX / TRIGGER WORDS (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)",
helpModels8: "GenUI Model button: applies the selected model to the workflow node (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder / Hypernetwork); LoRA additionally switches to the Single tab, disables all Stack models, and shows LORA SYNTAX / TRIGGER WORDS; Embedding tab shows GenUI PP / GenUI NP buttons instead — appends (embedding:Name:1.0) to the Positive or Negative prompt",
helpModels9: "User-defined badges: assign free-label badges with custom colors shared with the Workflow tab",
helpModels10: "Enable/Disable models: toggle visibility in ComfyUI by renaming file extension (.disabled suffix). Disable per model (⏸ button on each card) or per group (Enable All / Disable All in Group panel). Changes take effect after ComfyUI refresh.",
helpModels11: "Multi-select & bulk operations: click Select to enter selection mode, check multiple models, then use the bulk action bar to add/remove from groups or permanently delete files (model file + preview images + sidecar files such as .json/.info).",
@@ -1480,8 +1480,8 @@ const LANGUAGES = {
helpGen1: "ComfyUIの接続・切断、接続状態の確認",
helpGen2: "Workflowタブからワークフローを読み込み(App形式 .app.json は非対応)。Reset Workflowボタンは現在のワークフローファイルをディスクから再読込してエディタをリロード。Saveボタン(タブバー右端)はエディタでの編集を含む現在のワークフローを新しい.jsonファイルとしてWorkflowタブに保存(現在のワークフロー名を初期値としたファイル名ダイアログを表示)",
helpGen3: "5タブ構成 — Input(プロンプト+画像)、Model、Settings、Feeder、Batch — Input/Model/SettingsタブにはRaw JSON列を常時表示",
helpGen4: "Inputタブ:左列にPrompt(上段)+ Image ドラッグ&ドロップ(下段)",
helpGen5: "Modelタブ:Checkpoint/VAE/LoRA(Single/Stackタブ)/ControlNet/UNET/TextEncoderのセレクタ(フィルタ検索付き)",
helpGen4: "Inputタブ:Prompt・Imageの内部タブ切り替え;PromptタブにはPositive Prompt・Negative Promptに加え最下部にEmbeddingsセレクタを表示(Filter+セレクト+Weight入力+Pasteボタン)— Pasteは最後にフォーカスしたテキストエリアのカーソル位置に(embedding:Name:weight)を挿入(未フォーカス時はPositiveに追加)",
helpGen5: "Modelタブ:Checkpoint/VAE/LoRA(Single/Stackタブ)/ControlNet/UNET/TextEncoder/Hypernetwork(Strength入力付き)のセレクタ(フィルタ検索付き)",
helpGen6: "Settingsタブ:KSamplerとLatent Imageを横並び(各50%幅)",
helpGen7: "Raw JSONを各タブの右列に常時表示 — 直接編集してApplyでワークフロー即時反映",
helpGen8: "シード管理:ランダム / 固定 / 増加 / 減少",
@@ -1550,7 +1550,7 @@ const LANGUAGES = {
helpModels5: "CivitAI連携:SHA256ハッシュでモデル情報取得、モデルタイプごとの一括取得;プレビュー画像がない場合は自動でダウンロード・保存",
helpModels6: "詳細モーダル:プレビュー画像、CivitAI情報(ベースモデル、トリガーワード、タグ)、サムネイル変更 — 任意の画像形式をアップロード可能;ComfyUI再起動なしで即時反映;破損/空のプレビューファイルは自動スキップ",
helpModels7: "グループ管理:グループの作成・名前変更・削除、モデルの割り当て・解除",
helpModels8: "GenUI Modelボタン:選択モデルをワークフローノードに適用。LoRAはSingleタブへ切り替え・Stack全無効化・LORA SYNTAX/TRIGGER WORDSをLoRAペインに表示(Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)",
helpModels8: "GenUI Modelボタン:選択モデルをワークフローノードに適用(Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder / Hypernetwork);LoRAはSingleタブへ切り替え・Stack全無効化・LORA SYNTAX/TRIGGER WORDSをLoRAペインに表示;EmbeddingタイプはGenUI PP / GenUI NPボタンを表示 — (embedding:Name:1.0)形式でPositive/Negativeプロンプトの末尾に追加",
helpModels9: "ユーザー定義バッジ:自由ラベルのバッジをモデルに付与(Workflowタブと色パレットを共有)",
helpModels10: "モデルの有効/無効切り替え:拡張子リネーム(.disabledサフィックス)でComfyUIへの表示を制御。各カードの⏸ボタンで単体操作、グループパネルの「全て有効化 / 全て無効化」でグループ一括操作。変更はComfyUIリフレッシュ後に反映。",
helpModels11: "複数選択と一括操作:「選択」ボタンで選択モードに入り複数モデルにチェックを入れると、一括操作バーからグループへの追加/削除、またはファイルの完全削除(モデルファイル+プレビュー画像+.json/.infoなどのサイドカーファイル)が行えます。",
@@ -2359,8 +2359,8 @@ const LANGUAGES = {
helpGen1: "连接/断开ComfyUI,检查连接状态",
helpGen2: "从工作流标签页加载工作流(不支持App格式.app.json)。Reset Workflow按钮从磁盘重新读取当前工作流文件并重新加载编辑器。Save按钮(标签栏右端)将当前工作流(包括在编辑器中所做的编辑)保存为新的.json文件到工作流标签页;会显示以当前工作流名称为默认值的文件名对话框",
helpGen3: "5标签布局 — Input(提示词+图像)、Model、Settings、Feeder、Batch — Input/Model/Settings各含实时预览和直接编辑的Raw JSON列",
helpGen4: "Input标签:左列为Prompt(上)+ Image拖放(下)",
helpGen5: "Model标签:Checkpoint/VAE/LoRA(Single/Stack标签)/ControlNet/UNET/TextEncoder选择器(含筛选)",
helpGen4: "Input标签:含Prompt和Image子标签(拖放上传);Prompt标签显示Positive Prompt、Negative Prompt,以及底部的Embeddings选择器(过滤+下拉+权重+Paste按钮)— Paste将(embedding:Name:weight)插入最后聚焦文本框的光标位置(未聚焦时默认追加到Positive)",
helpGen5: "Model标签:Checkpoint/VAE/LoRA(Single/Stack标签)/ControlNet/UNET/TextEncoder/Hypernetwork(带Strength输入)选择器(含筛选)",
helpGen6: "Settings标签:KSampler与Latent Image并排显示(各占50%宽度)",
helpGen7: "Raw JSON在每个标签右列常驻显示 — 直接编辑并Apply即时重载工作流",
helpGen8: "种子管理:随机/固定/递增/递减",
@@ -2429,7 +2429,7 @@ const LANGUAGES = {
helpModels5: "CivitAI集成:通过SHA256哈希获取模型信息,按模型类型批量获取;无预览图时自动下载并保存",
helpModels6: "详情弹窗:预览图片、CivitAI信息(基础模型、触发词、标签)、缩略图更改 — 可上传任意格式图片;无需重启ComfyUI立即生效;损坏/空预览文件自动跳过",
helpModels7: "分组管理:创建、重命名、删除分组,分配/移除模型",
helpModels8: "GenUI Model按钮:将选中模型应用到工作流节点;LoRA还会切换到Single标签、禁用所有Stack模型并在LoRA面板显示LORA SYNTAX/TRIGGER WORDS(Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)",
helpModels8: "GenUI Model按钮:将选中模型应用到工作流节点(Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder / Hypernetwork);LoRA还会切换到Single标签、禁用所有Stack模型并在LoRA面板显示LORA SYNTAX/TRIGGER WORDS;Embedding标签改为显示GenUI PP / GenUI NP按钮 — 以(embedding:Name:1.0)格式追加到Positive或Negative提示词末尾",
helpModels9: "用户自定义徽章:为模型添加自由标签徽章(颜色调色板与Workflow标签共享)",
helpModels10: "模型启用/禁用:通过重命名文件扩展名(添加.disabled后缀)控制ComfyUI中的显示。点击每个卡片上的⏸按钮单独操作,或在分组面板中使用「全部启用/全部禁用」进行批量操作。更改在刷新ComfyUI后生效。",
helpModels11: "多选与批量操作:点击「选择」按钮进入选择模式,勾选多个模型后,可通过批量操作栏将其添加/移出分组,或永久删除文件(模型文件+预览图+.json/.info等附属文件)。",
+84 -14
View File
@@ -77,12 +77,13 @@ const TYPE_LABELS = {
// Mapping from models-tab type → comfyui-editor key + inputKey
const GENUI_TYPE_MAP = {
checkpoint: { key: "checkpoints", inputKey: "ckpt_name" },
lora: { key: "loras", inputKey: "lora_name" },
vae: { key: "vaes", inputKey: "vae_name" },
controlnet: { key: "controlNets", inputKey: "control_net_name" },
unet: { key: "diffusionModels",inputKey: "unet_name" },
textencoder: { key: "textEncoders", inputKey: "clip_name1" },
checkpoint: { key: "checkpoints", inputKey: "ckpt_name" },
lora: { key: "loras", inputKey: "lora_name" },
vae: { key: "vaes", inputKey: "vae_name" },
controlnet: { key: "controlNets", inputKey: "control_net_name" },
unet: { key: "diffusionModels",inputKey: "unet_name" },
textencoder: { key: "textEncoders", inputKey: "clip_name1" },
hypernetwork: { key: "hypernetworks", inputKey: "hypernetwork_name" },
};
function applyToGenUI(modelName, modelType) {
@@ -188,6 +189,17 @@ function applyToGenUI(modelName, modelType) {
showToast(`${TYPE_LABELS[modelType]}: ${modelName.split("/").pop().split("\\").pop()}`, "success");
}
function applyEmbeddingToPrompt(modelName, promptType) {
if (!comfyUI.currentWorkflow) {
showToast(t("modelsGenUINoWorkflow"), "warning");
return;
}
const stem = modelName.replace(/\\/g, "/").split("/").pop().replace(/\.[^.]+$/, "");
const syntax = `(embedding:${stem}:1.0)`;
comfyEditor.appendEmbeddingToPrompt(syntax, promptType);
showToast(`Embedding → ${promptType === "positive" ? "PP" : "NP"}: ${stem}`, "success");
}
// User-defined badge colors (stored in metadata per model)
// Global badge palette: label → color, stored in localStorage
function getBadgePalette() {
@@ -1349,9 +1361,12 @@ function openDetailModal(modelName) {
</section>
<div class="wfm-modal-actions">
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-modal-model-save">${t("modelsSave")}</button>
${GENUI_TYPE_MAP[state.activeModelType]
? `<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-model" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
: ""}
${state.activeModelType === "embedding"
? `<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-pp" title="Positive Promptにエンベッディング追加">GenUI PP</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-np" title="Negative Promptにエンベッディング追加">GenUI NP</button>`
: (GENUI_TYPE_MAP[state.activeModelType]
? `<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-model" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
: "")}
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-modal-model-delete" style="margin-left:auto;">${t("modelsDelete")}</button>
</div>
</div>
@@ -1402,10 +1417,16 @@ function openDetailModal(modelName) {
renderModelGrid();
});
// GenUI Model button
// GenUI Model / Embedding buttons
document.getElementById("wfm-modal-genui-model")?.addEventListener("click", () => {
applyToGenUI(modelName, state.activeModelType);
});
document.getElementById("wfm-modal-genui-pp")?.addEventListener("click", () => {
applyEmbeddingToPrompt(modelName, "positive");
});
document.getElementById("wfm-modal-genui-np")?.addEventListener("click", () => {
applyEmbeddingToPrompt(modelName, "negative");
});
// Delete model button
document.getElementById("wfm-modal-model-delete")?.addEventListener("click", async () => {
@@ -1500,6 +1521,29 @@ function showSidePanel(modelName) {
const civitaiEl = document.getElementById("wfm-models-side-civitai");
if (civitaiEl) civitaiEl.style.display = "block";
const genuiNavBtn = document.getElementById("wfm-side-genui-nav-btn");
const genuiNpBtn = document.getElementById("wfm-side-genui-np-btn");
if (genuiNavBtn) {
if (state.activeModelType === "embedding") {
genuiNavBtn.textContent = "GenUI PP";
genuiNavBtn.title = "Positive Promptにエンベッディング追加";
genuiNavBtn.style.display = "";
if (genuiNpBtn) {
genuiNpBtn.textContent = "GenUI NP";
genuiNpBtn.title = "Negative Promptにエンベッディング追加";
genuiNpBtn.style.display = "";
}
} else if (GENUI_TYPE_MAP[state.activeModelType]) {
genuiNavBtn.textContent = t("modelsGenUIBtn");
genuiNavBtn.title = t("modelsGenUITitle");
genuiNavBtn.style.display = "";
if (genuiNpBtn) genuiNpBtn.style.display = "none";
} else {
genuiNavBtn.style.display = "none";
if (genuiNpBtn) genuiNpBtn.style.display = "none";
}
}
renderSideInfo(modelName);
renderSideGroup(modelName);
renderSideCivitai(modelName);
@@ -1512,6 +1556,10 @@ function closeSidePanel() {
document.querySelectorAll("#wfm-models-grid .wfm-card, #wfm-models-grid .wfm-models-table-row").forEach((el) => {
el.classList.remove("wfm-card-selected");
});
const npBtn = document.getElementById("wfm-side-genui-np-btn");
if (npBtn) npBtn.style.display = "none";
const ppBtn = document.getElementById("wfm-side-genui-nav-btn");
if (ppBtn) ppBtn.style.display = "none";
}
// ── Side Panel: Info Tab ──────────────────────────────────
@@ -1561,9 +1609,12 @@ function renderSideInfo(modelName) {
</div>
<div class="wfm-node-detail-section" style="display:flex;gap:6px;">
<button id="wfm-models-side-save-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">${t("modelsSave")}</button>
${GENUI_TYPE_MAP[state.activeModelType]
? `<button id="wfm-models-side-genui-btn" class="wfm-btn wfm-btn-sm" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
: ""}
${state.activeModelType === "embedding"
? `<button id="wfm-models-side-genui-pp-btn" class="wfm-btn wfm-btn-sm" title="Positive Promptにエンベッディング追加">GenUI PP</button>
<button id="wfm-models-side-genui-np-btn" class="wfm-btn wfm-btn-sm" title="Negative Promptにエンベッディング追加">GenUI NP</button>`
: (GENUI_TYPE_MAP[state.activeModelType]
? `<button id="wfm-models-side-genui-btn" class="wfm-btn wfm-btn-sm" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
: "")}
</div>`;
// Load preview image
@@ -1618,10 +1669,16 @@ function renderSideInfo(modelName) {
});
});
// GenUI Model button
// GenUI Model / Embedding buttons
el.querySelector("#wfm-models-side-genui-btn")?.addEventListener("click", () => {
applyToGenUI(modelName, state.activeModelType);
});
el.querySelector("#wfm-models-side-genui-pp-btn")?.addEventListener("click", () => {
applyEmbeddingToPrompt(modelName, "positive");
});
el.querySelector("#wfm-models-side-genui-np-btn")?.addEventListener("click", () => {
applyEmbeddingToPrompt(modelName, "negative");
});
}
// ── Side Panel: Group Tab ─────────────────────────────────
@@ -2378,6 +2435,19 @@ export function initModelsTab() {
});
});
// GenUI Model / Embedding buttons in side tab nav
document.getElementById("wfm-side-genui-nav-btn")?.addEventListener("click", () => {
if (!state.selectedModel) return;
if (state.activeModelType === "embedding") {
applyEmbeddingToPrompt(state.selectedModel, "positive");
} else {
applyToGenUI(state.selectedModel, state.activeModelType);
}
});
document.getElementById("wfm-side-genui-np-btn")?.addEventListener("click", () => {
if (state.selectedModel) applyEmbeddingToPrompt(state.selectedModel, "negative");
});
// Initialize badge filter bar
renderBadgeFilter();
+5 -3
View File
@@ -233,6 +233,8 @@
<button class="wfm-models-side-tab-btn active" data-side-tab="info">Info</button>
<button class="wfm-models-side-tab-btn" data-side-tab="group">Group</button>
<button class="wfm-models-side-tab-btn" data-side-tab="civitai">CivitAI</button>
<button id="wfm-side-genui-nav-btn" class="wfm-btn wfm-btn-sm" style="display:none;margin-left:auto;align-self:center;margin-right:4px;"></button>
<button id="wfm-side-genui-np-btn" class="wfm-btn wfm-btn-sm" style="display:none;align-self:center;margin-right:6px;"></button>
</div>
<!-- Info Tab -->
<div id="wfm-models-side-info" class="wfm-models-side-content active" style="overflow-y:auto;padding:12px;">
@@ -1034,8 +1036,8 @@
<li id="wfm-help-gen-1">Connect/disconnect ComfyUI and check connection status</li>
<li id="wfm-help-gen-2">Load workflows from Workflow tab (App format .app.json not supported); Reset Workflow button re-reads the current workflow file from disk and reloads the editor; <b>Save</b> button (right end of the tab bar) saves the current workflow — including any edits made in the editor — as a new .json file to the Workflow tab; a filename dialog appears with the current workflow name as the default</li>
<li id="wfm-help-gen-3">5-tab layout — Input (Prompt + Image), Model, Settings, Feeder, Batch — Input/Model/Settings each include a Raw JSON column for instant preview and direct editing</li>
<li id="wfm-help-gen-4">Input tab: inner tabs — Prompt (positive/negative textboxes with doubled height) and Image (drag-and-drop upload); switch between tabs with the tab bar at the top of the left column</li>
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; LoRA Stack — Apply writes all active LoRAs to the target node and simultaneously inserts LoRA syntax and CivitAI trigger words into the Positive prompt; re-applying updates the prompt by removing inactive LoRAs and re-adding active ones</li>
<li id="wfm-help-gen-4">Input tab: inner tabs — <b>Prompt</b> and <b>Image</b> (drag-and-drop upload); Prompt tab has Positive Prompt, Negative Prompt, and an <b>Embeddings</b> selector at the bottom — select a model, set Weight (default 1.0), then click <b>Paste</b> to insert <code>(embedding:Name:weight)</code> at the cursor position of the last focused textarea (defaults to Positive if neither is focused)</li>
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder, <b>Hypernetwork</b> (with Strength field) selectors with filter; LoRA Stack — Apply writes all active LoRAs to the target node and simultaneously inserts LoRA syntax and CivitAI trigger words into the Positive prompt; re-applying updates the prompt by removing inactive LoRAs and re-adding active ones</li>
<li id="wfm-help-gen-6">Settings tab: KSampler and Latent Image side by side, each at 50% width</li>
<li id="wfm-help-gen-7">Raw JSON always visible in the right column of each tab — edit directly and Apply to reload the workflow</li>
<li id="wfm-help-gen-8">Seed control: random, fixed, increment, decrement — seed input and mode selector stacked vertically for readability</li>
@@ -1183,7 +1185,7 @@
<li id="wfm-help-models-5">CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type</li>
<li id="wfm-help-models-6">Detail modal: preview image, CivitAI info (base model, trained words, tags), thumbnail change — upload any image format to replace the preview; changes take effect immediately without restarting ComfyUI; broken/empty preview files are automatically skipped; Delete button permanently removes the model file and all associated sidecar files</li>
<li id="wfm-help-models-7">Group management: create, rename, delete groups and assign/remove models; Checkpoint and LoRA tabs support B (Batch) and S (Stack) quick-assign buttons per model in both card and table views</li>
<li id="wfm-help-models-8">GenUI Model button: apply the selected model to the corresponding node in GenerateUI's current workflow (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)</li>
<li id="wfm-help-models-8">GenUI Model button: apply the selected model to the corresponding node in GenerateUI's current workflow (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder / Hypernetwork); <b>Embedding</b> tab shows <b>GenUI PP</b> / <b>GenUI NP</b> buttons instead — appends <code>(embedding:Name:1.0)</code> to the Positive or Negative prompt of the loaded workflow</li>
<li id="wfm-help-models-9">User-defined badges: assign free-label badges with custom colors shared with the Workflow tab</li>
<li id="wfm-help-models-10">Enable/Disable models: toggle visibility in ComfyUI by renaming file extension (.disabled suffix). Disable per model (⏸ button on each card) or per group (Enable All / Disable All in Group panel). Changes take effect after ComfyUI refresh.</li>
<li id="wfm-help-models-11">Multi-select &amp; bulk operations: click Select (green) to enter selection mode, then check multiple models; the bulk action bar is organized into three rows — <b>Group row:</b> select an existing group and Add/Remove, or type a new name and Create &amp; Add; <b>Badge row:</b> select a badge and +Badge / −Badge to apply or remove; <b>File row:</b> select a destination subfolder (or type a new folder name) and Move to relocate model files with all sidecar files (.preview.png, .json, .civitai.info, etc.), Delete Files to permanently remove selected models; header row provides Deselect All and ★/☆ Favorite toggles</li>