Compare commits

...
194 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 5 f9dbf3f399 release: v0.6.2 — Image Editタブにペンタブレット筆圧対応とFillツール(バケツ塗りつぶし)を追加
Draw/MaskツールをPointer Events化し、ペン筆圧でブラシサイズ/不透明度が
変化するように対応(マウス操作の挙動は変更なし)。Comic CreatorのImageタブ
から移植したFillツール(バケツ塗りつぶし、Solid/Gradient対応)を新規追加。
実機フィードバックを受け、Fillのグラデーションランプ/方向ダイヤルが
ペンタブレットで操作できない不具合も追加修正。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 09:25:36 +09:00
ketle-manandClaude Sonnet 5 a99bfc19a1 release: v0.6.1 — Galleryタブ検索の停止不具合・パフォーマンス問題を修正
検索欄のdebounce/AbortController追加、メタデータストアのロック保持時間短縮、
ponyxlWildcardsVaultフォールバック探索でのVaultフォルダ誤検出によるglob多発を解消。
53枚フォルダへの検索が3327ms→74msに改善。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 16:57:19 +09:00
ketle-manandClaude Sonnet 5 d75a9c812f release: v0.6.0 — Gallery/Image EditにPSD(Photoshop)対応を追加、Image Editのアクションバー/レイヤーパネル改善
- Gallery: 複数選択画像を1つのレイヤー付きPSDにまとめる「PSD作成」一括操作を追加
- Image Edit: Save PSD(レイヤー個別保持で書き出し)/Open PSD(レイヤー分解して読込)を追加
- Gallery→Image Edit: 複数選択画像を各レイヤーとして一括転送する「レイヤーとして編集」を追加
- Gallery: .psdファイルの一覧・サムネイル・プレビュー表示に対応(psd-tools合成→PNGキャッシュ)
- 実機発覚バグ2件を修正: サムネイル配信がイベントループをブロックする問題(run_in_executor化)、
  単一画像送信ボタンでPSDが1レイヤーに潰れる問題
- Image Edit: File Open改名、Open PSD配置、Close/複製レイヤーボタン追加、レイヤーヘッダー2段化
- ヘルプドキュメント更新+検証中に見つかった既存の翻訳漏れ/重複定義を修正
- 依存関係: psd-tools>=1.10を追加(pytoshopはWindowsでCコンパイラ必須のため不採用)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 20:22:41 +09:00
ketle-man 925a249cbe chore: v0.5.8リリース準備
Tagger DBタブの一括削除機能(PR #2)追加に伴うバージョン更新
2026-09-02 01:19:13 +09:00
ketle-man e067f34cd4 Merge pull request #2 from censor-ed/feature/tagger-bulk-delete
検証済み: バックエンドAPI・フロントエンドの動作を実機(ComfyUI + ブラウザ)で確認。一括削除時のcount不整合と全選択チェックボックスのトグル挙動の2点を修正コミットで追加。
2026-09-02 01:10:37 +09:00
ketle-man 995e98e1aa fix(tagger): 一括削除のcount不整合と全選択トグルの挙動を修正
- handle_db_delete_bulk: レスポンスのcountを渡されたID数ではなく
  実際の削除件数(delete_bulkの戻り値)にする
- _dbToggleSelection: 常時反転するトグル方式ではなく、クリック後の
  ヘッダーチェックボックス自身の状態に全行を揃える一般的な全選択挙動にする
2026-09-02 01:05:14 +09:00
censor-ed 398be43060 feat(tagger): Tagger DBの複数選択削除を追加 2026-09-01 10:53:27 +09:00
ketle-manandClaude Sonnet 5 1155cf1233 release: v0.5.7 — Video Planタブの設定項目レイアウト刷新(MiniMax H3 Turbo/LTX-2.5 Prompt Enhance/Wan2.2 Turbo対応) + フルバックアップのドキュメント修正
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:00:36 +09:00
ketle-manandClaude Sonnet 5 5aef634115 fix(tagger): WD Tagger系ONNXモデルの画像前処理をWD Tagger標準に修正
wd-swinv2-tagger-v3等で画像内容と一致しない不自然なタグが出力される問題を修正(Issue #1)。
単純リサイズ+RGBのまま0.0-1.0正規化だった前処理を、WD Tagger系標準の
アスペクト比維持パディング+RGB→BGR+0-255のfloat32のまま、に変更した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 16:54:27 +09:00
ketle-manandClaude Sonnet 5 b09cd2ef90 release: v0.5.5 — Videoタブ全面刷新(Plan/Asset/Editバッチ生成 + Projectサブタブ + プレビュー2ペイン化) + Video Assets/Video Temp運用整理 + Galleryメタデータ消失バグ根本修正
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 15:30:28 +09:00
ketle-manandClaude Sonnet 5 426f27c05a Video: __VideoAssets__グループがGallery再起動後に消えるバグを修正
__VideoAssets__はバッチ実行側からensure_groupを呼ぶコードが無く、一度削除されると
add_to_groupが個別画像への書き込みのみ行いレジストリを再登録しないため二度と一覧・
詳細パネルに出てこなくなっていた。ensureFeederGroup()と同型のensureVideoGroup()を
新設し、Video AssetタブのInitで確実に再登録するよう修正。詳細はDEVLOG.md参照。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 00:30:22 +09:00
ketle-manandClaude Sonnet 5 336e37724f Video: Plan/Asset/Editタブによるバッチ動画生成機能を追加
タイムラインブロック単位でFirst/Last画像・プロンプトを設定しバッチ生成するPlanタブ、
Galleryのグループ機能を再利用したAssetタブ(__VideoAssets__/__vtemp__)を新設。
調査過程でGalleryのジャンクションフォルダ環境でのパス不一致バグ、グループフィルタの
非再帰スキャンバグ、convertUiToApi()のCOMBO無警告フォールバックによるチェイン画像
すり替えバグの3件も修正。詳細はDEVLOG.md参照。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-30 22:15:01 +09:00
ketle-manandClaude Sonnet 5 7274017347 release: v0.5.4 — GenerateUIタブのLTX-2.5/Wan2.2対応 + VideoタブのLTX-2.5/Wan2.2対応・ハイライト表示 + RAW JSON検索の意図しない編集を修正
- GenerateUIタブ: LTX-2.5/Wan2.2ワークフローのPositive/Negative Prompt検出(LTXVDualCFGGuider/
  LTXVConditioning対応)とSettingsタブLatent Image検出(EmptyHunyuanLatentVideo/EmptyLTXVLatentVideo
  + Lengthフィールド)を追加、isVideoWorkflow()の動画タイムアウト判定も拡張
- Videoタブ: 該当項目のラベルをGenerateUI Modelタブと同じ色でハイライト表示する機能を追加
  (Wan2.2など操作不可な項目は非ハイライトのまま)
- 生成UIタブRAW JSON検索: ヒット箇所へのフォーカス/selectionRange設定を廃止し、ハイライト表示のみ
  に変更(検索直後のキー入力で意図せずJSONが編集される問題を修正)
- 別セッションでのVideoタブLTX-2.5/Wan2.2対応(サブグラフ入力labelベースの汎用検出)・MultiType
  ウィジェット脱落バグ修正・動画再生ボリューム保存設定、およびAI Assistant設定のUnsloth対応・
  Prompt/Tagger独立モーダル化・モデルアンロード機能を本リリースに統合
- ヘルプ(index.html/i18n.js 3言語/app.js helpIdMap)とREADME.md/DEVLOG.mdを更新

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 16:50:30 +09:00
ketle-manandClaude Sonnet 5 b94ab48ca4 AI Assistant設定をUnsloth対応+Prompt/Tagger独立モーダル化、モデルアンロード機能を追加
- Prompt AI/Tagger VLMにUnslothバックエンドを追加(サーバー側プロキシでAPIキー付与)
- Taggerタブ: Ollama直呼び出しを廃止しOllama/LM Studio/Lemonade/Unsloth共通のvlm_models/vlm_predictに統一、API URL直接入力欄を廃止
- 中央Settingsタブの「AI Assistant Settings」を廃止し、Prompt/Tagger各タブに⚙設定ボタン+モーダル(ai-settings-modal.js)を新設、それぞれ独立したlocalStorageキーで管理
- Thinking mode / Max tokens をPrompt/Tagger双方の生成呼び出しに反映(Tagger側はPython側のvlm_predictにも反映)
- Ollama/LM Studio/Lemonadeのモデルアンロード機能を追加(AI TOOL設定にもUnloadボタンを追加、Unslothは非対応として明示)
- ヘルプタブ(Prompt/Settings/AI TOOL/Tagger)の説明文を新仕様に合わせて更新(EN/JA/ZH)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 13:17:03 +09:00
ketle-manandClaude Sonnet 5 ed3512d269 ci: publish-node-actionのバージョンをSHA固定(サプライチェーン対策)
@mainの可変ブランチ参照はComfy-Org/publish-node-actionが更新された際に
挙動が変わりうるため、リリースタグ1.0.1のコミットSHAに固定する。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 10:24:53 +09:00
ketle-manandClaude Sonnet 5 9ed91e64f8 Video: LTX-2.5 / Wan2.2対応 + 動画音量の保存設定を追加
- VideoタブがLTX-2.5 (Text/Image/First&Last-Frame to Video) とWan2.2 (Text to
  Video) を検出・読み込み・生成できるよう汎用化。従来MiniMax H3専用だったノード
  検出/フォーム反映ロジックを、サブグラフが公開する入力のlabelベースで意味的に
  スロットを特定する方式に一般化した
- convertUiToApi(): object_infoの複合型宣言(例 "FLOAT,INT")がウィジェット名
  リストから丸ごと脱落し、後続ウィジェットの値がずれるバグを修正。
  LTXVEmptyLatentAudio.batch_sizeに誤った値が注入され動画生成が
  "Expected size 1 but got size 25" で失敗する原因だった
- Videoタブのminimax_test.json自動読み込みを廃止(同梱していないため)
- 動画再生ボリュームを設定タブに追加し、Video/Galleryの全プレーヤー間で
  保存・共有されるようにした(動画を切り替えるたびに最大音量へ戻る問題を解消)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 00:51:09 +09:00
ketle-manandClaude Sonnet 5 c0db7374b7 release: v0.5.3 — Labタブのワークフロー切替時の表示残留を修正 + Galleryタブ読み込み高速化・rootフォルダ自動展開 + READMEスクリーンショット刷新
- Labタブ: ワークフロー読み込み時、Labサブタブが既にアクティブでも
  Setting 1のライブ反映セルを再描画するよう修正(前ワークフローの表示残留を解消)
- Galleryタブ: フォルダスキャン時の不要なPath.resolve()呼び出しを除去し
  9,777枚のフォルダで7.5秒→0.14秒に高速化。os.walk()ベースの再帰スキャンも
  DirEntryベースに書き換え
- Galleryタブ: フォルダツリーのrootをデフォルト展開状態に変更
- README: スクリーンショット5件を削除、Video/Lab/AI TOOLタブの新規4枚を追加

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 16:08:24 +09:00
ketle-manandClaude Sonnet 5 cd4b721d51 release: v0.5.2 — GenerateUI/Labタブの動画ワークフロー対応 + VideoタブにFrame抽出/GIF変換機能 + データ管理監査とZIPフルバックアップ + Send to LI node統一
- GenerateUI/LabタブでMiniMax H3等のオールインワン動画ノードのプロンプト・画像を編集可能に(analyzeWorkflow拡張)、生成タイムアウト延長、動画結果プレビュー対応
- バグ修正: Lab index imageが真っ黒になる問題(動画は最終フレームを抽出して描画)
- バグ修正: Lab Ksampler列が動画ワークフローでも表示される問題(内部SamplerCustomAdvancedを編集対象から除外)
- Videoタブに Frame抽出(クライアント側canvas)/ アニメーションGIF変換(サーバー側PyAV+Pillow)を追加、Video Sourceパネルでプレビュー統合
- データ管理: civitai_cache.jsonのエクスポート漏れを修正、ZIP形式のフルバックアップ機能を新規実装(ai_skills/lab_plan/style/tagger.db対応、Zip Slip対策、デフォルトワークフロー/wildcardフォルダのオプトイン・復元除外)
- Image Edit/Galleryタブの画像送信ボタンを「Send to LI node」に統一し、Galleryタブにも追加
- Galleryタブの✕クリアボタンを表示形式切替ボタンの左隣に移動

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 13:27:12 +09:00
ketle-manandClaude Sonnet 5 46c789c492 release: v0.5.1 — mp4動画の埋め込みメタデータ対応 + Gallery Infoタブに寸法/再生時間表示 + MiniMax H3等オールインワン動画ノードのプロンプト抽出バグ修正
Gallery Prompt/JSONタブ・Metadataサブタブ・サイドパネルIタブの3箇所で、ComfyUIのSaveVideoがmp4のmoov/udta/metaに埋め込むworkflow/promptタグ(PNGのtEXtチャンクと同一キー名)を読み取れるようにした。バックエンドはPyAV、Metadataサブタブ/サイドパネルIタブはブラウザ側でMP4ボックス構造を直接パースする実装。副産物として、CLIPTextEncode系を介さず自ノードのprompt入力に直接テキストを持つ動画生成オールインワンノード(MiniMaxH3ImageToVideo等)のプロンプトが抽出できていなかったバグも修正。Gallery Infoタブには画像の幅×高さ・動画の再生時間の表示を追加。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 21:04:48 +09:00
ketle-man ede39ec715 release: v0.5.0 — mp4動画Gallery対応 + Videoタブ新設(MiniMax H3専用) + バグ修正: Galleryのタグ/メモが再起動後に消える
- Galleryタブでmp4動画の閲覧・再生・サムネイル生成(PyAV)に対応
- 新規Videoタブ(MiniMax H3専用、GenerateUIとは独立)を3ペイン構成で追加
  - first_frame/last_frameは両方optional、LoadImageノードの無いワークフローにも対応
  - Workflowタブから「Load in Video」で読み込み可能
- バグ修正: cleanup_stale_images()が非再帰スキャン時にサブフォルダ内画像/動画のメタデータを誤って全削除していた問題を修正
- バグ修正: Gallery側のタグ/メモ保存がサーバーエラーをサイレントに無視していた問題を修正
2026-08-27 14:46:09 +09:00
ketle-manandClaude Sonnet 5 ad3b380929 Save to Input(旧Send to ComfyUI)ボタンを削除
Send to Workflowと機能が重複していたため、Image Editタブの
「Save to Input」ボタン・uploadToComfyUI()を削除。ヘルプ・README・
i18n(日英中)を更新。次回リリース時にバージョンを上げて反映する。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 12:10:32 +09:00
ketle-manandClaude Sonnet 5 c589e562e4 release: v0.4.8 — LabにPromptグループ一括適用+キーフレーム並べ替え + デフォルトワークフロー上書き保存バグ修正 + StyleテーブルAdd to this file
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 12:16:06 +09:00
ketle-manandClaude Sonnet 5 cb61dc61a7 release: v0.4.7 — Prompt Tab内部整理 + Gallery Promptタブ新設 + Send to Canvas改善 + Presetsソート
- prompt-tab.js(1545行)をprompt-presets/ai-chat/wildcards/styles.jsの4ファイルに分割、
  prompt-tab.jsは薄いオーケストレーターに(prompt-table.js/app.jsは無変更でre-export経由)
- ワイルドカード入力支援ツールバーをPresetsのプロンプト編集モーダルへ追加(Wildcardモーダル
  ではなくプロンプトを書く場所に付けるべきという指摘を受けて再配置)
- Style適用とワイルドカード展開の実行順序を修正: Style内の__file__参照が展開されずに
  送信されていたバグを解消(Style適用→展開の順に変更)
- yamlワイルドカード(ImpactWildcardEncode)を使うサンプルワークフローを追加
- Galleryタブ詳細パネルに「Prompt」タブを新設(既定選択、Metadataタブと同じPOS/NEGリスト
  UIを再利用); Gallery側のプロンプト抽出はAPI形式優先のprompt_workflowを新設し、
  Metadataタブとの抽出結果の食い違いを解消
- Send to Canvasのフォールバックを、Workflow Studio LibraryのWタブを絞り込み表示する
  方式に統一(UI形式のタイトルドラッグ・API形式非対応だった従来方式を置き換え)
- PresetsテーブルツールバーにMarkdown ★/Bソートトグルボタンを追加(複合ソート対応)
- graphifyの運用を一時停止(CLAUDE.md、ユーザー指示による)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 12:19:09 +09:00
ketle-manandClaude Sonnet 5 ad9d06d3e1 graphify: v0.4.6の変更を反映しナレッジグラフを更新
v0.4.6(Metadataタブ移動・GenerateUI Save非表示・Prompt Table表示)で
変更した20ファイルをgraphify --updateで再抽出。
2320ノード・5560エッジ・157コミュニティ(旧グラフから+141ノード/+314エッジ、
重複ノード13件を整理)。DEVLOG.index.md/README.index.mdの2件はOllamaの
出力トークン上限で今回は未反映(次回--updateで再試行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 20:33:26 +09:00
ketle-manandClaude Sonnet 5 ea408690ff release: v0.4.6 — MetadataタブをGalleryへ統合 + PromptタブにTable表示を新設
- MetadataタブをGalleryタブのサブタブ(Style_Catalog右隣)へ移動
- GenerateUI: Batch/LabサブタブでSaveボタンを非表示化
- Promptタブ: Form/Table切替を追加。Tableには編集可能な
  Presets/Presets Group/Wildcards/Styleテーブルを新設
  - #列クリックで行選択→ツールバーDelete/Deselectで一括操作
  - 番号ダブルクリックでPositive/Negative編集モーダル
  - PresetsのB列/BCボタンでBatchグループ登録
  - PP/NP Copy + グループ選択でAdd to Group(Presets Groupの
    Add Preset選択式を置き換え)
- ヘルプ(index.html + i18n.js 3言語 + helpIdMap)とREADMEを更新

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 15:00:23 +09:00
ketle-man cbb096ec85 release: v0.4.5 — Lab Model列の無意味な空キーフレーム表示を解消(対象ノードなし時は非表示化)
対象ノード(Checkpoint/LoRA/VAE)がワークフローに存在しない列でも
Model列に常にSetting 1のキーフレーム行が表示されていた問題を修正。
Run時には何の効果も持たない死んだコントロールだったため、
_hasNodeForColumn()で判定し、対象ノードが無い列はプレースホルダー
表示にして+ボタンでの追加もブロックするようにした。
2026-08-21 20:27:05 +09:00
ketle-manandClaude Sonnet 5 99f342cc89 release: v0.4.4 — LoRAノードバイパス機能(Lab/GenerateUI Model) + Lab LoRA構文/トリガーワードのプロンプト適用 + AI TOOL Chat生成パラメータ拡張
- GenerateUI ModelタブのLoRA列にバイパストグルボタン(⛔)を追加(strength=0の簡易実装)
- Lab機能のLoRAキーフレームに「LoRAノードをバイパス」「LoRA構文/トリガーワードをポジティブプロンプトに適用」チェックボックスを追加
- AI TOOL Chatのgenerate_imageツールにsteps/cfg/sampler_name/scheduler/denoise/seed/width/height/batch_size/aspect_ratioを追加
- Resolution Selectorノード(ComfyUI組み込み)のaspect_ratio COMBO値対応
- ヘルプ(index.html/i18n.js 3言語/app.js helpIdMap)・README.md更新
- README/DEVLOG索引自動化(index.html PostToolUseフック + generate_doc_index.py)を導入

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 15:44:33 +09:00
ketle-manandClaude Sonnet 5 9681e76848 release: v0.4.3 — 共有モーダルの☆/リネーム残留バグ修正 + Lab Model列の+/-をCheckpoint/LoRA/VAEで完全独立化
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 23:44:26 +09:00
ketle-manandClaude Sonnet 5 e9fbb6dd39 release: v0.4.2 — Lab「Model」列統合(Checkpoint/LoRA Single/VAE)+ フィールド単位継承 + C/L/V表示切替
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 21:24:30 +09:00
ketle-man f858c5138a release: v0.4.1 — Mask Editor One連携ボタンを選択中ノード方式に再設計
Send to Workflowと同じ「選択中ノード優先・フォールバック」方式に
変更し、WFS生成UIタブへの事前読み込みを不要にした。
comfyUI.currentAnalysis依存を撤去し、ボタンは常時有効化。
2026-08-20 13:42:00 +09:00
ketle-man 7d9c498234 fix: Save to Inputボタンの背景色をデフォルトに戻す
改名時にwfm-btn-primaryクラスが残っており、他のアクションバー
ボタン(Save PNG/Save to Gallery/Send to Workflow)と見た目が
不揃いになっていた。
2026-08-20 12:17:49 +09:00
ketle-man d43b35dde3 chore: graphifyナレッジグラフをv0.4.0まで更新 + graphify CLAUDE.md統合
- graphify-out/: モジュール分割・Mask Editor One連携・Send to Workflow等、
  v0.4.0までの変更10ファイルを再抽出しグラフ再構築
- QWEN_CHAT_INTEGRATION_PLAN.md(未追跡の非公開プラン文書)由来の
  ノード/エッジ/ハイパーエッジを除去し、.graphifyignoreで今後も除外
- graphify claude install: CLAUDE.mdにgraphifyクエリ優先参照ルールを追記、
  .claude/settings.jsonにPreToolUseフック(graphify hook-guard)を登録
2026-08-20 12:14:48 +09:00
ketle-man b79f4e8fd0 release: v0.4.0 — モジュール分割リファクタ + Mask Editor One連携 + Send to Workflow
DEVLOGにv0.3.99以降の作業をまとめて記録:
- image-edit-tab.js / models-tab.js の低凝集度モジュール分割(前日実施分)
- Mask Editor One連携ボタン(DEVLOGフェーズ2計画の実装)
- Send to Workflowボタン追加 + Send to ComfyUI→Save to Input改名

pyproject.toml/READMEバージョンバッジをv0.4.0に更新。
push・GitHub Releaseはユーザー指示待ち。
2026-08-20 11:34:59 +09:00
ketle-man 87c53ef977 Rename Send to ComfyUI → Save to Input、Send to Workflowのヘルプ追加
- Image Edit タブの「Send to ComfyUI」ボタンを「Save to Input」に改名
  (README・ヘルプ英/日/中を追従)
- 前回追加した「Send to Workflow」ボタンのヘルプ項目が未記載だったため追加
2026-08-20 11:26:34 +09:00
ketle-man 8b75d2a8d0 Add Image Edit タブ「Send to Workflow」ボタン
Send to ComfyUI(アップロードのみ)とは別に、アップロード後の
ファイル名を ComfyUI 側で選択中のノードの image ウィジェットへ
直接書き込む機能を追加。chat_TE カスタムノードの
「Send to workflow」と同等(window.opener 経由のクロスウィンドウ
ブリッジ、Mask Editor One 連携と同じパターン)。
2026-08-20 11:15:38 +09:00
ketle-man 7aa2535964 Add Mask Editor One連携ボタン(DEVLOGフェーズ2) + ヘルプ更新
Image Edit タブの Mask ツールに「Edit in Mask Editor One →」ボタンを追加。
ワークフロー中の既存 MaskEditorOne ノードへキャンバス合成画像を送信し、
window.opener 経由で ComfyUI 側の実際のモーダルエディタを開いて編集、
Apply 後のマスクを新規マスクレイヤーとして WFS に取り込む。
2026-08-20 10:31:07 +09:00
ketle-manandClaude Sonnet 5 7769de6fbb chore: update graphify knowledge graph after models-tab.js refactor
Incremental update covering the 8 changed/new JS files from the
models-tab.js cohesion refactor (models-tab.js + 7 new models/*.js
modules). Code-only change, so semantic extraction was skipped.
2369->2378 nodes, 5401->5453 edges, 148->151 communities.

Unlike the image-edit-tab.js refactor, this one did NOT improve
cohesion: the 85 models-tab-related nodes remain a single community
(density 0.096), essentially unchanged from before the split (76 nodes,
same single community). Root cause: Phase 5 (grid-view/selection-bulk/
detail-panel) deliberately uses a circular import design rather than
one-directional callback injection, since rendering a card wires up
selection/side-panel/detail-modal handlers that in turn re-render the
grid. Files got smaller and easier to read, but the dependency graph
stayed tightly coupled - documented as a real finding, not a failure
to fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 22:21:29 +09:00
ketle-manandClaude Sonnet 5 7eafe9a684 refactor: models-tab.jsからグリッド描画/選択操作/詳細パネルをmodels/へ切り出し
低凝集度モジュール分割計画(models-tab.js側)Phase 5完了。
models/grid-view.js: グリッド描画(Thumbnail/Table)とBatch/Stack/
Favoriteトグル。
models/selection-bulk.js: 複数選択モードとバルクグループ/バッジ/
お気に入り/移動/削除操作。
models/detail-panel.js: 詳細モーダルとサイドパネルのInfo/Group/CivitAI
タブ。

この3モジュールはmodels-tab.js本体を含めた4者間で循環importする設計
にした(カード描画が選択/サイドパネル/詳細モーダルのクリックハンドラを
配線し、それらが変更後にグリッドを再描画するため、単純な一方向の依存
関係にならない)。全export/importがfunction宣言(hoisting対象)で、
相互呼び出しはすべてイベントハンドラ内(モジュール評価時ではない)に
限られるため、ES Modulesとして安全に解決される。実機でグリッド描画・
サイドパネル・複数選択・バルクバー・お気に入り/バッチトグル・詳細
モーダル開閉を確認し、循環import由来のエラーがないことを確認した。

models-tab.js: 2074→592行(約71%削減、Phase 3-5合計で2522→592行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 22:14:31 +09:00
ketle-manandClaude Sonnet 5 c9089c2892 refactor: models-tab.jsからフィルタ/ソートと共有ヘルパーをmodels/へ切り出し
低凝集度モジュール分割計画(models-tab.js側)Phase 4完了。
models/filters.js: フィルタリング(ステータス/お気に入り/バッチ/タグ/
バッジ/ディレクトリ/グループ/検索)・ソート・タグ/グループ/
ディレクトリフィルタドロップダウンの描画一式。
models/helpers.js: parseModelPath/getExtension/getStem/previewUrl/
loadPreviewImageという、以降のフェーズ(grid-view/detail-panel等)
でも共有される軽量パスヘルパーを、重複を避けるため先出しで切り出した。
(2522→2074行)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 22:01:45 +09:00
ketle-manandClaude Sonnet 5 9b3532704a refactor: models-tab.jsからバッジ機能をmodels/badges.jsへ切り出し
低凝集度モジュール分割計画(models-tab.js側)Phase 4の一部。バッジ
パレット管理・バッジHTML描画・バッジ編集モーダル・バッジフィルターバー
一式を切り出した。openBadgeEditModalはworkflow-tab.jsが直接importする
公開APIのため本体で再exportし、外部呼び出し側は無変更。renderModelGrid
(まだ本体に残るグリッド描画)への依存は循環importを避けるため
setGridChangeCallback()によるコールバック注入で解消した(2522→2300行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 21:55:08 +09:00
ketle-manandClaude Sonnet 5 f6f4b2c95c refactor: models-tab.jsから共有stateとルックアップ定数をmodels/state.jsへ切り出し
低凝集度モジュール分割計画(models-tab.js側)のPhase 3。共有state・
RESERVED_GROUPS/BATCH_MODEL_TYPES/STACK_MODEL_TYPES・FETCH_MAP/
TYPE_LABELS/GENUI_TYPE_MAPを切り出した。stateはconstのまま参照を
再代入せずプロパティ書き換えのみで運用し、ESM read-only制約を回避
している(2522→2446行)。以降のフェーズ(badges/filters/
selection-bulk/detail-panel/grid-view)はこのモジュールをimportして
共有する基盤。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 21:50:45 +09:00
ketle-manandClaude Sonnet 5 ac6a4f2dd6 chore: update graphify knowledge graph after image-edit-tab.js refactor
Incremental update covering the 6 new image-edit/*.js modules from the
cohesion refactor plus the 6 previously-hung docs (README.md, CLAUDE.md,
DEVLOG.md split into 4 parts, QWEN_CHAT_INTEGRATION_PLAN.md,
requirements.txt, publish.yml). 2094->2369 nodes, 5083->5401 edges,
112->148 communities.

Verifies the refactor's intent: each newly extracted module (GmicIntegration,
BlurTool, BgRemove, Sam3Segmentation, InpaintI2IActions, FileExport) now
forms its own high-cohesion community (density 0.18-0.48) versus the
original monolith's 0.07-0.08, while the intentionally-retained high-coupling
core (Mask Editor One dispatch, image loading) stays in one lower-cohesion
community as designed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 18:13:18 +09:00
ketle-manandClaude Sonnet 5 e6c503ef75 refactor: image-edit-tab.jsからファイル出力をFileExport.jsへ切り出し
低凝集度モジュール分割計画のPhase 2続き。レイヤー合成(maskApply対応の
書き出し用コンポジット)・PNG保存・Gallery保存・ComfyUIアップロードの
3出力先を独立クラスに切り出した。レイヤー初期化・画像ロード(_loadFile/
_loadFromDataUrl/_newCanvas)はキャンバス/Undoスタックと深く結合した
高結合コアのため本体に残置(2668→2577行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 17:25:36 +09:00
ketle-manandClaude Sonnet 5 e21f5596d8 refactor: image-edit-tab.jsからInpaint/I2I実行をInpaintI2IActions.jsへ切り出し
低凝集度モジュール分割計画のPhase 2続き。状態管理・ツールパネル描画・
Inpaint実行(ワークフロー合成/専用ワークフロー切替)・マスクなしI2I実行
一式を切り出した。gallery-tab.js(Comic Creator連携)から呼ばれる公開API
runInpaintExternal/runI2IExternalは本体に薄い委譲メソッドとして残し、
外部呼び出し側のインターフェースは変更していない(2932→2668行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 17:17:07 +09:00
ketle-manandClaude Sonnet 5 61bf2c83da refactor: image-edit-tab.jsからSAM3セグメンテーションをSam3Segmentation.jsへ切り出し
低凝集度モジュール分割計画のPhase 2続き。状態管理・可用性チェック・
セグメント実行/マスク適用ロジック・結果サムネイルパネルを独立クラスに
切り出した。マスクツールバー全体(Paint/Color/Alpha/Text/Vector/Shape/
SAM3共通の統合UI)は高結合コアとして本体に残し、SAM3固有部分のみ
インスタンス参照に置き換えている(3130→2932行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 17:11:06 +09:00
ketle-manandClaude Sonnet 5 d000219b86 refactor: image-edit-tab.jsから背景除去をBgRemove.jsへ切り出し
低凝集度モジュール分割計画のPhase 2続き。imgly(軽量ブラウザ内モデル)と
Mask Editor One連携のBiRefNetの2バックエンドを持つ背景除去一式(可用性
チェック・bgremoveツールパネルのrenderブロック・マスク合成処理)を独立
クラスとして切り出した(3304→3130行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 17:06:30 +09:00
ketle-manandClaude Sonnet 5 52ab637bd0 refactor: image-edit-tab.jsからBlur/MosaicツールをBlurTool.jsへ切り出し
低凝集度モジュール分割計画のPhase 2着手分。DrawTool等の既存ツールと同じ
onMouseDown/Move/Up/Leaveインターフェースを持つ独立クラスとして、全体/矩形
Blur・Mosaic機能一式を切り出した。ツール切替ディスパッチャーは委譲のみ残す
(3504→3304行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 17:01:01 +09:00
ketle-manandClaude Sonnet 5 5e5709594b refactor: image-edit-tab.jsからG'MIC統合をGmicIntegration.jsへ切り出し
低凝集度モジュール分割計画のPhase 1。G'MIC統合一式(状態管理・GUI起動/中断/
ジョブ待機/結果反映・filterツールのパネル描画)を独立クラスとして切り出し、
本体はコールバック注入するインスタンスを持つのみにした(3665→3504行)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 16:54:53 +09:00
ketle-manandClaude Sonnet 5 b20519c092 chore: track graphify knowledge graph, ignore cache/cost/local-path files
- Add graphify-out/{graph.json,graph.html,GRAPH_REPORT.md,manifest.json,
  .graphify_labels.json} so the knowledge graph is available to other
  clones and future sessions without rebuilding.
- .gitignore: exclude graphify-out/cost.json (churns every run),
  graphify-out/cache/ (local extraction cache, no cross-machine value),
  and graphify-out/.graphify_python|.graphify_root (machine-local paths).
- Add .claudeignore for graph.json/graphify-out/ so Claude Code's
  automatic context loading doesn't invalidate the prompt cache on
  every graphify rebuild.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 14:18:01 +09:00
ketle-manandClaude Sonnet 5 9d952c4b6e Add Unsloth backend to AI TOOL tab / sidebar A tab (v0.3.99)
Unsloth's OpenAI-compatible API always requires an API key, unlike the
existing Ollama/LM Studio/Lemonade backends, so it's relayed through a
new server-side proxy (py/routes/unsloth_routes.py) that attaches the
key from a local .env file (UNSLOTH_API_KEY, loaded via python-dotenv
in prestartup_script.py) instead of ever sending it to the browser.

Also fixes a client-controlled baseUrl SSRF that could have exfiltrated
the API key, and folds Unsloth's separate reasoning_content field back
into <think> tags so low Max tokens no longer produces silently empty
replies from reasoning models.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 17:51:13 +09:00
ketle-manandClaude Sonnet 5 8248ff8ac7 release: v0.3.98 — AI TOOL翻訳の信頼性向上 + GenerateUI Modelタブ再構成 + Thinking mode/Max tokens設定
- AI TOOL翻訳: system role対応chat APIへ切替、出力クリーニング、未翻訳検知を追加(SPA/サイドパネル両対応)
- GenerateUI Modelタブ: ワークフローに含まれる項目のハイライト色設定を追加、ControlNet/Hypernetworkを折りたたみ化、Text Encoderの表示順をControlNetより上に変更、LoRA列見出しもハイライト対応
- AI TOOL Settings: Thinking mode ON/OFF・Max tokens設定を追加(Ollama think/num_predict、LM Studio/Lemonade max_tokens、OFF時は<think>タグをクライアント側で除去)
- ヘルプタブ・README・DEVLOGを更新

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 12:27:06 +09:00
ketle-manandClaude Sonnet 5 7548c49910 release: v0.3.97 — KREA-2ワークフロー対応 + Labタブ拡張 + Input Imageプレースホルダ機能
- KREA-2ワークフロー対応で発覚した2件の既存バグ修正
  - PreviewAny/StringConcatenate中継ノードの役割伝播バグ修正
    (GenerateUI/Metadata/IタブでPositive Promptが空になる問題)
  - DynamicComboウィジェットのスロット数カウント修正
    (Prompt outputs failed validationエラーの原因)
- Labタブ: プロンプトモーダルにClear/Get from Previousボタン追加
- Labタブ: Setting 1(キーフレーム#1)の各列にGenerateUIの現在値をライブ反映
- Labタブ: 各キーフレームにBypassチェックボックス追加(Lab内部のみのスキップ機構)
- GenerateUI Input Imageサブパネル: Clear/Placeholderボタン追加
  (Color/Imageモード、設定は記憶、低頻度機能のため折りたたみ表示)
- ヘルプタブ更新(3点セット: index.html/app.js/i18n.js)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 12:39:42 +09:00
ketle-manandClaude Sonnet 5 e9f2c6171a release: v0.3.96 — カタログ作成バッチ無言停止バグ修正 + Style Catalog/Promptタブ機能拡張
- trackProgress()にタイムアウト・execution_interrupted処理・WebSocket切断時のPromise解放を追加し、
  バッチ処理が特定件数で無言のまま停止するバグを修正
- Style Catalogタブに「Load in GenerateUI」「Open in Metadata Tab」ボタンとダブルクリック拡大表示を追加
- Promptタブ右ペインにStyle管理サブタブ(Wildcardと切替式)を新設。作成・編集・削除、
  ファイル名バッジ表示、既存ファイルへの追加(+ Add to this file)に対応
- カタログ作成モーダルに「Outputフォルダにコピーを残さない」オプションを追加

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 13:47:03 +09:00
ketle-manandClaude Sonnet 5 90a7d824fb Merge feature/style-catalog-imageprompt: v0.3.95 ImagePrompt改名+Style_Catalogギャラリー
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 01:26:46 +09:00
ketle-manandClaude Sonnet 5 05e061d656 release: v0.3.95 — Style/Prompt→ImagePrompt改名 + Style_Catalogギャラリー + カタログ作成機能
Galleryタブが Output / ImagePrompt / Style_Catalog の3サブタブ構成に。既存の
Style/PromptサブタブをImagePromptへ全面改名(フォルダ ws_style_prompt→ws_image_prompt
含む)した上で、GenerateUIの登録済みStyleをプレビュー画像から視覚的に選べる
Style_Catalogサブタブを新設。

- Style_Catalogは ws_style_catalog フォルダ配下の画像を閲覧し、埋め込み
  Positive/Negativeプロンプトを表示・コピー、「Select as Style」で該当スタイルへ
  GenerateUIのStyleドロップダウンを切り替え可能
- GenerateUIに「カタログ作成」ボタンを追加。Batchタブ Styleサブタブで選択済みの
  スタイル(複数可)を対象に、現在のワークフローで順次生成しスタイル名で
  ws_style_catalog配下へ保存(既存のバッチ実行機構を再利用)。隣に「カタログ」
  ボタンでStyle_Catalogサブタブへワンクリック遷移
- Output Galleryの詳細パネルにプロンプト表示が出ていなかった不具合も併せて修正

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 01:26:41 +09:00
ketle-manandClaude Sonnet 5 5afdec395c Merge feature/style-prompt-gallery: v0.3.94 Style/Promptギャラリー追加
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:16:35 +09:00
ketle-manandClaude Sonnet 5 3ab4f3e36b release: v0.3.94 — Galleryタブをサブタブ化しStyle/Promptギャラリーを新設
Output(既存)/ Style-Prompt(新規)の2サブタブ構成に変更。Style/Promptギャラリーは
output/ws_style_prompt フォルダを対象に、フォルダツリー・サムネイル一覧・プロンプト
ビルダー(選択→追加→チップ→最終プロンプト→コピー)を提供する視覚的プロンプト作成UI。

- プロンプトは画像と同名の.txtサイドカーで保存(gallery_metadata.jsonには非依存)
- .txtサイドカーが無い画像は ponyxlWildcardsVault形式(*.yaml + thumbnails/)を
  その場で解決するフォールバックに対応(インポート不要でパックを直接閲覧可能)
- tools/import_style_prompt_seed.py でwildcardデータから画像+プロンプトの対を
  ポータブルな.txtサイドカー形式へ変換投入可能(画像データ自体はリポジトリに含めない)
- 親フォルダ選択時のサブフォルダ画像再帰表示、右ペイン2カラムレイアウトにも対応

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:16:22 +09:00
ketle-manandClaude Sonnet 5 4a23564c66 release: v0.3.93 — LabタブVAEキーフレーム不発バグ修正・Style適用UI刷新・Plan JSONスクロール同期修正・キーフレーム個別削除・Batch数超過警告・ワイルドカード対応・Save index imageデフォルトON
- VAE: 独立VAELoaderノードが無いワークフローでキーフレームが無警告で無視されるバグを修正(動的ノード注入+リンク張替え)
- Style: 上部Style有効化チェックボックスに依存しないApplyボタン+ON/OFFチェックボックス+別表示名に刷新
- Plan JSON: テキストエリアとハイライトオーバーレイのスクロール同期漏れを修正
- キーフレーム: 最後以外もモーダルから個別削除可能に
- Batch数: 既存キーフレームの回数目を下回った場合に警告トーストを追加
- ワイルドカード: Promptキーフレームでも__name__記法によるSPA側展開に対応
- Save index image to Output on Run のデフォルトをONに変更(+ Plan Clear時のチェックボックス表示ズレを修正)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-11 19:28:31 +09:00
ketle-manandClaude Sonnet 5 d8ffcc182e release: v0.3.92 — CLIPTextEncodeEditPlus実行結果不一致の根本修正(convertUiToApiのforceInput未考慮バグ)+LoRA Stack機能改善
- convertUiToApiの_getWidgetInputNames/_getWidgetInputTypesがforceInput:trueを考慮しておらず、未接続の任意入力(例: CLIPTextEncodeEditPlusのtext2)が誤ってwidgets_valuesの余分な値を吸収し送信データに紛れ込んでいたバグを修正。ComfyUI直接実行との生成結果不一致(text_edit欠落)の根本原因だった。
- Metadata/Infoタブ(metadata-tab.js, node_sets_menu.js)でCLIPTextEncodeEditPlusのtext1+text_edit+mode結合ロジック(RAW/EDIT/front/back)を追加し、ノード本体のPython実装と同じルールで正しくプロンプトを抽出するよう修正。
- GenerateUI ModelタブにLoRA Stack機能を3点改善: Use Stack Groupチェックボックス(ワークフロー実データ/Modelsタブ登録グループの切替)、複数LoRAの正しい表示、タブ切替でのON/OFF状態リセットバグ修正。
- ヘルプ(GenerateUIタブページ)にModel Tab — LoRA Detailsカードを追加(EN/JA/ZH)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 21:54:47 +09:00
ketle-man 3d5bc47e20 release: v0.3.91 — Labインデックス画像にPlanメタデータをPNG埋め込み、READMEのChangelogセクションを廃止
- Lab: インデックス画像PNG(Plan Save/Save As、Run時Output保存の両方)にPlan全体をiTXtチャンク(wfm_lab_plan)として埋め込み
- Lab: Planドロップエリアへの.pngドロップ時、埋め込みメタデータを直接読み込むように変更(対応する.jsonが無いOutputフォルダ側の画像でも読込可能に)。古い画像は従来通りサーバーへフォールバック
- README: 肥大化した Changelog セクションを削除。以後のバージョン履歴はGitHub Releaseのリリースノートで管理
- CLAUDE.md: リリース手順からREADME Changelog更新の手順を削除
2026-08-10 11:14:11 +09:00
ketle-man 35899bf53e release: v0.3.90 — Labタブにワークフロー呼び出し・T2I対応・Run時インデックス画像Output保存+Eagle連携・プラン接頭辞を追加、Galleryルート表示を簡略化
- Lab: Plan JSONに使用ワークフローファイル名を記録し、Open Workflowボタンで呼び戻し可能に
- Lab: T2I workflow (no source image) チェックボックスでソース画像なしのT2Iワークフローにも対応
- Lab: Save index image to Output on Run チェックボックスで、Run完了ごとにインデックス画像をComfyUIのOutputフォルダへ保存し、Eagle自動保存にも連携
- Lab: Plan Save/Save Asで保存されるファイル名にws_labplan_接頭辞を自動付与
- Gallery: フォルダツリーのルート表示を「[root] <フォルダ名>」から「[root]」に簡略化
- README: FeaturesセクションをタブごとにHTML detailsで折りたたみ化
2026-08-10 10:35:20 +09:00
ketle-manandClaude Sonnet 5 f356826e9f release: v0.3.89 — Lab機能への実動作確認フィードバック3件を反映(Get from Image・スタイル追記・Modelタブフィルター✕)
Get from ImageをLabタブに現在読み込まれている画像から取得する方式に変更。
スタイル適用を{prompt}置換ではなく常時カンマ区切り追記(既存プロンプトを消さない)に変更。
GenerateUI ModelタブのCheckpoint/VAE/Diffusion Model/ControlNet/Hypernetwork/Lora各フィルターに
オーバーレイ✕クリアボタンを追加。詳細はDEVLOG.md参照。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-09 19:43:33 +09:00
ketle-manandClaude Sonnet 5 003f3408fc release: v0.3.88 — Labタブ Promptセルにスタイル適用・画像/GenerateUIからのプロンプト取得、Checkpoint/VAEフィルター、Plan JSONサブタブを追加
Promptセル編集モーダルにGet from GenerateUI/Get from Image/Styleボタンを追加(Styleは
GenerateUIツールバー上部のチェックボックス・ドロップダウンをそのまま参照)。
Checkpoint/VAEセルにModelタブ同様のフィルター入力+オーバーレイ✕クリアボタンを追加。
Labに3つ目のサブタブ「Plan JSON」を新設し、現在のプランをJSONとして確認・編集・
Settingへ適用できるようにした。詳細はDEVLOG.md参照。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-09 19:16:19 +09:00
ketle-manandClaude Sonnet 5 54198f196a release: v0.3.87 — GenerateUIタブに実験的なLabサブタブ(I2Iバッチ生成・キーフレーム方式)を追加
Checkpoint/VAE/Prompt/KSamplerを列ごとに独立したキーフレームで管理し、任意の回数目から
値を変更できるI2Iバッチ生成機能。ワークフローを直接書き換えず、実行時にクローンして適用。
Plan Save/Save As/Load(json/pngドロップ対応)、画像連鎖生成、Eagle自動保存連携、
インデックス画像(最大9枚コンタクトシート)に対応。詳細はDEVLOG.md参照。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-09 12:15:07 +09:00
ketle-manandClaude Sonnet 5 3ff76aacc6 release: v0.3.86 — GalleryMetadataStoreの競合状態を修正
画像を一括生成(I2I)等でメタデータ保存リクエストが短時間に連発すると、バックグラウンドのフォルダインデックススレッドと競合し「dictionary changed size during iteration」が発生していた不具合を修正。GalleryMetadataStoreの共有辞書アクセスをthreading.RLockで保護した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 15:50:46 +09:00
ketle-manandClaude Sonnet 5 ec8be7ee6f release: v0.3.85 — Generate UI連携ブリッジ(T2I)にデフォルトワークフロー・Negative対応を追加
_wfmReceiveGenerateRequestをI2I/Inpaint連携と同じパターンに拡張し、
negative/workflowData/workflowFilename引数を追加。Comic Creator側の
「画像を一括生成」(T2I)からデフォルトワークフローを指定できるようになった。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 22:53:00 +09:00
ketle-manandClaude Sonnet 5 117fcad22a fix: release v0.3.84 — ernie_t2i.json実行時のPrompt outputs failed validationエラーを修正
サブグラフ境界のwidget値(width/height等)が複数の内部ノードへfan-outする場合
(EmptyFlux2LatentImage.widthへの実ウィジェット注入 + PreviewAny.sourceという
ウィジェット表現を持たないワイルドカード必須入力への中継)、_flattenSubgraphs
のinputPortTargetsが最後の1ターゲットで上書きされ、片方が未接続のまま
Required input is missing: sourceで検証エラーになっていた。全fan-outターゲット
を追跡し、非ウィジェット入力にはリテラル値を直接注入するよう修正。
実サーバーへの/promptバリデーションおよび実ブラウザでのGenerate実行で確認。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 21:45:00 +09:00
ketle-manandClaude Sonnet 5 feed327c23 release: v0.3.83 — Flux.2 Klein / Ernie Imageのプロンプト表示不具合を修正
CLIPTextEncode.textがPrimitiveStringMultilineへのリンク参照になっているパターン
(Metadata/IタブのresolveLinkedTextがvalueキー未対応)と、ComfySwitchNode経由で
生プロンプト/LLM強化版のどちらかに切り替わるErnie Imageのプロンプト強化トグル
(LLM出力は静的解析不能なため両分岐を辿りリテラルへ解決できる方を採用)に対応。
GenerateUIタブ・Metadataタブ・サイドパネルIタブの3箇所を修正し、実ブラウザで
3ワークフローすべての表示を確認。ヘルプにErnie Imageの表記を追加。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 19:31:37 +09:00
ketle-manandClaude Sonnet 5 82ddbb340c release: v0.3.82 — Metadata/Iタブのプロンプト抽出修正・widgets_values/Rerouteバグ修正
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 13:17:13 +09:00
ketle-manandClaude Sonnet 5 31f02962f5 ヘルプ・対応フォーマット表記にLongCat/Boogu/HiDream E1/FireRedを追加
GenerateUIタブ(helpGen2)・Metadataタブ(helpMetadata5)のヘルプ、および
Metadataタブ内の対応フォーマット補足(metaFormatTodo)を3言語(EN/JA/ZH)で更新。
併せてmetaFormatTodoにMage-Flowが未記載だった既存の抜けも修正。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 13:10:01 +09:00
ketle-manandClaude Sonnet 5 413f0d5068 MetadataタブとサイドパネルIタブのプロンプト抽出をImage Edit系ワークフローに対応
Flux.2 Klein/LongCat/Boogu/HiDream E1/FireRedをAI TOOL Chatで実際に生成し
Metadataタブで確認したところ、qwen_image_edit2509/2511・longcat・boogu・
Fireredの画像でプロンプトが表示されない問題が見つかった(同じ画像を
GenerateUIタブへ読み込むと正しく表示されるため、GenerateUIタブ側の解析
[comfyui-workflow.js]とは別に実装されているMetadataタブ独自のプロンプト
抽出ロジックが未対応と判明)。

原因は主に2点:
- PNGは`prompt`チャンク(既にAPI形式)が`workflow`チャンクより優先して読まれる
  ため、extractPromptsAPI()のtextMap構築が常に使われるが、そこは"text"/
  "text_g"キーのみを見ており、TextEncodeQwenImageEdit(Plus)/TextEncodeBooguEdit
  が使う"prompt"キーを見ていなかった。
- SamplerCustomAdvancedはpositive/negativeを直接持たずGuiderノード
  (CFGGuider/DualCFGGuider/BasicGuider)経由のため、サンプラーのinputsを
  直接見るだけのrole判定では見つけられなかった(Flux.2 Klein/HiDream E1)。

extractPromptsAPI/extractPromptsFromNodeSet双方に、guider経由のinputsを
辿る処理、TextEncodeBooguEditの1ノード2ロール(prompt/negative_prompt)対応、
InstructPixToPixConditioning経由の追加ホップ解決を追加。node_sets_menu.js
(ComfyUIサイドパネルのIタブ、web/comfyui/はESモジュールをimportできない
制約からcomfyui-workflow.js/metadata-tab.js相当のロジックを`_wfm`接頭辞で
ローカル複製している)にも同じ修正を適用。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 13:02:47 +09:00
ketle-manandClaude Sonnet 5 bec84ac30b release: v0.3.81 — Flux.2 Klein / LongCat / Boogu / HiDream E1 / FireRed Image Edit対応
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 17:40:33 +09:00
ketle-manandClaude Sonnet 5 61e16ddce0 Rerouteノードを透過解決し、hidream_comicの400エラーを修正
HiDream E1ワークフロー(hidream_comic.json)はUNETLoaderの出力をBasicScheduler/
DualCFGGuiderへ分岐させるのにRerouteノードを使っていた。RerouteはUI専用の
パススルーノードでComfyUIバックエンドにノードクラスが存在しないため、
そのままAPIペイロードに含めると「missing_node_type」の400エラーになっていた
(実機でGenerateして初めて発覚)。

_resolveBypassSource()をReroute対応に拡張し、Bypass(mode:4)ノードと同様に
配線を実際の入力元まで直結して解決するようにした。Rerouteの入力型は多くの場合
汎用型"*"のまま保存されており、Bypass用の型一致検索では見つからないため、
Reroute(常に1入力1出力)は型チェックを省略して唯一の入力を辿るようにしている。
convertUiToApi本体のノードループでもReroute自体をAPIペイロードから除外する。

実機でGenerate実行し、エラーなく生成できることを確認済み。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:39:48 +09:00
ketle-manandClaude Sonnet 5 174a67a569 LongCat/Boogu/HiDream E1/FireRedのImage Editワークフローに対応
GenerateUIタブでの検出範囲を拡張:
- TextEncodeQwenImageEdit(Plus無し版)とFluxGuidance/FluxKontextMultiReferenceLatentMethod
  のCOND_PASSTHROUGH対応(LongCat)
- SamplerCustomをSamplerCustomAdvancedと分離し、自身が持つpositive/negative/cfg/noise_seed
  を正しく読み取るよう修正、TextEncodeBooguEdit対応(Boogu)
- DualCFGGuiderをguiderとして認識(cfg_condsを代表cfg値に)、InstructPixToPixConditioning
  のrole伝播中継に対応(HiDream E1)
- KSamplerのseed/steps/cfg/denoiseがリンク(Primitive経由)で非数値の場合にundefined化

あわせて、サブグラフ展開処理(_flattenSubgraphs)のwidgets_valuesノーマライズを実機検証で
発見した既存バグごと全面的に書き直した。従来は「widgets_values長とwidget数が完全一致する
場合のみ」ノーマライズが働く設計で、seed直後のcontrol_after_generate拡張値('fixed'等)が
挟まるノード(KSampler等)では条件が成立せず、リンクされたwidget(steps/cfg等)のエントリが
除去されないまま後続処理に渡り、cfg/denoiseなどの値が一つずつズレて上書きされていた
(Flux.2 KleinのEmptyFlux2LatentImage、Firered_comicのKSamplerで実際に発生)。
_simulateWidgetValues/_stripLegacyLinkedWidgetValues/_findInjectedWidgetIndexとして、
legacy-full形式かどうかの自動判定・control_after_generate込みの正確な位置計算・注入を
共通ロジックに統一した。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 14:52:04 +09:00
ketle-manandClaude Sonnet 5 d903f33a31 Flux.2 Klein(Advanced Sampling)ワークフローのGenerateUI対応
CFGGuider+RandomNoise+SamplerCustomAdvanced+KSamplerSelect+Flux2Schedulerという
KSamplerを使わない構成を、SamplerCustomAdvanced起点でたどってSettingsパネルの
Seed/Steps/CFG/Sampler欄に集約表示・編集できるようにした。EmptyFlux2LatentImageも
Latentパネルに対応させ、GetImageSizeへリンクされたwidth/heightは空欄+説明表示にして
誤上書きを防止。CFGGuider/BasicGuiderをpositive/negative判定の起点にも追加。

あわせて実機検証で見つかった既存バグを修正:
- サブグラフ内部完結リンク(GetImageSize等)の扱いが誤り、widgets_values変換で
  batch_sizeが1024になったりCLIPTextEncodeのtextが消えたりしていた不具合
- 同ロールのプロンプトノードが複数ある場合にドロップダウン選択とテキスト内容が
  食い違う不具合
- ミュート/バイパスしたサブグラフの内部ノードにmodeが伝播せず、無効なパイプライン
  のノードがModelタブ等のデフォルト表示に紛れ込む不具合

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 15:55:55 +09:00
ketle-manandClaude Sonnet 5 afed788537 release: v0.3.80 — Comic Creator Semi-Automatic Manga bridges (LLM prompt draft + batch generate)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 14:14:55 +09:00
ketle-manandClaude Sonnet 5 ee020cb0c0 Comic Creator「半自動マンガ作成」向けブリッジを追加(LLMプロンプト下書き・バッチ画像生成)
gallery-tab.jsに_wfmReceiveLLMPromptRequest/_wfmReceiveGenerateRequestを追加。既存のI2I/Inpaint連携と同じ配置パターンで、Comic Creator側からiframe越しに呼び出される。ai-tab.jsのcallLLM/loadAiSettings/isValidBackendUrlをexportし再利用。

Comic Creator側からKaptureで実機E2E確認済み(Ollama接続でのLLM呼び出し、t2iワークフローでの画像生成とも成功)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 20:22:18 +09:00
ketle-manandClaude Sonnet 5 f6942eb7fa release: v0.3.79 — AI TOOL Chat Skills (SVG quality + Skill Creator), Help tab card redesign
- AI TOOL Chat: new "Skills" system — selectable .md system-prompt files
  (frontmatter name/description) managed in-pane via a wildcard-manager-style
  list+editor, backed by a new /api/wfm/skills service (skill_service.py /
  skill_routes.py). Bundled with two starter skills: "SVG Icon Generator"
  (explicit part-decomposition technique that fixes unrecognizable SVG output
  from smaller local models) and "Skill Creator" (a meta-skill that
  interviews the user and drafts a new skill as a ```skill block, with a
  one-click "Save as new skill" button).
- Help tab: every page now opens with a title + "Open tab" jump button and
  splits its content into topic-focused cards instead of one long bullet
  list, matching a pattern independently adopted by a sibling project that
  had in turn been modeled on this app's own help UI. Content itself is
  unchanged — only regrouped — except for fixing a duplicated Settings-pane
  bullet and filling in Tagger/Troubleshooting text that only existed in the
  i18n dictionary and never reached the page markup.
- Version bump bundles the previously-committed sidebar Info tab Mage-Flow/
  subgraph fix into this release.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-02 12:02:46 +09:00
ketle-manandClaude Sonnet 5 bdfd0edb7a Sidebar Info tab: match Metadata tab's Mage-Flow/subgraph workflow support
node_sets_menu.js duplicated a convertUiToApi()-equivalent (subgraph
flattening with outer widget value injection, DynamicCombo support) and
added TextEncodeMageFlowEdit-specific prompt handling, mirroring the
v0.3.78 Metadata tab changes — web/comfyui/ can't import static/js/
modules (different serving URL), so the same local-duplication pattern
used for AI backend URL resolution was followed here too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 18:45:10 +09:00
ketle-manandClaude Sonnet 5 e1ffadbdca release: v0.3.78 — Eagle SVG support, subgraph workflow support (Mage-Flow), structured AI summary
- Eagle integration: SVG auto-save for both standard SaveSVGNode and comfyui-tosvg's Save SVG String node
- GenerateUI/Metadata tabs: subgraph-containing workflows (Mage-Flow etc.) no longer blocked as unsupported App format; outer subgraph widget values now correctly injected into internal nodes; DynamicCombo widget type support
- Workflow tab: AI summary now uses structured analysis instead of raw JSON truncation; accurate P/I/-> node counts and format badge for newer node types
- Workflow/Gallery tabs: Send to Canvas toast now distinguishes direct-load from drag-required fallback

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 14:29:24 +09:00
ketle-manandClaude Sonnet 5 65ef71b4ad release: v0.3.77 — Gallery SVG support, Chat SVG generation without a workflow
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 16:19:19 +09:00
ketle-manandClaude Sonnet 5 49019dfb05 DEVLOGに含まれるユーザー固有のパスを汎用表現に置き換え
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-29 13:41:28 +09:00
ketle-manandClaude Sonnet 5 78d9bba904 release: v0.3.76 — Comic Creator I2I execution bridge
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-29 13:29:37 +09:00
ketle-manandClaude Sonnet 5 f8435ed770 release: v0.3.75 — Lemonade Server backend support, Bypass/Mute node fix
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-26 10:04:09 +09:00
ketle-manandClaude Sonnet 5 b2ef333dfe release: v0.3.74 — Chat image attachment (TOOLS drop zone) + I2I generation
Shares the TOOLS pane's existing image drop zone as the Chat pane's
attachment mechanism: images are sent to the LLM as vision input and,
when generate_image is called, used as the base for image-to-image
generation via a new Chat I2I Generation dedicated workflow setting.
Also adjusts chat bubble image sizing and documents verified models
(Gemma 4:e4b, Qwen 3.5:9b, Ministral 3:3b).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 19:25:53 +09:00
ketle-manandClaude Sonnet 5 dfb33e831d release: v0.3.73 — Chat image generation via Tool Calling, Default Checkpoint safeguard
Adds LLM Tool Calling-driven image generation to the AI TOOL Chat pane
(generate_image tool, GenerateUI pipeline reuse, dedicated workflow option,
allow-toggle), plus a Settings > Default Checkpoint safeguard and a fix for
convertUiToApi() silently substituting missing checkpoints without warning.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 13:03:06 +09:00
ketle-man 64c21b1224 release: v0.3.72 — Comic Creator Inpaint integration, cross-realm Blob fix 2026-07-24 10:54:17 +09:00
ketle-manandClaude Sonnet 5 8f43412e96 release: v0.3.71 — Inpaint機能追加(GenerateUI マスクスロット・Image Edit Inpaintタブ・Mask Editor One対応・専用ワークフロー)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 20:40:13 +09:00
ketle-manandClaude Sonnet 5 b1e665b46b release: v0.3.70 — Ollama summary fix, Image Edit Layer 1 + mask overlay, GenerateUI prompt revert & weight editing
- Workflow AI summary: use the Ollama URL/model saved in Settings instead of a
  hardcoded default model tag that caused a 404 against locally installed models
- Image Edit: New button now auto-adds an empty Layer 1 (matching image-load behavior)
- Image Edit: mask overlay is now shown only for the active mask layer
- GenerateUI Input: Revert button (↺) next to Apply reverts the textarea to the
  node's currently applied value
- GenerateUI Input: Ctrl+Up/Down adjusts prompt emphasis weight in (text:weight)
  syntax by ±0.05, A1111/native ComfyUI style
- Comic Creator I2I integration (window._wfmReceiveImageForI2I) carried over from
  v0.3.69 that had been implemented but not yet committed

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 00:59:41 +09:00
ketle-manandClaude Sonnet 5 335ee517cc release: v0.3.69 — Lora batch fixes, prompt auto-sync, Comic Creator Send CC
Lora batch generation:
- Fix `Prompt outputs failed validation` errors for LoRAs that actually
  exist. Root cause: ComfyUI on Windows returns `\`-separated LoRA enum
  values while WFS tracked LoRAs internally with `/`. Added a shared
  `comfyEditor.resolveLoraName()` helper and applied it consistently to
  Lora Single apply, Stack apply, the Models tab GenUI Model button, and
  Lora batch generation.
- Add a pre-flight check before batch runs on standard LoraLoader
  workflows: warns if a selected LoRA isn't yet recognized by ComfyUI's
  model list (suggests Refresh/restart) instead of silently failing
  each queued prompt.
- Batch-applied LoRAs now auto-append their `<lora:...>` syntax and
  CivitAI trained words to the Positive prompt, rebuilt from the
  original prompt each time (not accumulated), and restore the prompt
  to its pre-batch state on completion, stop, or error.

Models tab:
- Add a Close button to the model detail modal's button row (next to
  Save / GenUI PP·NP / Delete) to cut down on mouse travel during
  repeated batch edits.

Gallery tab:
- Add Send CC button (shown only when embedded as an iframe inside
  ComfyUI Comic Creator, renamed from "Comic Creater") that sends the
  selected image into Comic Creator's selected panel/overlay via its
  existing insertImageFromUrl(url) helper.

Help / docs:
- New help entry helpGen19 (EN/JA/ZH) describing the Lora batch prompt
  sync, restore, and pre-flight check behavior.
- README and DEVLOG updated for v0.3.69.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 22:21:49 +09:00
ketle-manandClaude Sonnet 5 8509eee527 release: v0.3.68 — MASK EDITOR ONE section always visible
Show the MASK EDITOR ONE / MASK EDITOR ONE (COLOR) properties section
at all times in Draw and Mask Paint mode, instead of hiding it when no
ABR brushes are imported yet. Header text is green when brushes are
available and gray otherwise, with the Select button disabled until a
brush exists. Prompted by a report that ABR brushes "don't show up" —
SAM3/BiRefNet were confirmed working; the real cause was an empty
brushes/ folder hiding the whole section.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 19:18:10 +09:00
ketle-manandClaude Sonnet 4.6 202deab5d6 release: v0.3.67 — Alt+Click Apply & Generate
GenerateUI タブの Apply ボタンを Alt+Click すると Apply と Generate を
1操作で実行できる機能を追加。

- Positive Prompt / Checkpoint / KSampler 等の Apply ボタン対象
- Apply 成功時のみ生成をトリガー(ノード未存在時は何もしない)
- カスタムイベント (wfm:apply-and-generate) 経由で循環参照を回避
- ボタンに title 属性でヒントを表示
- ヘルプ helpGen18 を EN/JA/ZH で追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 22:15:03 +09:00
ketle-manandClaude Sonnet 4.6 8a86895262 release: v0.3.66 — Mask ツール 5サブツール追加(Color / Alpha / Text / Vector / Shape)
- Image Edit — Mask Tool: 5つの新サブツールを追加(すべて Mask Editor One 不要)
  - Color: クリック位置の色類似度でマスク選択(Tolerance / Feather / Mode)
  - Alpha: 画像の透明チャンネルをマスクとして抽出(Threshold / Invert / Extract Alpha)
  - Text: テキストスタンプマスク(Font / Size / Bold / Italic / Align / Mode、Ctrl+Enter確定)
  - Vector: Catmull-Rom スプラインポリゴン(Enter 確定 / Backspace 取消 / Esc リセット)
  - Shape: 矩形・楕円ドラッグ描画(Shift で正方形/正円、青点線プレビュー)
- Image Edit — MaskEditorOneTools.js 新規作成(5クラス + MASK_TEXT_FONTS 定数)
- Image Edit — DrawTool: ABRブラシ対応(spacing / angle / sizeJitter / rotationJitter)
- Image Edit — LayerManager: マスクレイヤーサムネイルをグレースケール(黒背景)表示に変更
- Image Edit — レイヤーアイコンの明度改善(opacity 0.5 → 0.85)
- Help — Support ページに ComfyUI Image Feeder・Mask Editor One リポジトリリンク追加
- Help — ヘルプ i18n 更新(英 / 日 / 中 3言語、mask-9〜mask-13 新規追加)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 17:28:35 +09:00
ketle-manandClaude Sonnet 4.6 cbec20633e release: v0.3.65 — Mask Editor One 連携修正・トップバーアイコン修正・Mask ABRブラシ対応
- Mask Editor One store_image API フィールド名不一致修正 (image_b64 → bg_image_b64、後方互換対応)
- トップバーアイコン消滅バグ修正: MutationObserver でVue再レンダリング後もSVGを再適用
- Mask Tool ABRブラシライブラリ対応 (Mask Editor One v0.1.9+ 必須)
  - プロパティパネルに Select ボタン・Spacing・Angle・Sz Jitter・Rot. Jitter コントロール追加
  - ABRボタンをオプションバーからプロパティパネルに移動
  - ブラシサイズJitter時の0px防止 (IndexSizeError修正)
- Mask ブラシカーソルをキャンバス外では非表示に
- ヘルプ更新: Mask Tool (SAM3・ABRブラシ) / BG Remove (BiRefNet) / i18n 3言語
- README 更新: v0.3.65 / Mask Editor One 必須要件・機能説明追記
- DEVLOG 更新: v0.3.65 エントリ追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 12:04:20 +09:00
ketle-manandClaude Sonnet 4.6 8b82a3103d feat: Image Edit mask Add/Subtract, BiRefNet BG Remove, SAM3 segmentation
- LayerManager: add `operation` property (add/subtract) to mask layers with toJSON/fromJSON support and toggleOperation()
- _updateCompositeView: detect consecutive maskApply mask groups, composite with lighten(add)/destination-out(subtract) matching Mask Editor One logic
- Layer panel: A/S toggle button on mask layers (green=add, red=subtract); sync MaskTool.mode on layer select
- BG Remove: BiRefNet option via Mask Editor One API (store_image → birefnet/remove_bg → grayscale-to-RGBA)
- Mask tool: SAM3 button with text prompt, max masks selector, multi-select thumbnails, Add/Erase mode, Apply Selected
- Bugfix: maskApply mask at layers end (no target) now falls back to overlay-only instead of disappearing
- Bugfix: brush cursor dot appearing outside Image Edit tab (rect.width===0 guard)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 16:15:29 +09:00
ketle-manandClaude Sonnet 4.6 d70905d032 fix: Image Edit ツールメニューを画像読み込み前にも表示
Select/Draw/Text/Shape の _renderToolOptions 条件に
this._xxxTool の存在チェックが含まれており、画像読み込み前は
全ツールが null → else(coming soon)に落ちていた。

コンストラクタでデフォルト値で早期初期化することで修正。
_initCanvases() での再生成と衝突しない。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 14:11:00 +09:00
ketle-manandClaude Sonnet 4.6 390921a13d release: v0.3.63 — ノードタブ複数選択・全タブフィルタークリア・検索Xボタン
- Nodes tab: Ctrl+click / Shift+click multi-select with bulk action bar (add/remove/create group, bulk favorite/unfavorite)
- All tabs (Workflow/Nodes/Models/Gallery): ✕ Clear button resets all filters in one click
- All tabs: inline ✕ overlay button on search inputs clears text immediately
- Fix: node bulk bar layout collapse (moved outside flex container)
- Fix: search clear button not showing (display:'flex' instead of '')
- Fix: node card multi-selected style not applied (added .wfm-card.multi-selected to main.css)
- docs/12_Tagger.png, docs/13_ImageEdit.png added (missed in v0.3.62)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-28 13:23:15 +09:00
ketle-manandClaude Sonnet 4.6 78b34c99f7 feat: WFS_PromptText を GenerateUI Prompt タブで認識・ドロップ title 固定
- analyzeWorkflow に WFS_PromptText 検出を追加(positive/negative を個別の prompt_node として登録)
- _getWidgetMapping に WFS_PromptText フォールバックマッピングを追加(UI→API 変換対応)
- placePromptNode のドロップ時 title をプリセット名から「Wfs Prompt」固定に変更

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 21:58:27 +09:00
ketle-manandClaude Sonnet 4.6 71ed9788a6 release: v0.3.62 — Send GenUI Image ボタン追加・tagger_settings.json バグ修正
- Gallery タブツールバーに Send GenUI Image ボタンを追加(Image Edit ボタン右隣)
  選択画像を ComfyUI へアップロードし GenerateUI Input Image スロット 0 に自動適用
- tagger_settings.json がデータエクスポート対象から漏れていたバグを修正
- ヘルプ helpGallery17 を EN/JA/ZH で追加
- README: v0.3.62 Changelog・スクリーンショット(Tagger/Image Edit)追加
- DEVLOG 更新・pyproject.toml バージョン 0.3.62 に更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 18:10:47 +09:00
ketle-manandClaude Sonnet 4.6 4cfc793c76 docs: Send GenUI Image ボタンのヘルプを追加(helpGallery17)
- templates/index.html: wfm-help-gallery-17 エントリ追加
- static/js/i18n.js: helpGallery17 キー追加(EN/JA/ZH)
- static/js/app.js: helpIdMap に wfm-help-gallery-17 → helpGallery17 追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 17:54:06 +09:00
ketle-manandClaude Sonnet 4.6 a7b5667a50 feat: ギャラリータブに Send GenUI Image ボタンを追加
ギャラリーツールバーの Image Edit ボタン右隣に「Send GenUI Image」ボタンを
設置。選択中の画像をギャラリーから取得し、ComfyUI にアップロードした後、
GenerateUI タブの Input > Image スロット 0 へ自動的に適用する。

- templates/index.html: Send GenUI Image ボタン追加
- static/js/comfyui-editor.js: comfyEditor.applyImageToSlot() メソッド追加
- static/js/gallery-tab.js: comfyUI/comfyEditor をインポート、ボタンハンドラ追加
- static/js/i18n.js: galleryNoLoadImageNode / gallerySentGenUI キー追加(EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 17:49:14 +09:00
ketle-manandClaude Sonnet 4.6 1eaf4b2158 fix: tagger_settings.json をデータエクスポート/インポート対象に追加
settings_routes.py の _DATA_FILES リストから tagger_settings.json が
漏れており、データバックアップ時にTagger設定が含まれなかった。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 17:36:29 +09:00
ketle-manandClaude Sonnet 4.6 cbf35e8ddf feat: v0.3.61 — G'MIC バグ修正・セキュリティ・Draw/Mask ブラシ操作性改善
- G'MIC-Qt 引数順序修正 (-o output input が正しい順序)
- CREATE_NEW_CONSOLE フラグ追加(Windows GUI 表示に必須)
- G'MIC 設定パスのプレースホルダーを汎用パスに変更
- handle_result パストラバーサル対策(gmic_temp 外を 403 拒否)
- ヘルプ追加: G'MIC Filter 使い方・インストール手順(EN/JA/ZH)
- Draw/Mask ブラシカーソルを円形オーバーレイに変更(ブラシサイズ連動)
- キャンバス余白からのドラッグ開始対応(ie-canvas-wrap.mousedown)
- キャンバス外へのストローク継続対応(window mousemove/mouseup 追跡)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 16:43:07 +09:00
ketle-man b985f73d35 v0.3.60: Image Edit Filter Tool - G'MIC-Qt integration
Implement G'MIC-Qt filter tool in the Image Edit tab:
- Add gmic_routes.py (new): /api/wfm/gmic/open, /status/{id}, /result endpoints
- Register gmic_routes in wfm.py
- Enable Filter button in index.html (remove ie-tool-placeholder)
- Implement _gmicOpenGui, _gmicWaitForJob, _gmicApplyResult, _gmicAbort in image-edit-tab.js
- Add G'MIC-Qt path setting UI and save logic to settings-tab.js
2026-06-27 14:51:58 +09:00
ketle-manandClaude Sonnet 4.6 0d8ae03c7b feat: v0.3.59 — Image Edit Mask Tool 実装・Draw/Mask 描画バグ修正・クリッピング保存対応
- Mask Tool (🎭) 新規実装: マスクレイヤー追加(M ボタン)・プロパティペイン(Size/Hardness/Add-Erase)・ツールオプションバー(Paint/Invert/Overlay/Blur)・マスクオーバーレイ表示
- クリッピングマスク機能: ✂ ボタンで直下レイヤーをマスク範囲でクリッピング;PNG保存・Gallery・ComfyUI送信に反映
- Draw/Mask 描画バグ修正: layer.canvas 直接描画により描画中も全レイヤーが常時表示
- レイヤーパネル幅 190→220px (✂ ボタン追加による見切れ解消)
- ヘルプ更新 (EN/JA/ZH): Mask Tool カード追加・Add/Erase ボタン・✂ ボタン説明

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 12:39:34 +09:00
ketle-manandClaude Sonnet 4.6 9fa1490d4b feat: v0.3.58 — GenerateUI Model タブ GGUF対応拡張(Diffusion Model / Text Encoder)
- Diffusion Model: LoaderGGUF / LoaderGGUFAdvanced を認識、gguf_name キーを自動選択
- Text Encoder: CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF 対応
  - 単体CLIP: clip_name + type + device(GGUF only) のUI
  - DualCLIP: clip_name1 + clip_name2 + type + device(GGUF only) の2段UI
  - type選択肢を /object_info から動的取得
- Models タブ GenUI Model ボタン: unet=gguf_name / textencoder=clip_name にも対応
- ヘルプ3点セット更新(helpGen5、helpGen17・helpGallery15・16のi18n漏れ修正含む)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-27 10:49:52 +09:00
ketle-manandClaude Sonnet 4.6 3a5637a4cf feat: v0.3.57 — Image Edit Blur Tool / BG Remove Tool 追加
- Blur ツール (≈): Whole Blur / Whole Mosaic(全体適用)+ Rect Blur / Rect Mosaic(矩形ドラッグ選択)
- BG Remove ツール (⬚): Lightweight @imgly(ブラウザ内処理)+ BiRefNet stub(Python backend, coming soon)
- サイドバーの Blur / BG Remove アイコンから ie-tool-placeholder を除去(白色表示)
- ヘルプに Blur Tool / BG Remove Tool カードを追加(英語・日本語・中国語 i18n 対応)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:27:46 +09:00
ketle-manandClaude Sonnet 4.6 be66dc3d5a feat: v0.3.56 — Style機能追加(GenerateUI ツールバー & Batchタブ)
- GenerateUI ツールバーに Style チェックボックス+ドロップダウンを追加
  - user/default/Workflow-Studio/style/*.json を自動読み込み
  - {prompt} プレースホルダー置換、negative_prompt 末尾連結
  - ワークフローコピーにのみ適用(currentWorkflow は変更しない)
- Batch左ペインに Style タブを追加(全スタイルのフラットリスト、All/None)
- Batch Queue に Style 列を追加(7列目)
- GET /api/wfm/styles エンドポイントを settings_routes.py に追加
- ヘルプ・README・DEVLOG 更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:02:44 +09:00
ketle-manandClaude Sonnet 4.6 5a3d69fe14 fix(generate-tab): Batch/Stack グループをバッチ実行UIに復元
v0.3.55 で誤って追加した RESERVED フィルターを削除。
Batch/Stack はグループ削除保護のための予約グループであり、
バッチ実行選択UIに表示され選択できることが正しい動作。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 22:56:53 +09:00
ketle-manandClaude Sonnet 4.6 8c5fce77c5 feat: v0.3.55 — グループ機能バグ修正・ヘルプi18n対応
- Windows バックスラッシュ/スラッシュ不一致によるグループメンバー消失を修正
- ネットワークドライブ切断時の全消去防止(アクセス可能ディレクトリ0件ならクリーンアップスキップ)
- _scan_model_names に 30秒 TTL キャッシュ追加(起動時高負荷の解消)
- RESERVED_GROUPS (Batch/Stack) 保護バイパス修正(bulkRemoveFromGroup, renderPmGroups)
- groupFilter 陳腐化バグ修正(削除後に自動リセット)
- toggleGroupEnable 部分失敗時の状態乖離修正
- 生成UI全バッチグループから Batch/Stack 予約グループを除外
- GenerateUI LoRA グループのパス正規化追加
- batchComplete トーストを英語ハードコードから t() に変更
- Prompt tab マイグレーション時の negText 消失バグ修正
- ヘルプタブ Image Edit セクションを日本語・中国語対応(37キー×3言語追加)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 22:46:17 +09:00
ketle-manandClaude Sonnet 4.6 7360b17842 feat(image-edit): v0.3.54 — Shape ツール追加・Models overlay ボタン修正
- Image Edit タブに Shape ツール(□ / S キー)を追加
  - ShapeTool.js 新規作成: Rect / Ellipse / Line / FreeLine 対応
  - ドラッグ中は overlayCanvas に青い破線プレビュー表示
  - 確定ごとに独立した draw レイヤーとして追加(Undo 1操作で除去可)
  - Tool Options: Shape / Rounded / Fill / Stroke / Opacity / Undo
  - Line / FreeLine 時は Stroke None を非表示(常にストローク有効)
  - S キーショートカット追加
- Models タブ: Batch(B) / Stack(S) overlay ボタンが async await 後に
  e.currentTarget が null になり色が変わらないバグを修正
  → await 前に const btn = e.currentTarget で参照を保存
- ヘルプ更新: Shape ツール説明・S キーショートカットを追記
- DEVLOG / README / pyproject.toml を v0.3.54 に更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 17:24:58 +09:00
ketle-man 2ce9fb2ab9 Merge feature/image-edit-tab: v0.3.53 Image Edit Tab 強化 2026-06-25 15:16:33 +09:00
ketle-manandClaude Sonnet 4.6 baa3c32abd feat(image-edit): v0.3.53 — Image Edit Tab 強化(オブジェクト操作・レイヤーロック・ギャラリー保存)
- SelectTool: 移動・リサイズ・回転・Flip H/V によるオブジェクト操作
- TextTool: バウンディングボックスサイズで配置、リサイズ時に再描画(拡大ぼやけ防止)
- テキスト再編集: ダブルクリックで既存テキストレイヤーを再編集
- 回転ハンドル位置バグ修正: _getRotateHandle() の x 座標符号を修正
- レイヤーロック: 🔒/🔓 トグル、ロック中は SelectTool 操作無効(オレンジ表示)
- Layer 1 自動ロック: 初回画像読み込み時に誤移動を防止
- Save to Gallery ボタン: wfs-image-YYYYMMDDHHmmss デフォルト名でギャラリールートに保存
- Gallery タブ「Image Edit」ボタン追加
- Help に Image Edit ページ追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 15:16:01 +09:00
ketle-manandClaude Sonnet 4.6 5fb843c6e2 feat(image-edit): Phase 1 — Image Edit タブ追加(Draw・Text・レイヤー・保存)
- static/js/image-edit/LayerManager.js: Layer + LayerManager (追加/削除/順序/可視/不透明度/合成)
- static/js/image-edit/DrawTool.js: ソフトブラシ描画・消しゴム (PaintToolベース)
- static/js/image-edit/TextTool.js: Canvas直描きテキスト・フォント/サイズ/太字/斜体対応
- static/js/image-edit-tab.js: メインUI — ツールバー・アクションバー・ズーム/パン・Undo/Redo・PNG保存・ComfyUIアップロード・From Gallery連携
- static/css/image-edit-tab.css: タブ専用スタイル (ツールバー/キャンバス/レイヤーパネル/テキストオーバーレイ)
- templates/index.html: Image Editタブ追加 + CSS読み込み追加
- static/js/app.js: import・初期化・i18nマップ追加
- static/js/i18n.js: tabImageEdit キー追加 (3言語)

Mask/Blur/Filter/BG Removeはプレースホルダー(Phase 2以降)
キーボードショートカット: B=Draw, T=Text, Ctrl+Z=Undo, Ctrl+Y=Redo, Space+Drag=Pan, Wheel=Zoom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 12:16:04 +09:00
ketle-manandClaude Sonnet 4.6 76dc2cbbf6 feat(genui): LATENT IMAGEにプリセット機能を追加 — 正方形ボタン・解像度ドロップダウン・WHSet/HWSet・カスタムプリセット管理(+/-)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 11:51:14 +09:00
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
ketle-manandClaude Sonnet 4.6 465871b9f8 feat: GenerateUI A1111-style wildcard expansion + Gallery bug fixes (v0.3.49)
- GenerateUI: SPA-side __name__ wildcard expansion for non-ImpactWildcard nodes
  (CLIPTextEncode etc.); nested expansion up to 5 passes; ImpactWildcard* skipped
  (server-side); works in single and batch generation
- Gallery: fix Export button missing text label in bulk action bar
- Gallery: fix prompt search missing images with no cached prompt index —
  on-demand metadata read + cache build when search is active
- Help text updated (EN/JA/ZH): helpGen16 added
- Version bumped to 0.3.49

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 11:43:17 +09:00
ketle-manandClaude Sonnet 4.6 c3bee0ee09 docs: ギャラリータブの画像ダウンロード・エクスポート機能のドキュメント更新
- README.md: Gallery Tabセクションに機能説明を追加
- DEVLOG.md: v0.3.48エントリを追加(新機能の実装詳細)
- templates/index.html: ヘルプテキストを更新(wfm-help-gallery-6, -7)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 10:57:11 +09:00
ketle-manandClaude Sonnet 4.6 3dc593da4e feat: ギャラリータブに画像ダウンロードと一括エクスポート機能を追加
- 詳細パネルのプレビュー画像にマウスホバーでダウンロードアイコンをオーバーレイ表示
- 詳細パネルから単一画像をダウンロード可能に
- 複数選択メニューに「エクスポート」ボタンを追加
- 複数選択した画像をZIPファイルにしてエクスポート
- Backend: POST /wfm/gallery/images/export-zip エンドポイント実装
- Frontend: ダウンロード・ZIPエクスポート機能実装
- i18n対応: 英語/日本語/中国語

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 10:36:09 +09:00
ketle-manandClaude Sonnet 4.6 aa8c8f73fe fix: update JS group state after model file move (v0.3.47)
When models were moved to a subdirectory via bulkMoveModels, state.modelGroups
was not updated to reflect the new model paths, causing moved models to
disappear from group filter views immediately after the operation.

Added in-place rename of group members (from → to) inside the moved.forEach
loop, mirroring the server-side rename already performed by move_models in
models_service.py. Generate tab Batch groups are unaffected as they fetch
fresh from the server on each tab open.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 08:34:59 +09:00
ketle-manandClaude Sonnet 4.6 281fba373c feat: Prompt tab AI Assistant LM Studio support + Settings AI Assistant section (v0.3.46)
- Settings tab: rename "Ollama Settings" to "AI Assistant Settings (Prompt Tab)";
  add backend selector (Ollama / LM Studio), URL input, model select, Test button;
  save to localStorage wfm_prompt_ai_settings (independent of AI TOOL tab)
- Prompt tab: replace Python proxy (/api/wfm/ollama/*) with direct browser-to-backend
  calls; supports Ollama (/api/chat) and LM Studio (/v1/chat/completions);
  image attachments auto-converted to correct format per backend
- Auto-refresh model list when backend changes: sendMessage() detects mismatch
  between current backend setting and what was used to populate the dropdown,
  then re-fetches before sending to avoid stale model name errors
- i18n (EN/JA/ZH): ollamaSettings, ollamaUrl, saveOllama, ollamaSaved,
  helpPrompt1, helpSettings5, helpTrouble2 updated for dual-backend support

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 18:17:12 +09:00
ketle-manandClaude Sonnet 4.6 2b84c69ef9 feat: group stale-entry auto-cleanup + Gallery Shift+click range select (v0.3.45)
- Models tab: scan valid model files on group load, remove stale entries;
  move_models() also updates group membership for moved models
- Gallery tab (folder view): cleanup stale metadata entries after each
  folder scan, synced with 60s TTL + folder-mtime cache
- Gallery tab (group list): list_images_in_group() filters non-existent
  paths and removes them from the group in a single write
- Gallery tab: Shift+click range-selects from the last anchor item;
  works in both thumbnail and table views; anchor resets on folder
  change, reload, and Deselect All; help updated (EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 17:16:45 +09:00
ketle-manandClaude Sonnet 4.6 7523892bc2 feat: Gallery tab performance + compare mode + bulk API + help improvements (v0.3.44)
Phase 2 — Performance:
- Server-side 256px JPEG thumbnail generation (Pillow, disk cache data/thumb_cache/)
- Infinite-scroll paging: 50 images/page with IntersectionObserver sentinel
- Cache TTL extended 30s → 60s

Phase 3 — Features:
- Bulk API endpoints: POST /wfm/gallery/bulk/favorite and /wfm/gallery/bulk/group
  replace N-parallel individual requests with single-request batch operations
- Image compare mode: Ctrl+click 2–4 images → Compare button → side-by-side lightbox
  (position:fixed close button avoids overflow:auto clipping)
- Prompt search: A1111 parameters text cached as prompt_cache on detail-panel open,
  included in list_images() text search alongside filename/tag/memo

Bulk bar UI cleanup:
- Dropdown placeholder: "Add to Group..." → "Select Group"
- Button: "Add" → "Add to Group"
- New "Remove from Group" button (uses POST /wfm/gallery/bulk/group action:remove)
- Button: "Delete" → "Delete File"

Help tab (Gallery page):
- helpGallery4/6/7 updated to reflect prompt search, compare, Remove from Group,
  Delete File; EN/JA/ZH all updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 14:07:49 +09:00
ketle-manandClaude Sonnet 4.6 d8fc1b62a3 feat: Send to Canvas direct load via window.opener + API-format DnD enabled (v0.3.43)
- node_sets_menu.js: register window.wfmReceiveWorkflow() so SPA can call
  app.handleFile() directly via window.opener; remove API-format grayout
  from W-tab items (all formats now draggable and double-clickable)
- workflow-tab.js: sendToCanvas() prefers window.opener.wfmReceiveWorkflow
  over localStorage fallback; remove API-format disabled state from side
  panel and detail modal Send to Canvas buttons
- gallery-tab.js: Copy & Send Canvas prefers window.opener; remove API-
  format disabled state from _updateCopyCanvasBtn
- i18n.js: add apiFormatCanvasNoOpener key (EN/JA/ZH); update helpGallery8
  and helpSidepanel17 to reflect new direct-send behaviour
- comfyui-client.js: queuePrompt() accepts extraData; generate() passes
  extra_pnginfo so SaveImage embeds workflow metadata in output PNGs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 00:09:34 +09:00
ketle-manandClaude Sonnet 4.6 f2162844fb feat: Gallery Feeder mode + WFS_GalleryFeeder node + security fixes (v0.3.42)
- Add WFS_GalleryFeeder custom node (group_name/index/sort_mode/seed → IMAGE)
- Add Feeder tab Gallery mode ([Image Loop]/[Gallery] toggle, node selector,
  group picker, image grid with click-to-set-index, Run/Stop loop)
- Add gallery_feeder_extension.js: After Gen combo + Run/Stop widgets on
  WFS_GalleryFeeder node in ComfyUI canvas (serialize:false, waitForExecution)
- Add Gallery thumbnail F button to toggle __Feeder__ group membership (cyan overlay)
- Add __Feeder__ reserved group: rename/delete blocked (403 server + disabled UI);
  FC toolbar button clears members; ensure_group auto-creates on Feeder init
- Security: escapeHtml() applied to tag names, filenames, error messages in gallery-tab.js;
  single-quote escaping added to util.js escapeHtml
- Security: _check_path_allowed() added to save_image_meta, toggle_favorite,
  add_to_group, remove_from_group in gallery_service.py
- Security/bugfix: _init_allowed_root() in gallery_routes.py initializes _allowed_root
  at module load (settings.json → ComfyUI default); fixes serve_image 404 in
  Feeder Gallery mode and prevents list_folder_tree from overriding _allowed_root
- Bugfix: WFS_GalleryFeeder seed max 0x7FFFFFFF → 0xffffffffffffffff (KSampler parity)
- Update README, DEVLOG, pyproject.toml to v0.3.42

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 18:16:09 +09:00
ketle-manandClaude Sonnet 4.6 272de3d168 fix: ImpactWildcardEncode/Processor prompt not shown in Generate UI (v0.3.41)
- Add CLIPTextEncodeEditPlus BFS role propagation (text1/text2 inputs)
- Skip empty text_edit in CLIPTextEncodeEditPlus prompt_nodes to prevent
  blank textarea when upstream ImpactWildcard nodes supply the prompt
- Always overwrite wildcard_text from widgets[0] in convertUiToApi to
  guard against object_info widget-order differences between impact-pack versions
- Add static fallback mapping for ImpactWildcardProcessor/Encode

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:04:42 +09:00
ketle-manandClaude Sonnet 4.6 7181f4e20a feat: add Chat pane and Wildcard generation to AI TOOL tab (v0.3.40)
- AI TOOL tab: 3-pane layout expanded to 4-pane (Translation | Chat | TOOLS | Settings)
- Chat pane: multi-turn LLM conversation with history; Enter to send, Shift+Enter for newline; Clear resets history; Ollama /api/chat, LM Studio /v1/chat/completions
- TOOLS pane: new "Create wildcards" task — enter category name and count, generates plain-text entries one per line (no markdown, no numbering)
- Both features added to the Library side panel A tab (Chat sub-tab + wildcard dropdown option)
- i18n: aiStatusChatting / aiToastChatFailed / aiToastWcNoName added in EN/JA/ZH
- Help: AI TOOL tab card updated to 6 items; helpSidepanel16 updated in EN/JA/ZH

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:43:03 +09:00
ketle-manandClaude Sonnet 4.6 735e8ba876 feat: Send to Canvas button + Library title drag-to-canvas (v0.3.39)
- Workflow tab: replaced "Open in ComfyUI" with "Send to Canvas" (toolbar
  and detail modal); stores workflow JSON in localStorage for title-drag
- Gallery tab: renamed "Copy Workflow" to "Copy & Send Canvas"; copies to
  clipboard and stores for title-drag simultaneously
- Workflow Studio Library: panel title turns blue with green indicator when
  a pending workflow is stored; drag title onto canvas to load via
  app.loadGraphData(); title resets automatically after loading
- i18n: sendToCanvas / copyAndSendCanvas / workflowSentToCanvas (EN/JA/ZH)
- Help: helpWf6, helpGallery8 updated; helpSidepanel17 added (EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 21:33:13 +09:00
ketle-manandClaude Sonnet 4.6 c5a2662bef feat: add Tagger tab + GenUI:P button + ZIT workflow fix (v0.3.38)
### Tagger tab (new)
- WD Tagger (ONNX/NCHW/NHWC), SwinV2, DeepDanbooru (.h5/TF optional), Ollama VLM
- Single subtab: drag & drop / upload, 5 output targets (GenUI:P / Prompt / Gallery / File / DB)
- Batch subtab: folder processing, Save DB / Write to File / Write .txt output options
- DB subtab: searchable SQLite, row edit, CSV export
- Backend: tagger_service.py, tagger_db_service.py, tagger_routes.py (17 endpoints)
- Security: model name validation, extension allowlist, path traversal fix in gallery_service

### Tagger single — GenUI:P button
- Appends generated tags to GenerateUI positive prompt and applies to loaded workflow immediately

### GenerateUI — ZIT/Lumina2 workflow prompt fix
- Remove ConditioningZeroOut from COND_PASSTHROUGH; shared CLIPTextEncode now correctly
  gets role "positive" instead of "unknown" in ZIT workflows
- workflow_analyzer: add lumina2 → Z-IMAGE to _CLIP_TYPE_TO_MODEL

### Gallery detail panel
- Split tab row (Info/JSON/Groups) and action row (Metadata/Load GenUI/Tagger) to separate rows
- Add Tagger button (purple) to open selected image in Tagger tab
- Fix Save to Gallery: tags now stored as array (was string, broke forEach on refresh)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 15:04:42 +09:00
ketle-manandClaude Sonnet 4.6 127d85d913 feat: Select All button for Models & Gallery bulk bars, Gallery bulk bar i18n (v0.3.37)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 09:22:04 +09:00
ketle-manandClaude Fable 5 85ce2e05df fix: review fixes (Save safety, help i18n), util.js refactor, toast i18n, README refresh (v0.3.36)
- GenerateUI Save: overwrite confirmation with UI-format warning, Raw JSON
  sync, HTML-injection-safe filename input, double-submit guard
- Help i18n: v0.3.35 help updates were overwritten by stale i18n strings;
  synced helpGen2/helpModels2/helpGallery8/10 in 3 languages, registered
  missing helpIdMap entries, added helpGallery12/13
- Toast i18n: ~115 hard-coded English toasts replaced with t() (+~60 shared
  keys in EN/JA/ZH); fixed undefined Settings keys (textSize*/jsonColor*)
- Refactor: new shared util.js (escapeHtml unified across 5 files,
  readJsonStorage/getSettings replace 15 localStorage parses); sortModels
  precomputes sort keys; Gallery action buttons split from tab-button class
  (all !important CSS removed)
- README: intro rewritten around 3 pillars (Management / GenerateUI /
  Library side panel); new screenshots (LoRA Stack, Batch, Multi-select);
  WS Library image updated; pyproject description aligned

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 21:37:06 +09:00
ketle-manandClaude Sonnet 4.6 3190cc1443 feat: Models table sort, Gallery Load GenUI, GenerateUI Save button, help update (v0.3.35)
- Models tab: click column header to sort table (asc▲/desc▼/clear); active column highlighted in accent color; E/D label for Enable/Disable column
- Gallery tab: Load GenUI button loads embedded workflow into GenerateUI tab; Metadata button restyled green; warning toast if no workflow or unsupported format
- GenerateUI tab: Save button at right end of subtab row; filename dialog defaults to current workflow name; saves to Workflow tab via import API
- Help: Models tab note and Troubleshooting entry added for model loading error after move/delete (requires Hard Reset or ComfyUI restart)
- README and DEVLOG updated for v0.3.35

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 10:27:46 +09:00
ketle-manandClaude Sonnet 4.6 070e378314 feat: Models table Type/BaseModel columns, modal delete, bulk move, B/S fix, Gallery-Metadata link (v0.3.34)
- Table view: add CivitAI Type and Base Model columns between Subdirectory and Extension
- Detail modal: Delete button removes model file + all sidecar files
- Bulk action bar: file move operation (model + sidecars) with subfolder create; 3-row layout (Group/Badge/File); Select button green; dropdown width 330px; Delete Files moved to File row right end; X button removed
- B/S buttons (Checkpoint/LoRA table+card): targeted active-class toggle instead of full grid re-render; renderModelGrid only called when showBatchOnly filter is active
- Backend: GET /api/wfm/models/subdirs and POST /api/wfm/models/move with path traversal protection and _VALID_MODEL_TYPES whitelist
- Gallery: Alt+click or Metadata button opens selected image in Metadata tab via loadFileIntoMetadataTab()
- Help and DEVLOG updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 16:11:22 +09:00
ketle-manandClaude Sonnet 4.6 dbc9ff0820 fix: LoRA pane load overwrite, tab reset, Stack group visibility, CLIPTextEncodeEditPlus mapping, Stack Apply trigger words (v0.3.33)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 00:49:21 +09:00
ketle-manandClaude Sonnet 4.6 3957ec7d21 feat: Lora Loader (LoraManager) detection, M-tab Groups drop, P-tab Groups subtab (v0.3.32)
- I/Metadata tabs: detect LoRAs from Lora Loader (LoraManager) nodes in both workflow and API formats (inputs.loras.__value__)
- Fix strength parsing: use parseFloat to handle string values like "0.20" from LoraManager
- placeLoraMgrNode: sync text widget with LoRA syntax (<lora:name:s:c>) after drop
- M tab Groups: add "All N LoRAs" drag/drop item to place Lora Loader (LoraManager) with full group
- P tab: add Groups subtab (row2) showing wfm_prompt_preset_groups from localStorage
- Help (i18n.js), README, DEVLOG updated for v0.3.32

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 22:11:02 +09:00
ketle-manandClaude Sonnet 4.6 0c7ca31c99 feat: split LoRA pane into Single/Stack tabs, fix GenUI Model LoRA handling (v0.3.31)
- renderLoraPane rewritten: Single tab (filter, dropdown, M/C strength, Apply, P,
  LORA SYNTAX, TRIGGER WORDS) and Stack tab (target, Apply, P, toggle-all,
  global adj, LORA SYNTAX, TRIGGER WORDS, model list) are now independent
- _refreshLoraSingleDynamic: auto-updates LORA SYNTAX/TRIGGER WORDS on model or
  strength change in Single tab
- comfyEditor.switchLoraSingleTab() / disableAllStack() added for external access
- applyToGenUI (models-tab): now handles Lora Loader (LoraManager) via lora_nodes;
  switches to Single tab, disables Stack, updates LORA SYNTAX/TRIGGER WORDS display
- i18n helpGen5 / helpModels8 updated (EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 18:47:13 +09:00
ketle-manandClaude Sonnet 4.6 ff9df1ad92 feat: LoRA stack trigger words fix, stack refresh button, help troubleshooting (v0.3.30)
- Fix trigger words display: inactive stack models no longer contribute trigger
  words; initial render and per-model toggle/toggle-all now filter to active only
- Add LoRA column header refresh button (🔄) for manual Stack group reload
  without switching away from the Model tab
- Add help troubleshooting entry for "No such file or directory" error when
  running LoRA Stack (comfyui-lora-manager compatibility issue)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 17:00:29 +09:00
ketle-manandClaude Sonnet 4.6 c0fde1c42e feat: LoRA unified pane, Help sidebar, Feeder UI, Batch Sampler/Scheduler, LoraManager support (v0.3.29)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 15:10:00 +09:00
ketle-manandClaude Sonnet 4.6 3886ad2b42 fix: workflow batch 404 and rename double-submit bug (v0.3.23)
- fix: workflow batch used non-existent route /api/wfm/workflows/{name};
  corrected to /api/wfm/workflows/raw?filename={name}
- fix: rename modal accumulated blur listeners on #wfm-modal-title-input
  across modal opens; subsequent renames sent two requests back-to-back
  (first succeeded, second hit 409/404); store listener ref on
  titleInput._commitRename and removeEventListener before re-registering

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 17:49:59 +09:00
ketle-manandClaude Sonnet 4.6 080d75b8c4 feat: remove card view, add 4-type batch selector UI (v0.3.22)
- Remove Card view from Workflow and Models tabs (Thumbnail/Table only);
  localStorage fallback: stored "card" value defaults to "thumb"
- Replace Checkpoint Batch toggle with per-column-header checkboxes in
  Batch Queue pane (Checkpoint/Lora/Prompt/Workflow, radio behavior);
  Batch panel below Generate repurposed as status display + Pause/Stop
- Add _runBatchLoop() generic loop + _runBatchGenerate() 4-type dispatcher:
  Checkpoint (file-tree + group), Lora (group), Prompt (preset objects →
  positive/negative nodes), Workflow (group, restores original after batch)
- Remove ~86 lines of card-view CSS; keep nodes-tab card view intact
- Update help strings (EN/JA/ZH): helpWf1, helpModels2, helpGen11/13/14
- Update README features and Changelog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 16:22:29 +09:00
ketle-manandClaude Sonnet 4.6 eada3923c7 feat: CivitAI host setting, Info/Sample sub-tabs, URL fix, help i18n (v0.3.21)
- Settings tab: add civitai.com / civitai.red host selector; saved to
  settings.json and synced to localStorage for use across tabs
- CivitAI panel: split into Info / Sample sub-tabs; images moved to
  Sample tab with count in label; images open full-size in new tab
- URL fix: modelId=null entries now use /model-versions/{versionId}
  fallback (fixes all 324 existing cache entries client-side)
- Help: add helpGen12/13/14 (Batch tab panes) and helpSettings11/12/13
  (Text Size / RAW JSON Colors / CivitAI Host) with EN/JA/ZH; update
  helpGen3 (4-tab→5-tab) and helpGen11; fix JA/ZH English-mixed terms

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 22:47:21 +09:00
ketle-manandClaude Sonnet 4.6 ef0fccbd36 feat: CivitAI panel — Type/Hash display, image new-tab, URL fix, 3-state UI (v0.3.20)
- Add Type badge, Base Model row, Hash row (BLAKE3/SHA256) to CivitAI side panel
- Extract fileHashes (BLAKE3, SHA256, AutoV2 etc.) in _extract_info
- Sample images wrapped in <a target="_blank"> to open full-size in new tab
- Fix broken model page URL caused by batch POST API omitting model.id;
  fall back to top-level modelId field in _extract_info; also reconstruct
  URL client-side from modelId+versionId for existing cached data
- Add 3-state CivitAI tab UI: unchecked / checked-not-found / found
- CivitAI tab click now calls renderSideCivitai to always show latest state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 20:35:45 +09:00
ketle-manandClaude Sonnet 4.6 9564aa8c6e feat: CivitAI batch speedup, retry backoff, API key, richer metadata (v0.3.19)
- civitai_service.py: replace per-model GET with POST /model-versions/by-hash
  batch endpoint (up to 100 hashes/request); batch_fetch now runs in 2 phases:
  Phase 1 hashes all files, Phase 2 POSTs uncached hashes in one shot —
  100-model fetch drops from ~50 s to a few seconds
- Add exponential backoff retry (1s/2s/4s, max 3 attempts) for HTTP
  429/500/502/503/504 in both fetch_by_hash and _batch_fetch_post
- Add CivitAI API key support: CIVITAI_API_KEY env var takes priority over
  settings.json civitai_api_key; Bearer token added to all requests
- settings_routes.py: exclude civitai_api_key from data export bundle
- _extract_info: add nsfwLevel, air (AIR URN), stats (downloadCount/thumbsUp),
  updatedAt, publishedAt, imageDetails (url/width/height/nsfwLevel per image),
  fileMeta (fp/size/format); images URL list kept for backward compatibility
- Normalize hash casing: lowercase for cache keys, uppercase for API calls
- models-tab.js: apply data.hashes from done SSE event directly to
  state.modelMetadata to fix CivitAI tab blank after batch fetch
- settings-tab.js + i18n.js (EN/JA/ZH): add CivitAI API Key settings section

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 18:44:05 +09:00
ketle-manandClaude Sonnet 4.6 7395fe2432 feat: add Batch tab to GenerateUI, expand Models bulk actions (v0.3.18)
- GenerateUI: new Batch subtab (5th tab) with 3-pane layout —
  left pane: file-tree checkpoint selector (initially all unchecked);
  center pane: group-based selection with inner tabs (Checkpoint/Lora/
  Prompt/Workflow); right pane: live Batch Queue preview combining both
  selections with duplicates removed
- Checkpoint selector removed from right panel dropdown; Batch tab
  is now the single entry point for checkpoint selection
- Group selection state refactored from flat selectedModels Set to
  selectedGroups + partialSelections so group membership changes in the
  Models tab are always reflected without stale entries
- Models: bulk action bar adds Deselect All, bulk Favorite/Unfavorite,
  bulk +Badge/-Badge; i18n keys added for all three (EN/JA/ZH)
- civitai_service.py: remove SSL CERT_NONE fallback (v0.3.17 patch,
  SSL verification is now never disabled)
- Help, README, DEVLOG updated to v0.3.18

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 13:55:48 +09:00
ketle-manandClaude Sonnet 4.6 49e2519f89 chore: bump pyproject.toml version to 0.3.17
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 18:20:09 +09:00
ketle-manandClaude Sonnet 4.6 5390f0c94d fix: SSL cert error on CivitAI + Lora Manager UI-to-API conversion
- civitai_service: add _make_ssl_context() that tries certifi first,
  falls back to system store, then CERT_NONE with warning; fixes
  CERTIFICATE_VERIFY_FAILED on Windows Portable Python environments
- comfyui-workflow: convertUiToApi() now detects nodes with
  properties.__lm_widget_ids (Lora Loader (LoraManager)) and maps
  widgets_values via that index, wrapping the loras array as
  {"__value__": [...]} for the API format

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 18:18:10 +09:00
ketle-manandClaude Sonnet 4.6 b20f46dc93 feat: show CivitAI image as preview fallback when no local file exists
When the backend preview download fails (server-side network restriction etc.),
loadPreviewImage() now falls back to civitaiCache[sha256].images[0] so the
card and side panel always show the CivitAI image after fetching.
fetchCivitaiForModel() also refreshes the grid and side panel regardless of
preview_saved, using the CivitAI URL directly when no local file was saved.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:32:20 +09:00
ketle-manandClaude Sonnet 4.6 14c538eb55 docs: v0.3.15 README and DEVLOG update
- README: version badge 0.3.14 → 0.3.15, Sample Workflows section,
  CivitAI auto-preview note, Create Tags in TOOLS pane, v0.3.15 changelog
- DEVLOG: add 2026-05-20 v0.3.15 entry covering all three changes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:35:51 +09:00
ketle-manandClaude Sonnet 4.6 ef0017a0fc docs: update help text for CivitAI auto-preview and Create Tags
- helpModels5 (EN/JA/ZH): note that preview is auto-downloaded when missing
- helpAi3 (EN/JA/ZH): add Create Tags / タグ作成 / 标签生成 to TOOLS task list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:33:37 +09:00
ketle-manandClaude Sonnet 4.6 19e77a00db feat: add Create tags option to TOOLS pane VLM task selector
Add "Create tags" task to the VLM dropdown in both the SPA AI TOOL tab
and the Library panel A tab. Sends a prompt that asks the VLM to output
comma-separated English tags describing the image.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:31:38 +09:00
ketle-manandClaude Sonnet 4.6 826988cc0b feat: auto-save CivitAI preview image for models without preview
When fetching CivitAI info (individual or batch), if the model has no
preview image, automatically download the first CivitAI image and save
it as {model_stem}.preview.png next to the model file.

- civitai_service.py: add download_image() static method
- models_routes.py: auto-download preview in handle_civitai_fetch and
  handle_civitai_batch; batch summary includes preview_saved count
- models-tab.js: refresh side panel and grid on preview_saved=true;
  batch done toast shows "+N preview" when previews were saved

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:16:16 +09:00
ketle-manandClaude Sonnet 4.6 28bfbcda6b docs: add Sample Workflows section to README
Explains that workflows/ contains sample workflows and that some may
require additional custom nodes installable via ComfyUI Manager or git clone.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 16:54:18 +09:00
ketle-manandClaude Sonnet 4.6 6eef19e656 feat: add sample workflow files for distribution
Add workflows/ directory with 13 sample workflows (JSON + PNG thumbnails)
covering SD1.5, SDXL, DWPose, face detailer, and image editing presets.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 16:46:51 +09:00
ketle-manandClaude Sonnet 4.6 646721a5f4 docs: update DEVLOG for AI TOOL tab English label fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:54:47 +09:00
ketle-manandClaude Sonnet 4.6 4c44215f70 fix: English-only static labels for AI TOOL tab (SPA + Library panel)
- Replace all Japanese-hardcoded labels in templates/index.html AI TOOL section with English
- Replace all Japanese-hardcoded labels in node_sets_menu.js AI tab (HTML + JS toast/status strings)
- Rename VLM subtab to TOOLS in Library panel subtab list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:52:20 +09:00
ketle-manandClaude Sonnet 4.6 66f46af8b6 v0.3.14: AI TOOL tab 3-pane layout + RAW JSON color customization
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:34:17 +09:00
ketle-manandClaude Sonnet 4.6 95266a20b8 v0.3.13: AI tab (Translation, VLM, Settings) for SPA and Library panel
- Add A tab to SPA (templates/index.html) with Translation, VLM, Settings sub-tabs
- Add new static/js/ai-tab.js module (Ollama / LM Studio backends, full i18n via t())
- Add A tab to Workflow Studio Library side panel (node_sets_menu.js)
- Settings shared between SPA and Library panel via localStorage (wfm_ai_settings)
- URL security: validate backend URL with new URL() before any network call
- Rename ollamaSettings to 'Ollama Settings (Prompt Tab)' in EN/JA/ZH to distinguish from AI tab
- Add AI tab help card and helpSidepanel16 to Help tab (index.html + i18n.js + app.js)
- Update docs/6_ws_library.png, README.md (v0.3.13), DEVLOG.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 14:42:40 +09:00
ketle-manandClaude Sonnet 4.6 d54234b18d v0.3.12: Raw JSON search, workflow analyzer extended model detection, README screenshots refresh
- GenerateUI: always-visible search bar in Raw JSON panel (match count, ↑/↓ nav, Escape/✕ clear, orange/yellow highlights, scroll sync)
- workflow_analyzer: CLIPLoader type-field detection (_CLIP_TYPE_TO_MODEL), subgraph node scanning, UnetLoaderGGUF support, NewBie/Ovis/HiDream/Wan/Cosmos/Lumina added
- README: screenshots replaced with 8 feature-focused images; v0.3.12 changelog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 13:46:59 +09:00
ketle-manandClaude Sonnet 4.6 4298fd9ea2 v0.3.11: Metadata tab extended loader support + Settings text size slider
- metadata-tab.js: add UnetLoaderGGUF/UNETLoaderGGUF as Diffusion Model
  and QuadrupleCLIPLoader as Text Encoder (was already in node_sets_menu.js
  for the I tab; now consistent across both Metadata tab and side panel)
- settings-tab.js: add applyTextareaFontSize() + Text Size section (10-28px
  slider that applies to all 8 prompt/chat textareas at once)
- app.js: apply saved textareaFontSize on page load alongside theme
- templates/index.html: update help text for Metadata and Settings tabs
- README/DEVLOG: v0.3.11 documentation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 16:03:10 +09:00
ketle-manandClaude Sonnet 4.6 b8b4a65881 v0.3.10: Information tab drag-to-canvas, extended node type support, bug fixes
- Add drag & drop from I tab (model/lora/Prompts) to ComfyUI canvas
  - model sub-tab: places CheckpointLoaderSimple / VAELoader / UNETLoader / CLIPLoader
  - lora sub-tab: drag individual LoRA → LoraLoader; Multiple LORA section → Lora Loader (LoraManager)
  - Prompts sub-tab: drag prompt → CLIPTextEncode with text pre-filled
  - Double-click also places nodes at canvas center
- Add UnetLoaderGGUF / UNETLoaderGGUF detection as Diffusion Model
- Add QuadrupleCLIPLoader (HiDream, 4-CLIP workflows) detection as Text Encoder
- Fix CLIPLoader widget name in MODEL_NODE_MAP (clip_name1 → clip_name)
- Fix Information tab preview area height (fixed 110px, prevents list compression)
- Update help (index.html, app.js, i18n.js EN/JA/ZH) with new drag features
- Update README and DEVLOG for v0.3.10

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 12:25:37 +09:00
ketle-manandClaude Sonnet 4.6 0015638874 v0.3.9: side panel I tab + top bar icon fix
- Add Information (I) tab to ComfyUI side panel: drop PNG/WebP/JSON to
  inspect model, LoRA, and prompt metadata without leaving the canvas;
  sub-tabs: model / lora / Prompts with full-text preview and Copy button
- Shorten side panel tab labels to W / N / P / M / I with full name on hover
- Fix top bar icons invisible in newer ComfyUI: remove early-return guard
  that skipped SVG injection when Iconify had already converted the MDI
  class to an inline SVG; replace MutationObserver with simple rAF retry
- Update README, DEVLOG, help text (EN/JA/ZH), and index.html for v0.3.9

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 13:48:37 +09:00
ketle-manandClaude Sonnet 4.6 a48d9c1437 v0.3.8: Metadata tab - data9 workflow support and unclassified prompt text type
- Extended extractPromptsFromNodeSet to resolve link sources from any STRING-output
  node (ComfySwitchNode, PrimitiveStringMultiline, etc.) without type restriction
- Added fallback for SamplerCustomAdvanced (no positive/negative inputs): return
  textMap contents as texts[] instead of null
- Extended step4 PrimitiveStringMultiline and step7 final fallback to search
  subgraph nodes via collectAllNodes
- Added "text" prompt type (no POS/NEG badge) for cases where polarity cannot be
  determined; buildPromptItem and handleFile updated accordingly
- Added metaPromptText i18n key (EN/JA/ZH)
- Updated README (v0.3.8, feature description) and DEVLOG

Supported in data9: flux2_fp8, flux2_klein_4b_distilled, ernie_image,
qwen_image_edit_2511, wan2_2_14B_animate

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 00:32:49 +09:00
ketle-manandClaude Sonnet 4.6 48303e1452 docs: update README and DEVLOG for v0.3.7
README:
- Bump version badge to 0.3.7
- Update Metadata Tab feature section: subgraph support, expanded
  format list, updated prompt extraction description
- Add v0.3.7 changelog entry

DEVLOG:
- Append i18n/HTML text update notes to v0.3.7 entry

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 23:05:56 +09:00
ketle-manandClaude Sonnet 4.6 b0171add24 docs: update Metadata tab format note and help text (EN/JA/ZH)
- metaFormatTodo: replace "more formats planned" with note that
  Flux.2 / Qwen-Image / Z-Image subgraph workflows are now supported
- helpMetadata5: list Flux.2 / Qwen-Image / Z-Image explicitly
- Update static fallback text in index.html accordingly

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 23:03:17 +09:00
ketle-manandClaude Sonnet 4.6 7958ad1276 v0.3.7: Metadata tab support for Flux2/Qwen/Z-Image subgraph workflows
- Add extractPromptsFromNodeSet() to handle CLIPTextEncode+KSampler in
  subgraphs (definitions.subgraphs) used by official ComfyUI templates
- Add extractMarkdownNoteModels() to parse **section** → - [model](url)
  from MarkdownNote nodes as fallback model extraction
- Add PrimitiveStringMultiline prompt support (flux2-klein workflows)
- Fix extractCheckpoints/extractVAEs to use collectAllNodes() so
  subgraph loaders are included
- Restructure extractPromptsLiteGraph into 7-stage fallback chain

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 22:09:06 +09:00
ketle-manandClaude Sonnet 4.6 fa62684b2e v0.3.6: Metadata tab for PNG/WebP/JSON model and prompt extraction
- Add Metadata tab (between Prompt and Gallery) with drag-and-drop support
- Extract checkpoint, VAE, diffusion model, text encoder, LoRA from PNG/WebP/JSON
- Extract positive/negative prompts with SDXL Prompt Styler support
- One-click transfer to GenerateUI and Prompt tab presets
- Support ComfyUI LiteGraph, API format, SD WebUI, Fooocus metadata
- Add i18n (EN/JA/ZH) for all new UI elements and help card

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 21:49:38 +09:00
ketle-manandClaude Sonnet 4.6 8fcc4af262 fix: correct PublisherId to statsu for Registry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:49:52 +09:00
ketle-manandClaude Sonnet 4.6 33f1d22e30 ci: use official Comfy-Org/publish-node-action
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:46:57 +09:00
ketle-manandClaude Sonnet 4.6 184da84718 ci: pass registry token via env variable
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:40:22 +09:00
ketle-manandClaude Sonnet 4.6 e3aeec8022 ci: pipe N to skip tracking prompt in publish workflow
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:39:04 +09:00
ketle-manandClaude Sonnet 4.6 c444db45e6 ci: add GitHub Actions workflow for Registry publish
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:37:33 +09:00
ketle-manandClaude Sonnet 4.6 a1613bd1e8 chore: bump version to 0.3.5 for Registry publish
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:28:05 +09:00
ketle-manandClaude Sonnet 4.6 30162789b8 docs: add thumbnail and update Registry icon
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 09:21:44 +09:00
ketle-manandClaude Sonnet 4.6 1cd3fb3fff v0.3.5: Feeder subtab for comfyui-image-feeder + workflow analysis improvements
- Add Feeder subtab to GenerateUI: ImageFeeder node selector, all node parameters,
  folder tree, image grid with checkbox selection, preview panel, presets,
  Run/Stop loop with After gen modes (Loop / Increment / Fixed)
- Run loop captures image_loop_node_sync WebSocket messages to auto-update Index;
  uses right-pane seed settings for KSampler (fixes same-image-repeated bug)
- Improve analyzeWorkflow: BFS CONDITIONING chain expansion (5 iterations),
  CLIPTextEncodeSDXL/Refiner, SDXLPromptStyler/Advanced, KSamplerAdvanced noise_seed,
  TextEncodeQwenImageEditPlus, PrimitiveStringMultiline, Power Lora Loader (rgthree),
  Checkpoint Loader (WAS) with space in class name
- Fix KSamplerAdvanced seed key via data-seed-key attribute in editor
- Add Help card for Feeder subtab with EN/JA/ZH i18n
- Update README to v0.3.5, add Feeder subtab section and changelog entry
- Update DEVLOG with full implementation notes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 19:11:25 +09:00
ketle-manandClaude Sonnet 4.6 5b087713b9 v0.3.4: Checkpoint Batch folder-tree dropdown, Pause/Resume, Settings side-by-side layout
- Checkpoint Batch: replace Include/Exclude text inputs with folder-tree dropdown
  - Folder-level checkboxes with indeterminate state for partial selection
  - Expand/collapse folders with ▶; supports any subfolder depth
  - Filter search, All / None quick-select buttons
- Checkpoint Batch: add Pause / Resume button (suspends between models)
- Checkpoint Batch: Stop while paused now immediately exits the loop
- GenerateUI Settings tab: KSampler and Latent Image side by side (50% each)
- Help tab: update gen-6, add gen-11 (batch), fix gallery-5~11 i18n gap (5-item shift)
- i18n: add helpGen11, helpGallery11; update helpGallery5-10 across EN/JA/ZH

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 00:41:57 +09:00
ketle-manandClaude Sonnet 4.6 6a2da8e4e9 docs: update DEVLOG v0.3.3 with subdirectory support and ImpactWildcardEncode fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 21:43:52 +09:00
ketle-manandClaude Sonnet 4.6 54fc57344a feat: wildcard subdirectory support
- wildcard_service.py: rglob recursive scan; _safe_path allows
  forward-slash separated relative paths (path traversal still blocked);
  save_file auto-creates parent directories; all responses include
  dir and wc_name fields (e.g. wc_name="color/animals").
- prompt-tab.js: file list and file picker group files by directory with
  a collapsible directory header; insert uses __wc_name__ (e.g.
  __color/animals__); editor name input accepts "folder/name" paths;
  save validation checks each path component individually.
- index.html: update editor name input placeholder to "name or folder/name".
- main.css: add .wfm-wc-dir-header, .wfm-wc-file-item--sub,
  .wfm-wc-picker-dir, .wfm-wc-picker-item--sub; add -webkit-user-select
  for Safari compatibility.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 21:41:46 +09:00
ketle-manandClaude Sonnet 4.6 1cc0e94724 Fix: ImpactWildcardEncode validation error in GenerateUI
- comfyui-workflow.js: validate COMBO widget values against object_info
  choices; fall back to first valid choice when stored value (e.g.
  "Select Wildcard 🟢 Full Cache") is not in the current options list.
  Prevents "Prompt outputs failed validation" with Impact Pack nodes.
- comfyui-workflow.js: recognize ImpactWildcardEncode/ImpactWildcardProcessor
  as prompt nodes in analyzeWorkflow (role detection via sampler refs);
  use wildcard_text as the editable text field (textKey).
- comfyui-editor.js: use node's textKey (defaulting to "text") when
  applying and syncing prompt fields, so ImpactWildcardEncode edits
  update wildcard_text instead of the non-existent text field.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 21:27:53 +09:00
ketle-manandClaude Sonnet 4.6 823f1ebd54 v0.3.3: Wildcard support panel & Impact Pack integration
- Add wildcard input toolbar to Prompt tab (right column) with one-click
  syntax buttons ({|}, {n$|}, __|__, <lora:>, etc.) and selection wrapping
- Add wildcard file manager: create/edit/delete .txt/.yaml files stored in
  user/default/Workflow-Studio/wildcard/
- Tab-ify Prompt tab center pane (Presets / Preset Manager toggle)
- New wildcard CRUD API (GET/POST /api/wfm/wildcards/*)
- New Wildcard Integration section in Settings tab: auto-detects
  ComfyUI-Impact-Pack and creates a directory junction (Windows) or symlink
  (other OS) between WFS wildcard dir and Impact Pack wildcards dir; existing
  files are migrated automatically; link can be removed via UI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 21:02:10 +09:00
ketle-manandClaude Sonnet 4.6 0886ea6e2b v0.3.2: Checkpoint Batch for GenerateUI & Seed layout fix
- Add Checkpoint Batch panel to GenerateUI right column: checkbox ON/OFF,
  include/exclude subfolder filters (comma-separated), real-time model count
  preview, amber progress bar with model name and index display
- Refactor handleGenerate into _coreGenerate (throws) + _runBatchGenerate loop;
  Stop button now aborts both single generation and batch loop
- Fix Seed row layout: seed input and mode selector now stacked vertically
  so neither is clipped in narrow right panels
- Update Help tab, DEVLOG, README for v0.3.2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 12:14:55 +09:00
ketle-manandClaude Sonnet 4.6 226fc885d7 v0.3.1: Gallery folder/file operations, tree state persistence, workflow auto-save
- Gallery: add folder create/delete and file delete/move (single & multi-select)
- Gallery: preserve folder tree expanded state across operations
- Gallery: improve workflow metadata extraction (workflow > prompt > gallery_metadata.json)
- Generate tab: auto-save workflow metadata to gallery on image generation
- Help tab: update Gallery section to reflect new v0.3.1 features

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:38:33 +09:00
ketle-manandClaude Sonnet 4.6 8d48c2276f v0.3.0: Cross-type group filter & sidebar group display fix
- models-tab.js: group filter dropdown now shows groups from all model
  types with [TypeLabel] prefix; selecting a group auto-switches type
- node_sets_menu.js: fix TypeError in renderModelGroups caused by v0.2.9
  per-type group format; add type label badge to each group header

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-18 14:23:50 +09:00
ketle-manandClaude Sonnet 4.6 918ab54004 v0.2.9: Model Enable/Disable, per-type groups, multi-select & bulk delete
- Toggle model visibility by renaming file extension (.disabled suffix)
  per card (⏸ button), per group (Enable All / Disable All), or via
  status filter (All / Enabled / Disabled)
- Groups are now scoped per model type; old flat groups auto-migrated
- Multi-select mode with bulk action bar: add/remove from groups,
  permanently delete model files + preview + sidecar (.json/.info)
- Fix: subdirectory model disable path-doubling error
- Fix: Hypernetwork tab showing C/O/M/B from new ComfyUI COMBO format

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-18 10:11:29 +09:00
ketle-manandClaude Sonnet 4.6 f25c042c39 v0.2.8: Move data dir to user/default/Workflow-Studio, add export/import
- py/config.py: DATA_DIR now resolves to ComfyUI/user/default/Workflow-Studio/
  with fallback to data/ when user/default/ does not exist
- py/routes/settings_routes.py: add GET /api/wfm/settings/export and
  POST /api/wfm/settings/import endpoints for full data bundle backup
- static/js/settings-tab.js: add Data Management section (export/import UI)
- static/js/i18n.js: add 8 new keys in EN/JA/ZH
- templates/index.html, static/js/app.js: add helpSettings8/9 to Help tab
- README.md, DEVLOG.md: updated for v0.2.8

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 11:11:40 +09:00
ketle-manandClaude Sonnet 4.6 1c9ec7ac19 Fix: Gallery tab auto-selects root folder on load
Previously the gallery showed "Select a folder to browse images."
until the user manually clicked a folder. Now the root folder is
automatically selected when the folder tree loads.

Also update docs/screenshot_gallery.png and screenshot_settings.png.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 10:09:12 +09:00
170 changed files with 171024 additions and 3481 deletions
+60
View File
@@ -0,0 +1,60 @@
"""PostToolUse hook: regenerate README.index.md / DEVLOG.index.md right after
Claude Code edits README.md or DEVLOG.md, so graphify's excluded-doc index
stand-ins (see .graphifyignore) never drift from the source files within a
session. A git pre-commit hook covers edits made outside Claude Code.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
TARGETS = {"readme.md": "readme", "devlog.md": "devlog"}
def main() -> None:
try:
payload = json.load(sys.stdin)
except (json.JSONDecodeError, ValueError):
return
if payload.get("tool_name") not in ("Edit", "Write"):
return
file_path = payload.get("tool_input", {}).get("file_path", "")
if not file_path:
return
name = Path(file_path).name.lower()
target = TARGETS.get(name)
if target is None:
return
project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or str(Path(file_path).resolve().parent)
script = Path(project_dir) / "tools" / "generate_doc_index.py"
if not script.exists():
return
result = subprocess.run(
[sys.executable, str(script), target],
cwd=project_dir,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
print(json.dumps({"systemMessage": f"[doc-index] {result.stdout.strip()}"}))
else:
print(
json.dumps(
{"systemMessage": f"[doc-index] generate_doc_index.py {target} failed: {result.stderr.strip()}"}
),
file=sys.stderr,
)
if __name__ == "__main__":
main()
+36
View File
@@ -0,0 +1,36 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Grep",
"hooks": [
{
"type": "command",
"command": "C:/Users/statsu-11/.local/bin/graphify.EXE hook-guard search"
}
]
},
{
"matcher": "Read|Glob",
"hooks": [
{
"type": "command",
"command": "C:/Users/statsu-11/.local/bin/graphify.EXE hook-guard read"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python \"$CLAUDE_PROJECT_DIR/.claude/hooks/on_doc_edit.py\"",
"timeout": 30
}
]
}
]
}
}
+5
View File
@@ -0,0 +1,5 @@
# graphify: keep graph.json/graphify-out/ out of Claude Code's automatic
# context so re-running `graphify extract` doesn't churn the prompt cache
# on every rebuild. These are still tracked by git (see .gitignore).
graph.json
graphify-out/
+11
View File
@@ -0,0 +1,11 @@
# ComfyUI-Workflow-Studio - Unsloth backend (AI TOOL tab / sidebar A tab)
#
# Unsloth Desktop requires an API key even for local access
# (Settings -> API in the Unsloth app, shown only once when issued).
#
# 1. Copy this file to ".env" (same directory as this example file)
# 2. Paste your key after the "=" below (do NOT add a leading #, or the
# line becomes a comment and the key will not be loaded)
# 3. Restart ComfyUI
UNSLOTH_API_KEY=
+22
View File
@@ -0,0 +1,22 @@
name: Publish to Comfy Registry
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "pyproject.toml"
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@d2366e7abb6ab16f3bb03e3520ae25c8cf749bc9 # 1.0.1
with:
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
+9
View File
@@ -5,3 +5,12 @@ __pycache__/
.venv
*.egg-info/
data/
# graphify: keep the knowledge graph itself under version control,
# but exclude the run-by-run cost/token log, the local extraction
# cache (both churn every rebuild and have no value to other clones),
# and the machine-local interpreter/scan-root pointers.
graphify-out/cost.json
graphify-out/cache/
graphify-out/.graphify_python
graphify-out/.graphify_root
+10
View File
@@ -0,0 +1,10 @@
# Private/unpublished planning notes — never committed to git, must not leak
# into the published graphify-out/ knowledge graph either.
QWEN_CHAT_INTEGRATION_PLAN.md
# Too large for reliable local-Ollama semantic extraction (large chunks make the
# model summarize in prose instead of emitting JSON, and time out on slower
# models/hardware). README.index.md / DEVLOG.index.md are condensed stand-ins
# that graphify extracts instead — regenerate them after editing the originals.
README.md
DEVLOG.md
+40
View File
@@ -185,3 +185,43 @@ os.environ["HF_HOME"] = "D:\\hf_cache"
5. `INPUT_TYPES` 変更時は `widgets_values` も同時更新
6. 削除した依存への参照が残っていないか grep で確認
7. ComfyUI完全再起動 → ワークフロー読み込み → エンドツーエンド実行確認
---
## リリース手順
コミット・プッシュ・GitHub リリース(`gh release create`)を行う際は、**必ず以下の順序**で実施する。
1. `pyproject.toml` の `version` を新バージョン番号に更新してステージングに含める
2. `README.md` のバージョンバッジを更新(`![Version](https://img.shields.io/badge/version-X.Y.Z-green)`)
3. `DEVLOG.md` の先頭に変更詳細エントリを追加
4. 上記すべてを同一コミットにまとめてプッシュ
5. `gh release create vX.Y.Z` でリリースを作成(リリースノート本文に変更点を記載する — v0.3.90でREADME.mdのChangelogセクションは廃止したため、以後のバージョン履歴はGitHub Releaseのリリースノートのみで管理する)
`pyproject.toml` のバージョン変更が GitHub Actions のトリガー(`paths: pyproject.toml`)になっており、ComfyUI Registry への自動公開もここで行われる。バージョン更新を忘れると Registry に反映されない。
<!-- graphify運用は一時停止中(2026-08-23〜、ユーザー指示により凍結)。再開時はこのコメントブロックを解除すること。graphify-out/ 自体は削除しておらずそのまま残っている。
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
### README.md / DEVLOG.md の索引ファイル
`README.md`/`DEVLOG.md`はサイズが大きすぎてローカルOllamaでの意味抽出が不安定になる(大きな塊を渡すとJSONではなく散文の要約を返す、または処理がタイムアウトする)ため、`.graphifyignore`でgraphifyの抽出対象から除外している。代わりに縮小版の`README.index.md`/`DEVLOG.index.md`を抽出対象にしている。
- 生成スクリプト: `python tools/generate_doc_index.py [readme|devlog|all]`
- 自動化: `README.md`/`DEVLOG.md`を編集すると以下の2つのフックが自動でindexを再生成する
- Claude Code PostToolUseフック(`.claude/hooks/on_doc_edit.py`)— Edit/Write直後に即時実行
- git pre-commitフック(`.git/hooks/pre-commit`)— コミット時にstagedファイルを検知して再生成し、同じコミットに含める(他エディタでの編集にも対応)
- 索引ファイルを手動で編集しない(次の生成で上書きされる)
- 索引ファイル再生成後は`graphify update .`を実行してグラフに反映する
-->
+178
View File
@@ -0,0 +1,178 @@
# DEVLOG Index — ComfyUI-Workflow-Studio
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.6.2** — Image Editタブにペンタブレット筆圧対応とFillツール(バケツ塗りつぶし)を追加
- **v0.6.1** — Galleryタブの検索が「読み込み中」のまま止まりクリアでも中断できない不具合、および50枚程度のフォルダでも数秒〜十数秒かかる不具合を修正
- **v0.6.0** — Gallery/Image Edit両タブにPSD(Photoshop)対応を追加 — 複数画像の一括PSD書き出し、レイヤー保存/読み込み、Gallery表示、Image Editのレイヤーパネル改善
- **v0.5.8** — Tagger DBタブに一括削除機能を追加(外部コントリビューターPRのレビュー・検証・修正・マージ)
- **v0.5.7** — 設定エクスポート/フルバックアップのドキュメント修正: v0.5.5のVideo Plan機能追加分の言及漏れ
- **v0.5.6** — バグ修正: WD Taggerで不正確なタグが生成される問題を修正(GitHub Issue #1)
- **v0.5.5** — Videoタブ全面刷新: Plan/Asset/Editバッチ生成 + Projectサブタブ + プレビュー2ペイン化 + Video Assets/Video Temp運用整理 + Galleryメタデータ消失バグ根本修正
- **v0.5.4** — 機能追加: Video/GenerateUIタブのLTX-2.5・Wan2.2対応拡大 + AI Assistant設定のUnsloth対応・独立モーダル化・モデルアンロード機能
- **v0.5.3** — バグ修正: Labタブのワークフロー切替時に前の内容が残留 + Galleryタブの読み込み高速化・root自動展開 + READMEスクリーンショット刷新
- **v0.5.2** — 機能追加: GenerateUI/Labタブの動画ワークフロー対応 + VideoタブにFrame抽出/GIF変換機能 + データ管理監査とZIPフルバックアップ + Send to LI node統一
- **v0.5.1** — 機能追加: mp4動画の埋め込みメタデータ対応(Gallery Prompt/JSON・Metadataサブタブ・サイドパネルIタブ)+ Gallery Infoタブに寸法/再生時間表示 + MiniMax H3等オールインワン動画ノードのプロンプト抽出バグ修正
- **v0.5.0** — 機能追加: mp4動画Gallery対応 + Videoタブ新設(MiniMax H3専用) + バグ修正: Galleryのタグ/メモが再起動後に消える
- **v0.4.8** — 機能追加: LabタブにPromptグループ一括適用+キーフレーム並べ替え + バグ修正: デフォルトワークフローの上書き保存が反映されない + Styleテーブルの「このファイルへ追加」対応
- **v0.4.7** — 機能追加: Prompt Tab内部リファクタ + Gallery Promptタブ新設 + Send to Canvas改善 + Presetsソート
- **v0.4.6** — 機能追加: MetadataタブをGalleryタブへ統合 + Promptタブに一覧編集可能なTable表示を新設
- **v0.4.5** — 調査: トップバー保存ワークフローのRMBG不具合報告(原因なし) + バグ修正: LabタブModel列の無意味な空キーフレーム表示を解消
- **v0.4.4** — 機能追加: Lab/GenerateUI ModelタブへLoRAバイパス機能 + AI TOOL Chatの画像生成パラメータ拡張
- **v0.4.3** — バグ修正: 共有モーダルのお気に入り☆/リネームがLabモーダルへ残留 + Lab Model列の+/-をCheckpoint/LoRA/VAEで完全独立化
- **v0.4.2** — 機能追加: Lab「Model」列統合(Checkpoint / LoRA Single / VAE)+ フィールド単位継承 + C/L/V表示切替
- **v0.4.1** — UX改善: Mask Editor One連携ボタンを「選択中ノード優先」方式に再設計
- **v0.4.0** — リファクタリング: image-edit-tab.js / models-tab.js の低凝集度モジュール分割
- **v0.3.99** — 機能追加: AI TOOLタブ + サイドパネルAタブにUnslothバックエンド追加(APIキーは.env管理、SSRF脆弱性修正、reasoning_content対応)
- **v0.3.98** — 機能追加・バグ修正: AI TOOL翻訳の信頼性向上 + GenerateUI Modelタブ再構成(ハイライト色・折りたたみ・並び替え)+ Thinking mode/Max tokens設定
- **v0.3.97** — 機能追加・バグ修正: KREA-2ワークフロー対応 + Labタブ拡張(Clear/Get from Previous/Bypass/ライブ反映)+ Input Imageプレースホルダ機能
- **v0.3.96** — バグ修正: カタログ作成バッチが特定件数で無言停止する問題の修正 + Style Catalog/Promptタブ機能拡張
- **v0.3.95** — 機能追加: Style/Prompt→ImagePrompt改名 + Style_Catalogギャラリー新設 + GenerateUI「カタログ作成」機能
- **v0.3.94** — 機能追加: Gallery タブのサブタブ化 + Style/Prompt ギャラリー新設(視覚的プロンプトビルダー)
- **v0.3.93** — バグ修正・機能改善: Labタブ VAEキーフレーム不発バグの修正+Style適用UI刷新+Plan JSONスクロール同期修正+キーフレーム個別削除+Batch数超過警告+ワイルドカード対応+Save index image デフォルトON
- **v0.3.92** — バグ修正: CLIPTextEncodeEditPlus使用ワークフローがGenerateUI経由だと直接実行と異なる画像になる問題(根本原因はconvertUiToApiのForceInput 未考慮バグ)+LoRA Stack機能の改善一式
- **v0.3.91** — 機能拡張: Labインデックス画像にPlanメタデータをPNG埋め込み+README構成整理(Changelogセクション廃止)
- **v0.3.90** — 機能拡張: Labタブの進化(ワークフロー呼び出し・T2I対応・Run時インデックス画像Output保存+Eagle連携・プラン接頭辞)+Galleryタブのルート表示簡略化
- **v0.3.89** — バグ修正: v0.3.88で追加したLab機能への実動作確認フィードバック3件を反映
- **v0.3.88** — 機能拡張: Labタブ Promptセルにスタイル適用・画像/GenerateUIからのプロンプト取得、Checkpoint/VAEフィルター、Plan JSONサブタブを追加
- **v0.3.87** — 追加機能: GenerateUIタブに実験的な「Lab」サブタブを追加(I2Iバッチ生成・キーフレーム方式)
- **v0.3.86** — バグ修正: 画像を一括生成(I2I)等の連続実行で "GalleryMetadataStore: save error: dictionary changed size during iteration" が発生
- **v0.3.85** — 機能拡張: Generate UI連携ブリッジ(T2I)にデフォルトワークフロー・Negativeプロンプト対応を追加
- **v0.3.84** — バグ修正: ernie_t2i.jsonをGenerateUIタブで実行すると "Prompt outputs failed validation" エラー
- **v0.3.83** — 追加機能: Ernie Image(ernie-image / ernie-image-turbo)ワークフロー対応 + プロンプトがリンク経由のノードから供給されるパターンの修正
- **v0.3.82** — バグ修正: MetadataタブとサイドパネルIタブでLongCat/Boogu/HiDream E1/FireRed等のプロンプトが表示されない不具合
- **v0.3.81** — 追加機能: GenerateUIタブでFlux.2 Klein / LongCat / Boogu / HiDream E1 / FireRedのImage Editワークフローに対応
- **v0.3.80** — 追加機能: Comic Creator「半自動マンガ作成」向けブリッジ(LLMプロンプト下書き・バッチ画像生成)
- **v0.3.79** — 追加機能: サイドパネル(Workflow Studio Library)IタブのMage-Flow等サブグラフワークフロー対応
- **v0.3.78** — 追加機能: Eagle自動保存のSVG対応
- **v0.3.76** — 追加機能: Comic Creator向けI2I実行ブリッジ`_wfmReceiveI2IRunRequest`
- **v0.3.77** — 追加機能: GalleryタブでSVGファイルの表示・管理に対応
- **v0.3.75** — Lemonadeバックエンド追加(3つ目のAIバックエンド)
- **v0.3.74** — AI TOOL Chatペインの画像添付対応 + I2I連携
- **v0.3.73** — AI TOOL Chatペインからの対話式画像生成(Tool Calling)+ Checkpoint関連の安全策
- **v0.3.72** — Comic Creator連携用の外部Inpaintエントリポイントを追加
- **v0.3.71** — Inpaint機能の追加(GenerateUI Imageタブ + Image Edit「Inpaint」タブ)
- **v0.3.70** — Workflow AI要約: Ollama 404エラー修正
- **v0.3.69** — Gallery → ComfyUI Comic Creator 連携(Send CC ボタン)
- **v0.3.68** — MASK EDITOR ONE セクション常時表示化
- **v0.3.67** — Alt+Click Apply & Generate
- **計画: Image Edit 拡張 — ABRブラシ連携 + Mask Editor One 統合** — フェーズ1: Draw ツール — ABRブラシ対応
- **2026-06-29: v0.3.66 — Mask ツール 5サブツール追加(Color / Alpha / Text / Vector / Shape)・Support リンク追加** — 概要
- **2026-06-29: v0.3.65 — Mask Editor One 連携修正・トップバーアイコン修正・Mask ABRブラシ対応** — 概要
- **2026-06-28: v0.3.64 — Image Edit マスク Add/Subtract・BiRefNet BG Remove・SAM3 セグメンテーション・ブラシカーソルバグ修正** — 概要
- **2026-06-28: v0.3.63 — ノードタブ複数選択・全タブフィルタークリア・検索Xボタン** — 概要
- **2026-06-27: WFS_PromptText の GenerateUI 対応・ドロップ時 title 固定** — 概要
- **2026-06-27: v0.3.62 — Send GenUI Image ボタン追加・tagger_settings.json バグ修正・README 更新** — 概要
- **2026-06-27: データ管理バグ修正 — tagger_settings.json をエクスポート対象に追加** — 概要
- **2026-06-27: v0.3.61 — G'MIC バグ修正・セキュリティ・Draw/Mask ブラシ操作性改善** — 概要
- **2026-06-27: v0.3.60 — Image Edit Filter Tool (G'MIC-Qt 連携) 実装** — 概要
- **2026-06-27: v0.3.59 — Image Edit Mask Tool 実装・Draw/Mask 描画バグ修正・クリッピング保存対応** — 概要
- **2026-06-27: v0.3.58 — GenerateUI Model タブ GGUF対応拡張(Diffusion Model / Text Encoder)** — 概要
- **2026-06-26: v0.3.57 — Image Edit Blur Tool / BG Remove Tool 追加** — 概要
- **2026-06-26: v0.3.56 — Style機能追加(GenerateUI ツールバー & Batchタブ)** — 概要
- **2026-06-25: v0.3.55 — グループ機能バグ修正(全タブ)** — 根本原因(データ消失): パス区切り文字の不一致
- **2026-06-25: v0.3.54 — Image Edit Shape ツール追加・Models タブ overlay バグ修正** — Image Edit Tab — Shape ツール(□ / S キー)
- **2026-06-25: v0.3.53 — Image Edit Tab 実装・レイヤーロック・ギャラリー保存** — Image Edit Tab(新規タブ)
- **2026-06-25: GenUI設定タブ LATENT IMAGE にプリセット機能を追加** — 変更内容
- **2026-06-24: GenUI ModelでLoRA適用後、Modelサブタブ再表示時に値がリセットされるバグ修正** — 問題
- **2026-06-24: v0.3.51 — Embedding GenUI PP/NP対応 + GenerateUIプロンプトタブEmbeddingセレクタ追加** — 変更内容
- **2026-06-24: v0.3.51 — GenerateUIタブ Hypernetwork対応 + ModelsタブGenUI Modelボタン追加** — 変更内容
- **2026-06-24: v0.3.51 — Hypernetwork/Embeddingモデル未表示バグ修正** — 原因
- **2026-06-24: v0.3.51 — ModelsタブサイドパネルにGenUI Modelボタン追加** — 変更内容
- **2026-06-22: v0.3.50 — ギャラリータブ プロンプト検索負荷改善(バックグラウンドインデックス)** — 問題
- **2026-06-22: v0.3.49 — 生成UIタブ A1111風ワイルドカード展開・ギャラリータブ バグ修正2件** — 生成UIタブ — A1111風SPAサイドワイルドカード展開
- **2026-06-22: v0.3.48 — ギャラリータブ 画像ダウンロード・一括エクスポート機能追加** — 詳細パネルの画像プレビューにダウンロード機能を追加
- **2026-06-22: v0.3.47 — モデルタブ ファイル移動後グループ状態修正** — モデル移動後のグループ状態不整合を修正
- **2026-06-21: v0.3.46 — プロンプトタブ AI Assistant LM Studio対応・設定タブ AI Assistant設定に変更** — 設定タブ「AI Assistant設定(プロンプトタブ)」
- **2026-06-21: v0.3.45 — グループ孤立エントリ自動クリーンアップ・Galleryタブ Shift+クリック範囲選択** — グループ孤立エントリ自動クリーンアップ
- **2026-06-21: v0.3.44 — Galleryタブ高速化・比較モード・バルク強化・バルクバーUI整理** — フェーズ2-A: サーバーサイドサムネイル生成
- **2026-06-21: ヘルプタブ改善 — Gallery mode 多言語対応・フォント拡大・検索機能追加** — Gallery mode の多言語対応
- **2026-06-21: Send to Canvas — window.opener経由のキャンバス直接ロード対応**
- **2026-06-20: API形式ワークフローのキャンバス読み込み修正・画像メタデータ埋め込み修正** — API形式ワークフローをキャンバスへドラッグすると空になる問題を修正
- **2026-06-20: セキュリティ修正(XSS・パスバリデーション)** — 修正内容
- **2026-06-20: WFS_GalleryFeeder — ComfyUI キャンバス上コントロール追加** — 新規ファイル(`web/comfyui/gallery_feeder_extension.js`)
- **2026-06-20: __Feeder__ グループ保護 + サムネイル F ボタン + seed バグ修正** — `__Feeder__` グループの予約済み保護
- **2026-06-20: Gallery Feeder 機能追加(WFS_GalleryFeeder ノード)** — 概要
- **2026-06-19: Generate UI — ImpactWildcardEncode/Processor プロンプト検出バグ修正(v0.3.41)** — 修正内容(`static/js/comfyui-workflow.js`)
- **2026-06-19: AI TOOL タブ Chat ペイン・ワイルドカード生成追加(v0.3.40)** — Chat ペイン(`templates/index.html`, `static/css/main.css`, `static/js/ai-tab.js`, `web/comfyui/node_sets_menu.js`)
- **2026-06-18: Send to Canvas機能追加(ワークフロータブ・ギャラリータブ→LibraryタイトルDnD)** — ワークフロータブ — Send to Canvas(`static/js/workflow-tab.js`, `static/js/app.js`, `templates/index.html`)
- **2026-06-15: TaggerシングルGenUI:Pボタン追加+生成UIのZITワークフロープロンプト解析修正** — TaggerシングルGenUI:Pボタン(`templates/index.html`, `static/js/tagger-tab.js`, `static/js/i18n.js`)
- **2026-06-15: Taggerバッチ.txt出力追加+Galleryタグ保存バグ修正** — Taggerバッチ.txt出力(`templates/index.html`, `static/js/tagger-tab.js`, `static/js/i18n.js`, `py/routes/tagger_routes.py`, `py/services/tagger_service.py`)
- **2026-06-15: Taggerタブ新規実装+ギャラリー詳細パネルUI改善+パストラバーサル修正** — Taggerタブ新規実装
- **2026-06-15: 全選択ボタン追加+ギャラリーバルクバーi18n対応** — 変更内容
- **2026-06-10: v0.3.36 — コードレビュー修正+リファクタリング+README刷新** — コードレビュー修正(v0.3.35の不具合10件)
- **2026-06-10: v0.3.35 — テーブルソート・Load GenUI・ワークフロー保存** — 変更内容
- **2026-06-09: v0.3.34 — Modelsタブ テーブルビュー強化・バルク操作改善** — 変更内容
- **2026-06-09: v0.3.33 — LoRAペイン・ワークフロー解析バグ修正** — 変更内容
- **2026-06-08: v0.3.32 — Lora Loader (LoraManager) LoRA検出対応・ライブラリ機能拡張** — 変更内容
- **2026-06-08: v0.3.31 — LoRAペイン Single/Stack タブ分割・GenUI Model LoRA対応強化** — 変更内容
- **2026-06-08: v0.3.30 — LoRAスタック トリガーワードバグ修正・ヘルプ更新** — 変更内容
- **2026-06-08: v0.3.29 — LoRAセクション統合・ヘルプタブサイドバー・UI細部改善** — 変更内容
- **2026-06-08: 生成UIタブ 複数改善 — LoRA Stackトリガーワード連携・Reset Workflowボタン・Inputタブタブ化** — 変更内容
- **2026-06-08: Feederタブ UI改善 — (root)自動選択・PREVIEWペイン右移動・RUN中プレビュー反映** — 変更内容
- **2026-06-07: v0.3.28 — Batchタブ Sampler/Scheduler対応 + Modelsサムネイルバグ修正** — 概要
- **2026-06-07: v0.3.27 — model-and-prompt-from-metadata カスタムノード対応 + README修正** — 概要
- **2026-06-07: v0.3.26 — Stack LORA SYNTAX 表示修正 + 全体強度調整 UI** — 概要
- **2026-06-07: v0.3.25 — Lora Loader (LoraManager) 対応 + Stack 有効無効切り替え** — 概要
- **2026-06-06: v0.3.24 — Lora Stack 登録機能 + 生成UI Model タブ 3ペイン化** — 概要
- **2026-06-05: v0.3.23 — バグ修正2件** — バグ修正
- **2026-06-05: v0.3.22 — カードビュー廃止 + Batch タイプ切り替え UI + 4タイプバッチ生成** — 概要
- **2026-06-05: (未リリース) — 生成UIタブ Batch 4タイプ対応(Lora/Prompt/Workflow グループ選択 + BATCH QUEUE 4列化)** — 概要
- **2026-06-05: (未リリース) — Prompt・Workflow Batchグループ登録UI** — 概要
- **2026-06-04: (未リリース) — モデルBatchグループ登録UI(サムネイル/カード/テーブル・フィルター・一括解除)** — 概要
- **2026-06-04: (未リリース) — Batch予約グループ・Presets Save後リセット・グループフィルター種別絞り込み** — 概要
- **2026-05-31: v0.3.21 — CivitAI ホスト設定・Sample サブタブ・URL 修正・ヘルプ i18n 整備** — 概要
- **2026-05-31: v0.3.20 — CivitAI 詳細パネル強化(Type / Hash 表示・URL 修正・画像別タブ)** — 概要
- **2026-05-31: v0.3.19 — CivitAI 連携強化(バッチ高速化・リトライ・APIキー・フィールド拡充)** — 概要
- **2026-05-31: v0.3.18 — Batch タブ追加・Models 複数選択強化** — 概要
- **2026-05-31: v0.3.17 patch — SSLコンテキスト セキュリティ強化** — 概要
- **2026-05-30: v0.3.17 — SSL証明書エラー修正・Lora Manager対応** — 概要
- **2026-05-20: v0.3.16 — CivitAIプレビューフォールバック表示** — 概要
- **2026-05-20: v0.3.15 — サンプルワークフロー同梱・CivitAI自動プレビュー・Create Tagsオプション** — 概要
- **2026-05-20: AI TOOL タブ 英語化(SPA・Libraryパネル)** — 概要
- **2026-05-19: v0.3.14 — AI TOOL タブ 3ペイン化・RAW JSON 文字色カスタマイズ** — 概要
- **2026-05-19: v0.3.13 — AI タブ(A)追加** — 概要
- **2026-05-18: v0.3.12 リリース — README スクリーンショット刷新 / workflow_analyzer 拡張** — 概要
- **2026-05-17: RAW JSON パネルに検索機能を追加** — 概要
- **2026-05-17: v0.3.11 Metadata タブ対応ノードタイプ拡張 / Settings テキストサイズ UI 追加** — 概要
- **2026-05-17: v0.3.10 Information タブ キャンバスドラッグ対応 / ノードタイプ拡張 / バグ修正** — 概要
- **2026-05-16: v0.3.9 サイドパネル I タブ追加 / トップバーアイコン修正** — 概要
- **2026-05-16: v0.3.8 Metadata タブ: data9 対応 / プロンプト判別不能テキスト** — 概要
- **2026-05-15: v0.3.7 Metadata タブ: Flux2 / Qwen / Z-Image 対応** — 概要
- **2026-05-15: v0.3.6 Metadata タブ追加** — 概要
- **2026-05-09: v0.3.5 GenerateUI — Feeder サブタブ・ワークフロー解析精度向上** — 概要
- **2026-04-29: v0.3.4 GenerateUI — Checkpoint Batch 刷新・Settings 横並びレイアウト・ヘルプ i18n 修正** — 概要
- **2026-04-28: v0.3.3 Promptタブ — ワイルドカード支援パネル・Impact Packシンボリックリンク連携・サブディレクトリ対応・GenerateUI修正** — 概要
- **2026-04-28: v0.3.2 生成UIタブ — Checkpoint Batch・Seed UIレイアウト修正** — 概要
- **2026-04-27: v0.3.1 ギャラリー拡張(フォルダ/ファイル操作・ワークフロー保存)** — 概要
- **2026-04-18: v0.3.0 モデルグループ表示改善(全タイプ横断・サイドパネル修正)** — 概要
- **2026-04-18: v0.2.9 モデル有効/無効・複数選択・一括削除** — 概要
- **2026-04-14: v0.2.8 データ保存先変更・エクスポート/インポート機能追加** — 概要
- **2026-04-06: v0.2.6 UI改善・バッジ保存修正・フォルダフィルター追加** — 概要
- **2026-04-04: v0.2.5 追加修正** — 概要
- **2026-04-03: v0.2.5 サイドパネル Category/Package サブタブ・テーマ設定・Workflow修正** — 概要
- **2026-03-29: v0.2.4 GenerateUIタブ レイアウト再設計** — 概要
- **2026-03-29: v0.2.3 バッジ統一・GenUI Model・サイドパネルModels拡充** — 概要
- **2026-03-28: v0.2.2 Modelsタブ・CivitAI連携** — 概要
- **2026-03-27: テーマカスタマイズ機能・設定タブ改善** — 概要
- **2026-03-26: トップバーボタンアイコン修正・Appモードバッジ調査** — 概要
- **2026-03-25: v0.2.0 プロンプトプリセット機能・Workflow Studio Library** — 概要
- **2026-03-24: v0.1.9 サイドパネルUI改善・保存ダイアログ・バグ修正** — 概要
- **2026-03-24: v0.1.8 WF & Node Library サイドパネル拡張** — 概要
- **2026-03-23: v0.1.7 Nodes タブ追加** — 概要
- **2026-03-23: v0.1.6 パストラバーサル脆弱性修正** — 概要
- **2026-03-22: v0.1.5 テーマシステム追加** — 概要
- **2026-03-22: v0.1.4 App形式対応・プリセットコピー・分析バグ修正** — 概要
- **2026-03-21: v0.1.3 ヘルプ&サポートタブ追加** — 概要
- **2026-03-19: v0.1.2 リリース** — 概要
- **2026-03-19: v0.1.1 リリース** — 概要
- **2026-03-18: プロジェクトリネーム & アイコン適用** — 概要
- **2026-03-18: デフォルトビュー設定追加** — 概要
- **2026-03-18: MarkdownNote表示専用ノード除外** — 概要
- **2026-03-18: サブグラフワークフロー対応 & 変換精度修正** — 概要
- **2026-03-18: Raw JSON同期修正** — 概要
- **プロジェクト構成 (現在)**
- **2026-03-18: JSONシンタックスハイライト** — 概要
- **2026-03-18: プロンプトタブ 中国語↔英語翻訳追加** — 概要
- **2026-03-18: v0.1.0 リリース** — 概要
- **2026-04-13: Gallery タブ追加 & 全タブ Group UI 統一** — 概要
+6662 -5
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ketle-man
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+262
View File
@@ -0,0 +1,262 @@
# README Index — ComfyUI-Workflow-Studio
Condensed index of README.md: intro summary, feature names per tab (full descriptions live in the excluded README.md), and the installation/usage/requirements/project-structure sections verbatim. Exists so graphify can extract this without feeding the full README (with its screenshot table) to the local Ollama model. Regenerate with `python tools/generate_doc_index.py readme` whenever README.md changes.
# ComfyUI-Workflow-Studio
A comprehensive workflow, asset management, and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
**📁 Management** — organize all your assets in one studio
- Workflow, model, image, and prompt management
- AI-powered prompt writing assistance, translation, and tag generation
- File drop & Gallery-linked metadata viewing — inspect and reuse generation settings instantly
**⚡ GenerateUI** — a productivity-focused generation tab connected to every other tab
- Batch generation across models, samplers, prompts, and workflows
- Image Feeder for continuous folder-based generation
- Lab: experimental I2I batch generation with independent per-iteration keyframes for Model (Checkpoint/LoRA Single/VAE)/Prompt/KSampler
**📚 Workflow Studio Library** — a multi-function side panel for smooth ComfyUI integration
- Drag & drop models, nodes, prompts, and workflows straight onto the canvas
- **Send to Canvas**: click "Send to Canvas" (Workflow tab) or "Copy & Send Canvas" (Gallery tab) to send the workflow directly to the ComfyUI canvas — UI and API formats both supported
- View metadata from images / JSON, then drop the detected models and prompts onto the canvas
- 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.6.2-green)
## Features (tab -> feature names)
### Workflow Tab
Thumbnail / Table views, Thumbnail side panel, Badge filtering, Search, Side panel tabs, Badge management, AI summary, Import / Export, Side panel toolbar buttons, Default view setting, Search clear (✕), Clear all filters (✕ Clear)
### Canvas Snapshot (v0.1.2)
One-click capture, Auto-save as thumbnail, Embedded workflow metadata, Auto-import
### GenerateUI Tab (v0.3.5)
6-tab layout, Save button, Input tab, Model tab, Settings tab, Always-visible Raw JSON, Bypass/Mute node handling, One-click generation, Seed control, Style selector, Create Catalog / Catalog buttons, Batch type selector, Batch tab, UI-to-API conversion, Video workflow support, Eagle integration
### Feeder subtab (v0.3.5 / v0.3.42)
ImageFeeder node control, Image library, Selection management, Presets, Continuous Run loop, Index sync, Seed, WFS_GalleryFeeder node, Node & group selector, Image grid, After Gen modes, Run / Stop controls
### Lab subtab (v0.3.87 – v0.5.2)
Setting / Results / Plan JSON sub-panels, Per-column keyframes, Model column — Checkpoint / LoRA Single / VAE, Empty state when no matching node exists, Wildcards, Prompt cell extras, Keyframe #1 live-reflect, Bypass checkbox, LoRA node bypass & prompt injection, T2I workflow support, Use generated image for next, Workflow recall, Plan files, Plan Load, Plan JSON tab, Save index image to Output on Run, Index images are self-contained plan files, Eagle integration, Select vs. edit, and keyframe reordering, PG — apply a Prompt tab preset group, Video workflow support, Use generated image for next, now video-aware
### Prompt Tab
3-column layout, AI chat assistant, Image attachment, Translation, Prompt presets, Preset Manager, Group management, Clipboard copy, GenUI Set, Wildcard/Style tab bar, Wildcard input toolbar, Wildcard file manager, Style manager, Form / Table toggle, Table view — Presets / Presets Group / Wildcards / Style
### Settings Tab
2-column layout, Collapsible sections, Theme selection, Theme customization, Workflows directory, Gallery output directory, Eagle connection, CivitAI Host, CivitAI API Key, Default workflow, Default Checkpoint, Video Playback Volume, Data Management, Text Size, RAW JSON Colors, GenerateUI Model Tab Highlight, Wildcard Integration, G'MIC-Qt Integration, Language
### Gallery Tab (v0.3.44)
Output / ImagePrompt / Style_Catalog / Metadata sub-tabs, Image browser, Folder tree root label, Thumbnail / Table views, Folder management, File operations, Download, MP4 video support, MP4 embedded metadata, Info tab: dimensions & duration, Multi-select, Image Compare, Prompt search, Server-side filtering, Group management, Thumbnail F button, Favorites, Detail panel, Prompt tab, Workflow viewer, GenUI button, Image Edit button, Send GenUI Image button, Send to LI node button, Send CC button, Search clear (✕), Clear all filters (✕ Clear), Workflow auto-save, Output folder configurable, SVG file support, PSD file support, Performance
### ImagePrompt Gallery subtab (v0.3.94, renamed from Style/Prompt in v0.3.95)
Visual prompt library, 3-column layout, Prompt builder (right pane), Plain-text prompt storage, ponyxlWildcardsVault format support, Seed data importer
### Style_Catalog Gallery subtab (v0.3.95)
Visual Style picker, 3-column layout, Positive/Negative panel, Select as Style button, Load in GenerateUI / Open in Metadata Tab buttons, Double-click to enlarge
### Metadata Gallery subtab (v0.3.8, moved from a top-level tab in v0.4.6)
Now inside Gallery, 3-column layout, File drop, MP4 embedded metadata, Model extraction, LoRA extraction, Prompt extraction, Prompt actions, Format support, Format note
### Nodes Tab (v0.1.7)
Node Browser, Search & Filter, Package badges, Node detail panel, Node Sets, Right-click context menu, Multi-select, Search clear (✕), Clear all filters (✕ Clear)
### Models Tab (v0.2.3)
Model Browser, Thumbnail / Table views, Table column sort, Search & Filter, User-defined badges, Side panel tabs, CivitAI integration, CivitAI panel — Info / Sample sub-tabs, CivitAI panel states, Batch CivitAI fetch, Detail modal, GenUI Model button, Group management, Table view memo, Preview images, Enable / Disable models, Multi-select & bulk operations, Search clear (✕), Clear all filters (✕ Clear)
### Tagger Tab (v0.3.38)
3 sub-tabs, Model support, Threshold sliders, VLM tagging, Single tab, Single output options, Batch tab, DB tab, Dependencies
### Image Edit Tab (v0.3.65)
Layer-based image editor, Loading images, Open PSD button, Close button, New button, Tools, Layer panel, Duplicate layer (⧉), Layer lock, Text quality, Export, Canvas navigation, Undo / Redo
### Video Tab (v0.5.0 – v0.5.7)
Dedicated video generation UI, independent of GenerateUI, Plan / Edit subtabs, Base settings row, Asset / Project subtabs, Two center previews, First Frame / Last Frame are both optional, Semantic node lookup, not hardcoded IDs, Field highlight color, Load in Video, Frame tab, GIF tab, Playback volume
### AI TOOL Tab (v0.3.14)
4-pane layout, Translation pane, Chat pane, Chat pane — image generation via Tool Calling, Chat pane — generate_image extra parameters, TOOLS pane (VLM), TOOLS pane — shared Chat attachment, TOOLS pane (Wildcards), Chat pane — image-to-image (I2I), Chat pane — SVG generation, no ComfyUI workflow involved, Chat pane — Skills, Settings pane, Unsloth backend, Settings pane — Chat Image Generation, Settings pane — Chat I2I Generation, Settings pane — Generation, Model unload, Settings shared, Backend support, URL security, Lemonade's other endpoints (not integrated)
### Workflow Studio Library (ComfyUI Side Panel) (v0.3.9)
Tab layout (W / N / P / M / I / A), W — Workflows tab, N — Nodes tab, M — Models tab, P — Prompts tab, I — Information tab, A — AI TOOL tab, Drag & drop workflows, Drag & drop nodes, Drag & drop prompts, Send to Canvas, Copy prompts, Double-click, Search, ⚙ Theme settings
### Help &amp; Support Tab (v0.1.3)
Sidebar navigation, Support, Feature list, Keyboard Shortcuts
## Installation
### Via ComfyUI Manager (Recommended)
Search for **Workflow Studio** in ComfyUI Manager and install.
### Manual Installation
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ketle-man/ComfyUI-Workflow-Studio.git
```
Restart ComfyUI after installation.
---
## Sample Workflows
Sample workflows are included in the `workflows/` folder. You can open them directly in ComfyUI via drag & drop, or load them from the Workflow tab.
> **Note:** Some sample workflows require additional custom nodes.
> If a node is shown as missing (red/unknown) after loading, install the required custom nodes via **ComfyUI Manager** or by cloning the repository from GitHub into your `ComfyUI/custom_nodes/` directory.
>
> ```bash
> cd ComfyUI/custom_nodes
> git clone <repository-url>
> ```
>
> After installation, restart ComfyUI to activate the new nodes.
---
## Usage
### Launch
Click the **W** button in the ComfyUI top menu bar, or navigate to:
```
http://127.0.0.1:8188/wfm
```
> **Tip:** Shift+Click the W button to open in a new window.
### Canvas Snapshot
Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture the current workflow canvas as a thumbnail. The image is automatically saved to the workflow data folder and appears in Workflow Studio's workflow list.
### Quick Start
1. **Workflow Tab** — Your workflows from `ComfyUI/user/default/workflows/` are automatically listed
2. **Click a workflow** — View thumbnail, JSON details, and metadata in the side panel
3. **Load in GenerateUI** — Click the button to load a workflow into the generation interface
4. **Adjust parameters** — Modify prompts, models, seeds, and settings via the auto-generated UI
5. **Generate** — Hit the Generate button to queue the prompt
---
## Requirements
- **ComfyUI** — any recent version (v1.33.9+ recommended for action bar integration)
- **Python 3.10+**
- **Jinja2** — `pip install jinja2` (usually included with ComfyUI)
### Optional
- **[Ollama](https://ollama.com/)** — for AI chat assistant, translation, and VLM features
- **[LM Studio](https://lmstudio.ai/)** — alternative backend for translation and VLM (OpenAI-compatible API)
- **[Lemonade Server](https://lemonade-server.ai/)** — alternative backend for translation, chat, and VLM (OpenAI-compatible API)
- **[Unsloth](https://unsloth.ai/)** — alternative backend for translation, chat, and VLM (OpenAI-compatible API); always requires an API key, set via `UNSLOTH_API_KEY` in a `.env` file — `pip install -r requirements.txt` for `python-dotenv`
- **[Eagle](https://eagle.cool/)** — for auto-saving generated images with metadata
- **[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
---
## Supported Languages
| Language | Status |
| -------- | ------ |
| English | Full |
| Japanese | Full |
| Chinese | Full |
---
## Project Structure
```
ComfyUI-Workflow-Studio/
├── __init__.py # ComfyUI entry point
├── py/
│ ├── wfm.py # Main class & route registration
│ ├── config.py # Path configuration
│ ├── nodes/
│ │ ├── prompt_text.py # WFS_PromptText custom node (positive/negative prompt)
│ │ └── gallery_feeder_node.py # WFS_GalleryFeeder custom node (gallery group → IMAGE)
│ ├── routes/
│ │ ├── workflow_routes.py # Workflow CRUD & analysis API
│ │ ├── nodes_routes.py # Nodes metadata & node sets API
│ │ ├── models_routes.py # Model metadata, preview, CivitAI API
│ │ ├── prompts_routes.py # Prompt presets CRUD API
│ │ ├── settings_routes.py # Settings API
│ │ ├── ollama_routes.py # Ollama proxy API
│ │ ├── eagle_routes.py # Eagle integration API
│ │ └── gallery_routes.py # Gallery tab API (Output + ImagePrompt + Style_Catalog sub-tabs)
│ └── services/
│ ├── workflow_service.py # Workflow file operations
│ ├── nodes_service.py # Node metadata & node sets
│ ├── models_service.py # Model metadata & preview images
│ ├── civitai_service.py # CivitAI API integration & cache
│ ├── prompts_service.py # Prompt presets persistence
│ ├── workflow_analyzer.py # Model/node detection
│ ├── settings_service.py # Settings persistence
│ ├── png_extractor.py # PNG metadata extraction
│ ├── gallery_service.py # Gallery image scanning, .txt sidecar & ponyxlWildcardsVault prompt resolution
│ └── gallery_metadata.py # Gallery per-image metadata store (favorites/tags/memo/groups)
├── templates/
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Metadata/Gallery/Nodes/Models/Settings/Help/AI)
├── static/
│ ├── favicon.svg # Browser tab icon (W+S Wave)
│ ├── css/main.css # Styles
│ └── js/
│ ├── app.js # App initialization & routing
│ ├── workflow-tab.js # Workflow browser
│ ├── generate-tab.js # Generation UI
│ ├── feeder-tab.js # Feeder subtab (Image Loop + Gallery modes)
│ ├── gallery-tab.js # Gallery tab: Output sub-tab (image browser, groups, metadata) + sub-tab switching
│ ├── image-prompt-tab.js # Gallery tab: ImagePrompt sub-tab (visual prompt builder)
│ ├── style-catalog-tab.js # Gallery tab: Style_Catalog sub-tab (visual Style picker)
│ ├── tagger-tab.js # Tagger tab (WD Tagger, DeepDanbooru, Ollama VLM)
│ ├── prompt-tab.js # AI assistant & presets
│ ├── metadata-tab.js # Metadata extraction & display (PNG/WebP/JSON)
│ ├── settings-tab.js # Settings panel
│ ├── comfyui-client.js # ComfyUI WebSocket/API client
│ ├── nodes-tab.js # Node browser & node sets
│ ├── models-tab.js # Model browser & CivitAI integration
│ ├── ai-tab.js # AI TOOL tab (Translation | Chat | TOOLS/VLM | Settings)
│ ├── comfyui-workflow.js # UI-to-API format conversion
│ ├── comfyui-editor.js # Dynamic parameter editor
│ ├── json-highlight.js # JSON syntax highlighting
│ ├── util.js # Shared utilities (escapeHtml, readJsonStorage, getSettings)
│ └── i18n.js # Internationalization
├── web/comfyui/
│ ├── top_menu_extension.js # ComfyUI menu bar integration
│ ├── node_sets_menu.js # Workflow Studio Library side panel
│ └── gallery_feeder_extension.js # WFS_GalleryFeeder canvas widgets (After Gen / Run / Stop)
├── tools/
│ └── import_style_prompt_seed.py # Dev tool: pre-process a wildcards-vault source into ws_image_prompt (not run by the plugin itself)
└── data/ # Fallback data dir (used when ComfyUI user/default/ is not found)
```
---
## License
MIT License
---
## Acknowledgements
- [ComfyUI](https://github.com/comfyanonymous/ComfyUI) by comfyanonymous
- [ComfyUI-Custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) by pythongosssss — Canvas snapshot and PNG workflow embedding implementation reference
- [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) — Plugin architecture and UI pattern reference
- [Ollama](https://ollama.com/) for local LLM inference
- [Eagle](https://eagle.cool/) for image management
- [Pillow (PIL Fork)](https://python-pillow.org/) — server-side thumbnail generation (`data/thumb_cache/`)
- [ComfyUI-Gallery](https://github.com/PanicTitan/ComfyUI-Gallery) by PanicTitan — thumbnail grid UX reference
- [infinite-image-browsing](https://github.com/zanllp/sd-webui-infinite-image-browsing) by zanllp — thumbnail caching and index strategy reference
- [Fooocus](https://github.com/lllyasviel/Fooocus) by lllyasviel — style preset JSON format reference
+462 -164
View File
@@ -1,69 +1,189 @@
# ComfyUI-Workflow-Studio
A comprehensive workflow management and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
A comprehensive workflow, asset management, and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
Browse, organize, and execute workflows directly from a dedicated studio interface — without switching between windows or manually editing JSON.
**📁 Management** — organize all your assets in one studio
- Workflow, model, image, and prompt management
- AI-powered prompt writing assistance, translation, and tag generation
- File drop & Gallery-linked metadata viewing — inspect and reuse generation settings instantly
**⚡ GenerateUI** — a productivity-focused generation tab connected to every other tab
- Batch generation across models, samplers, prompts, and workflows
- Image Feeder for continuous folder-based generation
- Lab: experimental I2I batch generation with independent per-iteration keyframes for Model (Checkpoint/LoRA Single/VAE)/Prompt/KSampler
**📚 Workflow Studio Library** — a multi-function side panel for smooth ComfyUI integration
- Drag & drop models, nodes, prompts, and workflows straight onto the canvas
- **Send to Canvas**: click "Send to Canvas" (Workflow tab) or "Copy & Send Canvas" (Gallery tab) to send the workflow directly to the ComfyUI canvas — UI and API formats both supported
- View metadata from images / JSON, then drop the detected models and prompts onto the canvas
- 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.2.7-green)
![Version](https://img.shields.io/badge/version-0.6.2-green)
## Screenshots
| Workflow Tab | GenerateUI Tab |
|:---:|:---:|
| ![Workflow](docs/screenshot_workflow.png) | ![GenerateUI](docs/screenshot_generate.png) |
| Workflow Tab | Models Tab |
| :-------------------------------------: | :---------------------------------: |
| ![Workflow Tab](docs/1_workflowtab.png) | ![Models Tab](docs/2_modelstab.png) |
| Prompt Tab | Settings Tab |
|:---:|:---:|
| ![Prompt](docs/screenshot_prompt.png) | ![Settings](docs/screenshot_settings.png) |
| Prompt Input Assistance | GenUI Batch |
| :----------------------------------------------------------: | :-------------------------------------: |
| ![Prompt Input Assistance](docs/3_PromptInputAssistance.png) | ![GenUI Batch](docs/10_GenUI_Batch.png) |
| Nodes Tab | Models Tab |
|:---:|:---:|
| ![Nodes](docs/screenshot_nodes.png) | ![Models](docs/screenshot_models.png) |
| Top Bar | Image Edit Tab |
| :----------------------------: | :--------------------------------------: |
| ![Top Bar](docs/5_topbar.png) | ![Image Edit Tab](docs/13_ImageEdit.png) |
| Gallery Tab | Help & Support Tab |
|:---:|:---:|
| ![Gallery](docs/screenshot_gallery.png) | ![Help](docs/screenshot_help.png) |
| WS Library | Library Information |
| :----------------------------------: | :---------------------------------------------------: |
| ![WS Library](docs/6_ws_library.png) | ![Library Information](docs/7_library_Infomation.png) |
| Workflow Studio Library (ComfyUI) | ComfyUI Integration |
|:---:|:---:|
| ![Workflow Studio Library](docs/screenshot_wf_node_library.png) | ![ComfyUI Top Bar](docs/screenshot_comfyui_topbar.png) |
| Video Tab | AI TOOL Tab |
| :----------------------------------: | :--------------------------------------: |
| ![Video Tab](docs/14_videotab.png) | ![AI TOOL Tab](docs/17_aitooltab.png) |
| Lab Tab | Lab Index Image |
| :--------------------------------: | :------------------------------------------: |
| ![Lab Tab](docs/15_labtab.png) | ![Lab Index Image](docs/16_lab_index.png) |
---
## Features
### Workflow Tab
- **Thumbnail / Card / Table views** — switch between view modes to browse your workflow library
<details>
<summary><h3>Workflow Tab</h3></summary>
- **Thumbnail / Table views** — switch between view modes to browse your workflow library
- **Thumbnail side panel** — preview workflow canvas snapshots in the side panel
- **Badge filtering** — filter by user-defined badges (free labels you assign to each workflow)
- **Search** — full-text search across workflow names and metadata
- **Side panel tabs** — Thumbnail preview, JSON viewer with syntax highlighting, and Group management
- **Badge management** — add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)
- **AI summary** — generate workflow descriptions using Ollama
- **Import / Export** — import workflows from files or clipboard, open in ComfyUI directly
- **Default view setting** — persist your preferred view mode (Thumbnail / Card / Table)
- **Import / Export** — import workflows from files or clipboard; **Send to Canvas** button sends the selected workflow directly to the ComfyUI canvas (UI and API formats both supported)
- **Side panel toolbar buttons** (v0.5.0) — selecting a card shows three buttons in the top toolbar: **Load in GenerateUI**, **Load in Video** (loads a MiniMax H3 Image-to-Video, LTX-2.5 (Text/Image/First&Last-Frame to Video), or Wan2.2 (Text to Video) workflow into the Video tab (LTX-2.5/Wan2.2 support: v0.5.4); shows an error toast for workflows that don't contain a supported node), and **Send to Canvas**; the detail modal's duplicate copies of these three buttons were removed in favor of this single toolbar location
- **Default view setting** — persist your preferred view mode (Thumbnail / Table)
- **Search clear (✕)** — inline ✕ button appears inside the search box whenever text is entered; click to clear immediately
- **Clear all filters (✕ Clear)** — rightmost toolbar button; resets search text, group filter, and badge filter (ALL) in one click
</details>
<details>
<summary><h3>Canvas Snapshot (v0.1.2)</h3></summary>
### Canvas Snapshot (v0.1.2)
- **One-click capture** — click the camera button in ComfyUI's top bar to snapshot the current workflow canvas
- **Auto-save as thumbnail** — the snapshot is saved directly to the workflow data folder as a PNG thumbnail
- **Embedded workflow metadata** — workflow JSON is embedded in the PNG (tEXt chunk), compatible with ComfyUI's drag-and-drop import
- **Auto-import** — the captured workflow is automatically imported and appears in the Workflow tab
### GenerateUI Tab (v0.2.4)
- **3-tab layout** — Input / Model / Settings tabs, each with a Raw JSON column on the right for instant preview and direct editing
- **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
- **Settings tab** — KSampler (top) and LatentImage (bottom) in the left column; 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
</details>
<details>
<summary><h3>GenerateUI Tab (v0.3.5)</h3></summary>
- **6-tab layout** — Input / Model / Settings / Feeder / Batch / **Lab** 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; hidden while the Batch or Lab subtab is active (v0.4.6), since those work on workflow copies / their own Plan files rather than the currently loaded workflow
- **Default-workflow snapshot fix** (v0.4.8) — overwriting the loaded workflow under a filename that's currently set as the auto-load **Default workflow** (Settings tab, see below) now also refreshes that cached snapshot; previously only the file on disk was updated, so the old (pre-edit) version — including any checkpoint no longer installed — kept reappearing after every page reload until the default was re-set by hand
- **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
- **Revert button** (v0.3.70) — a ↺ button next to each Apply button reverts the textarea to the node's currently applied value (the reverse of Apply)
- **Emphasis weight editing** (v0.3.70) — select text (or just place the cursor on a word/parenthesis block) and press Ctrl+↑/↓ to adjust `(text:weight)` by ±0.05, A1111/native-ComfyUI style; parentheses are removed automatically when the weight returns to 1.0
- **Mask slot for inpainting** (v0.3.71) — LoadImage slots whose MASK output feeds an inpaint node (e.g. `VAEEncodeForInpaint`) show an additional Mask drop zone; when a mask is set, image + mask are composited into a single RGBA upload (mask baked into the alpha channel) matching ComfyUI's native alpha→MASK extraction — no extra nodes required
- **Placeholder Image + Clear** (v0.3.97) — each LoadImage card gets a **Clear** button (resets that card's pending selection/preview back to empty; doesn't touch the workflow node itself) and a **Placeholder** button; a collapsible **Placeholder Image** section (collapsed by default) at the top of the Image sub-panel configures one shared default — **Color** mode (set Width/Height/Color, generates a solid-color PNG on the fly) or **Image** mode (drop one default image, reused as-is) — remembered across sessions; clicking a card's own Placeholder button immediately replaces just that card's image with the configured default, so multiple LoadImage cards can each be replaced individually with one click
- **Model tab** — Checkpoint, VAE, Diffusion Model (UNETLoader / UnetLoaderGGUF / LoaderGGUF), and Text Encoder (CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — single clip: type + device; dual clip: two clip selectors + type + device) are always shown; **ControlNet** and **Hypernetwork** (with Strength field) are collapsed by default (v0.3.98) since they're used less often — click their header to expand; **LoRA** (Single/Stack tabs) has its own column; all selectors have a filter; Raw JSON on the right
- **Highlight color** (v0.3.98) — the label of each model type above, plus the LoRA column header, turns a distinct color (default bright green, customizable in the Settings tab) when the loaded workflow actually contains that type of node; stays visible even while ControlNet/Hypernetwork are collapsed, so relevance is visible without expanding
- **LoRA Stack Group toggle** (v0.3.92) — for `Lora Loader (LoraManager)` nodes, a **Use Stack Group** checkbox next to the Single/Stack tabs switches what the Stack tab shows and edits: OFF (the default whenever a workflow is loaded) displays and edits the LoRAs actually configured in the workflow's own Lora Manager node — correctly showing every LoRA it holds, not just the first one; ON switches to the LoRA group registered in the Models tab instead; toggling either direction clears the node's LoRA list first, then loads it from the newly selected source, and switching back to OFF restores exactly the list that was present when the workflow was loaded
- **LoRA Bypass button** (v0.4.4) — a ⛔ toggle next to the Refresh Stack group button in the LoRA column header; forces the target LoRA node's strength to 0 (`strength_model`/`strength_clip` for a standard LoraLoader, or every entry's `strength`/`clipStrength` for a Lora Manager node — its LoRA list stays intact, not replaced) without touching the actual ComfyUI node's mode; click again to restore the exact values that were there before toggling; targets whichever node Single/Stack Apply default to (the workflow's Lora Manager node if it has one, else the first LoRA node); clicking a Single or Stack Apply button clears the bypass state so it can't silently reassert itself later
- **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
- **Bypass/Mute node handling** (v0.3.75) — loading a UI-format workflow with Bypass-mode nodes now reroutes their wires to the upstream source (matching same-type input/output slots, recursively through chained bypasses) instead of leaving a dangling reference that failed validation; Mute-mode nodes are excluded without rerouting, same as ComfyUI itself; when either is present, a note listing the affected nodes appears above the Raw JSON search bar in the Input/Model/Settings tabs
- **One-click generation** — queue prompts to ComfyUI without leaving the studio
- **Seed control** — randomize, lock, or manually set seeds
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion
- **Seed control** — randomize, lock, or manually set seeds; seed input and mode selector stacked vertically for readability
- **Style selector** — checkbox and dropdown next to the Reset Workflow button; enable to apply a Fooocus-style JSON to positive and negative prompts at generation time; style files (`*.json`) are loaded from `user/default/Workflow-Studio/style/`; the style's `{prompt}` placeholder is replaced with the original prompt text, or the style is appended if no placeholder exists; `negative_prompt` is appended to the existing negative prompt; styles are applied to a per-generation copy and do not modify the loaded workflow
- **Wildcards inside a Style now expand** (v0.4.7) — an A1111-style `__wildcard__` reference written into a Style's Positive/Negative prompt is expanded at generation time just like one typed directly into GenerateUI; the Style text is merged into the prompt *before* wildcard expansion runs (previously the order was reversed, so a Style's own wildcard references were sent to ComfyUI unexpanded)
- **Create Catalog / Catalog buttons** (v0.3.95) — next to the Style dropdown. **Create Catalog** generates one preview image per Style checked in the Batch tab's Style sub-tab (using the currently loaded workflow, typically T2I), then saves each result into a chosen `ws_style_catalog` subfolder named after the Style (existing files with the same name are overwritten); a modal lets you create a new destination folder or pick an existing one — separate folders are useful for grouping catalogs by checkpoint or by purpose. **Catalog** jumps straight to the Gallery tab's Style_Catalog sub-tab to browse the results (see below)
- **Don't keep a copy in the Output folder** (v0.3.96) — checkbox in the Create Catalog modal; each generation still writes a normal file to the Output folder first (the workflow's own Save Image node always does that), but once its copy has been saved into the catalog folder, checking this deletes that Output-folder original right away — keeps a large catalog run (e.g. every Style at once) from flooding the Output folder with near-duplicate files; if a style's catalog copy fails to save, its Output file is left alone rather than deleted
- **Batch type selector** — check one of the column header checkboxes in the Batch Queue pane (Checkpoint / Lora / Prompt / Workflow / Sampler / Scheduler / Style) to activate that batch type; only one type can be active at a time; the Batch panel below Generate shows the active type, progress, and Pause/Resume/Stop controls
- **Batch tab** (v0.3.18) — dedicated 3-pane layout for assembling the batch queue:
- **Left pane** — 4 tabs: **Checkpoints** (file-tree; Filter / All / None), **Sampler** (KSampler sampler list), **Scheduler** (KSampler scheduler list), **Style** (flat list of all styles from `Workflow-Studio/style/`; All / None buttons)
- **Center pane** — group-based selection with inner tabs (Checkpoint | Lora | Prompt | Workflow); Checkpoint/Lora groups come from the Models tab, Prompt groups from the Prompt tab, Workflow groups from the Workflow tab — check a group to add all its members, expand ▶ to select individually
- **Right pane (Batch Queue)** — 7 columns: Checkpoint / Lora / Prompt / Workflow / Sampler / Scheduler / **Style**; each column header has an enable checkbox (radio behavior: only one at a time); count shown per column; Style batch applies each selected style sequentially to a workflow copy
- **Lora batch prompt sync** (v0.3.69) — for each selected LoRA, its syntax (`<lora:name:strength_model:strength_clip>`) and CivitAI trained words are automatically appended to the Positive prompt (rebuilt from the original prompt each time, not accumulated), then restored to the pre-batch state when the batch completes or is stopped; if a selected LoRA is not yet recognized by ComfyUI's model list, a warning toast suggests a Refresh or restart
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion; improved analysis covers SDXL multi-hop CONDITIONING chains, CLIPTextEncodeSDXL, SDXLPromptStyler, KSamplerAdvanced, and Guider-based "Advanced Sampling" workflows (`SamplerCustomAdvanced`/`SamplerCustom` + `CFGGuider`/`DualCFGGuider`/`BasicGuider` + `RandomNoise` + `KSamplerSelect` + `*Scheduler` — Flux.2 Klein, LongCat, Boogu, HiDream E1, etc.)
- **MultiType widget-value bug fix** (v0.5.4) — a node input declaring a comma-joined MultiType (e.g. LTX-2.5's `LTXVEmptyLatentAudio.frame_rate: "FLOAT,INT"`) was silently dropped from the widget list instead of being recognized as a scalar widget, which shifted every subsequent widget's value onto the wrong input (surfaced as `LTXVEmptyLatentAudio.batch_size` receiving `frame_rate`'s value and video generation failing with "Expected size 1 but got size 25")
- **Video workflow support** (v0.5.2) — loading a MiniMax H3 (or other all-in-one video-generation) workflow now works from GenerateUI too, not just the dedicated Video tab: the Input tab's Prompt field picks up its `prompt` widget, the Image tab picks up its LoadImage-based `first_frame` the same way any other I2I workflow does, and generation runs with a longer timeout since video generation takes much longer than a still image; the result preview shows the generated mp4 inline (`<video>`) instead of trying to render it as an image
- **LTX-2.5 / Wan2.2 support** (v0.5.4) — these follow ComfyUI's regular node-graph pattern rather than an all-in-one node, so they needed their own detection: Positive/Negative Prompt now traces through LTX-2.5's `LTXVDualCFGGuider`/`LTXVConditioning` nodes to the actual prompt text, and the Settings tab's Latent Image section recognizes Wan2.2's `EmptyHunyuanLatentVideo` and LTX-2.5's `EmptyLTXVLatentVideo` (width/height/batch size, plus an added **Length (frames)** field) instead of showing "No EmptyLatentImage node found"; the extended generation timeout now also triggers off a `SaveVideo`/`CreateVideo` node anywhere in the graph, not just an all-in-one node
- **Eagle integration** — auto-save generated images to [Eagle](https://eagle.cool/) with metadata
### Prompt Tab
- **3-column layout** — AI Assistant, Presets editor, and Preset Manager displayed side-by-side
- **AI chat assistant** — powered by [Ollama](https://ollama.com/), generate and refine prompts interactively
</details>
<details>
<summary><h3>Feeder subtab (v0.3.5 / v0.3.42)</h3></summary>
Two independent modes selectable via **[Image Loop] / [Gallery]** toggle buttons at the top of the left pane (persisted in `localStorage`).
**Image Loop mode** — requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder)** custom node.
- **ImageFeeder node control** — select the target node from a dropdown auto-populated from the loaded workflow; edit all node parameters (Directory, Sort Mode, Index, Start/End Index, Batch Size, Seed, Use Selection) and Apply to the workflow
- **Image library** — 3-pane layout: folder tree (left) browsing `user/default/image-loop-data/`, image grid with checkbox selection (center), preview panel with resolution and file size (right)
- **Selection management** — check individual images; All / None buttons for the current folder; selected files are reflected in `selected_files` on Apply
- **Presets** — save the current directory + selection as a named preset; load or delete presets (server-side persistence via `image-feeder-presets.json`)
- **Continuous Run loop** — Run / Stop buttons below the presets; **After gen** mode controls index behavior after each generation:
- **Loop** — advance index and wrap back to 0 when all images are exhausted (runs indefinitely)
- **Increment** — advance index and auto-stop when all images are consumed
- **Fixed** — always use the same index
- **Index sync** — after each generation the node returns `next_index` via WebSocket (`image_loop_node_sync`); the Index field updates automatically
- **Seed** — Run loop uses the right-pane seed setting (Random / Fixed / Increment / Decrement); the node's own Seed field only affects random sort order
**Gallery mode** (v0.3.42) — no external plugin required; uses the built-in **WFS_GalleryFeeder** custom node.
- **WFS_GalleryFeeder node** — reads images directly from a Gallery group and outputs them one at a time; inputs: `group_name`, `index`, `sort_mode` (filename_asc / filename_desc / random), `seed`
- **Node & group selector** — pick the WFS_GalleryFeeder node from the loaded workflow and choose which Gallery group to feed images from; `__Feeder__` group is auto-created on first open
- **Image grid** — center pane shows all images in the selected group; click any image to update the Index to that position
- **After Gen modes** — Loop (wrap at end and continue indefinitely), Increment (stop automatically when last image is reached), Fixed (always use the same index)
- **Run / Stop controls** — left pane Run / Stop buttons manage the generation loop; After Gen combo (loop / increment / fixed), ▶ Run, and ■ Stop widgets are also available directly on the WFS_GalleryFeeder node in the ComfyUI canvas (`gallery_feeder_extension.js`)
</details>
<details>
<summary><h3>Lab subtab (v0.3.87 – v0.5.2)</h3></summary>
An experimental batch generator: runs the workflow currently loaded in GenerateUI N times, letting Model (Checkpoint/LoRA Single/VAE) / Prompt / KSampler each change independently starting at a chosen iteration — unlike the Batch tab's single-axis queue, every column keeps its own list of change points. Never mutates the loaded workflow; every iteration runs on a fresh clone. Works with both I2I and T2I workflows (v0.3.90).
- **Setting / Results / Plan JSON sub-panels** — Setting: image drop zone + 3 keyframe columns + run controls; Results: source image and up to 9 generated thumbnails (click to enlarge); Plan JSON: the current plan as raw editable JSON (v0.3.88)
- **Per-column keyframes** — Checkpoint, LoRA, VAE, Prompt, and KSampler each hold their own fully independent list of `{iteration, value}` keyframes; +/− per column adds/removes the last keyframe (iteration #1 is fixed and can't be removed); any keyframe other than #1 can also be deleted individually from inside its own edit modal (v0.3.93), not just the last one; click a cell to edit its value, the iteration it starts applying from, and a "revert to #1's setting" checkbox; the effective value at iteration N is the latest keyframe with iteration ≤ N, carried forward until the next one changes it; lowering the Batch count below an existing keyframe's iteration doesn't delete or renumber it — a warning toast appears and it just stays dormant until Batch count is raised again (v0.3.93)
- **Model column — Checkpoint / LoRA Single / VAE** (v0.4.2, redesigned v0.4.3) — Checkpoint and VAE (and now LoRA) share one visual "Model" column; a `[C][L][V]` toggle in its header picks which of the three independent keyframe lists the shared cell list, its own +/-, and its edit modal currently operate on — each behaves exactly like its own column (same as Prompt/KSampler), just sharing the Model column's screen space, so adding, removing, editing, reverting, or bypassing a keyframe while viewing one never touches the other two. Each toggle button lights up the same highlight color as GenerateUI's Model tab (configurable in Settings) when the loaded workflow actually contains that node type. A field left blank in a later keyframe's edit modal shows "(inherits: ...)" instead of "(workflow default)" when an earlier keyframe in that same list already set something. LoRA support is Single only (no Stack, matching the experimental scope of this tab); if a LoRA is set but the loaded workflow has no LoRA node at all, Run warns once and skips it rather than auto-inserting one — unlike VAE (which does auto-inject a VAELoader when missing), wiring in a LoraLoader would require rewiring the Checkpoint's model/clip outputs through it
- **Empty state when no matching node exists** (v0.4.5) — Checkpoint/LoRA/VAE each show "No matching node in this workflow" instead of a keyframe list when the loaded workflow has no node that column could actually override, and the column's +/− is disabled too, so no dead "(workflow default)" keyframe row can be created in the first place; VAE still counts as usable whenever a Checkpoint node exists, since its baked-in VAE can still be overridden via auto-injected VAELoader as above
- **Wildcards** (v0.3.93) — Prompt keyframes' Positive/Negative text supports the same A1111-style `__name__` syntax as the main GenerateUI prompt fields; each keyframe is expanded fresh right before that iteration runs, so reusing the same keyframe across iterations can still draw a different random line each time
- **Prompt cell extras** (v0.3.88, refined in v0.3.89, v0.3.93, and v0.3.97) — **Get from GenerateUI** fills Positive/Negative from the workflow currently loaded in GenerateUI; **Get from Image** extracts a prompt from the image currently loaded in Lab's own Image drop zone (same detection as the Metadata tab; no separate file picker); **Get from Previous** (v0.3.97) copies both Positive and Negative wholesale from the keyframe immediately before this one in the same column (e.g. editing #3 copies #2's prompt; not shown on keyframe #1, which has no earlier row); **Clear** (v0.3.97) empties both fields; **Style** row — an **Apply** button merges whichever style is currently selected in GenerateUI's own top-bar Style dropdown into the Positive/Negative text below, comma-separated after any existing text (never clears it) and works regardless of that top-bar's own Style enable checkbox; a checkbox next to it tracks on/off and shows the applied style's name beside itself (not on the button) — unchecking only clears that name label, the already-merged text stays and is yours to edit/delete by hand
- **Keyframe #1 live-reflect** (v0.3.97) — in every column, keyframe #1 shows the currently loaded workflow's own live setting instead of a blank placeholder — for the Model column this covers Checkpoint and VAE only, LoRA is never live-reflected since there's no reliable way to infer "the" active LoRA back out of a workflow node — both in its grid cell (dashed border) and pre-filled into its edit modal, for as long as it hasn't been explicitly saved with an override; saving it — even unchanged — locks that value in as a real override and the dashed/live styling goes away; switching to the Lab subtab always refreshes this against whatever is currently loaded in GenerateUI
- **Bypass checkbox** (v0.3.97) — available on every keyframe including #1; skips that row entirely when picking which setting applies at a given iteration, as if it didn't exist, so whatever was active before it keeps running instead; Lab-internal only, never touches the actual ComfyUI node's mode; disables that row's value fields and its Revert checkbox while checked (mutually exclusive with Revert); the cell shows an amber "⏭ Bypassed" label, taking priority over both the Revert and live-reflect display
- **LoRA node bypass & prompt injection** (v0.4.4) — inside the LoRA keyframe's own edit modal, two checkboxes independent of the row-level Bypass above: **Bypass LoRA node** forces that keyframe's `strength_model`/`strength_clip` to 0 at apply-time — the behavioral equivalent of ComfyUI's node Bypass (mode:4), since the workflow used here is already API-format with no `mode` concept; **Apply LoRA syntax + trigger words to Positive prompt** appends `<lora:name:strengthModel:strengthClip>` plus that LoRA's cached CivitAI trigger words to the Positive prompt, comma-separated, at apply-time — the same format GenerateUI's own Model tab Apply button writes. Switching keyframes (a different LoRA, this checkbox turned off, or the row Bypassed) always strips exactly what the previous iteration injected before adding anything new, so a batch never accumulates every LoRA it has used; the prompt checkbox is disabled automatically while Bypass LoRA node is checked
- **T2I workflow support** (v0.3.90) — a **T2I workflow (no source image)** checkbox in the Image pane skips the source-image requirement and never touches a LoadImage node, so workflows with no image input (e.g. plain `EmptyLatentImage` txt2img) can also use the Model/Prompt/KSampler keyframes; the Image drop zone and "Use generated image for next" are greyed out (not cleared) while it's on; saved with the plan as `t2i_mode`
- **Use generated image for next** — optional checkbox that chains iterations: from iteration 2 onward the previous iteration's first output image is fed back in as the I2I source instead of the original dropped image, using ComfyUI's `"name [type]"` annotated-filename reference (no re-upload needed); disabled together with the Image drop zone in T2I mode
- **Workflow recall** (v0.3.90) — every saved plan records the filename of the workflow that was loaded in GenerateUI at save time (`workflow_filename` in the Plan JSON); after loading a plan, an **Open Workflow** button appears next to it — click to load that exact workflow file back into GenerateUI (asks for confirmation first, since it replaces whatever is currently loaded)
- **Plan files** — Plan Save (silently overwrites the loaded plan) / Save As (always asks for a new name) / Plan Clear; plans are stored as `ws_labplan_<name>.json` in `user/default/Workflow-Studio/lab_plan/` (the `ws_labplan_` prefix is added automatically, v0.3.90 — type just the plain name when prompted), alongside an auto-generated `ws_labplan_<name>.png` index image (a 3-per-row contact sheet of up to 9 result thumbnails)
- **Plan Load** — same drag-and-drop / click-to-browse drop zone as the Image slot; drop a plan's `.json` (read directly in the browser) or any of its index-image `.png`s — since v0.3.91 every index image carries the full plan embedded in it directly (see below), so it's read straight from the file with no server round-trip; older index images without that embedding fall back to fetching a same-named `.json` from the server
- **Plan JSON tab** (v0.3.88) — view/edit the current plan as raw JSON (same shape saved to disk); Refresh re-reads it from the Setting tab, Apply to Setting parses your edits and writes them back into the Setting tab's columns/note/batch/chain-image/source-image/results — the same effect as loading that JSON as a plan file, without saving it first
- **Save index image to Output on Run** (v0.3.90, on by default since v0.3.93) — checkbox in the run controls; when checked, every completed Run also builds the same contact-sheet index image used for Plan files and saves it directly into ComfyUI's own Output folder as `Lab_index_<counter>_.png` (auto-numbered like a normal generated image, right alongside the images that Run just generated); independent of Plan Save, which always writes its own copy next to the plan file regardless of this checkbox; saved with the plan as `save_index_on_run`
- **Index images are self-contained plan files** (v0.3.91) — every index-image PNG, whether from Plan Save/Save As or from Save index image to Output on Run, carries the entire plan embedded directly in the file as a PNG `wfm_lab_plan` chunk; this is what lets the Output-folder copy above work as a Plan Load source even though it has no matching `.json` anywhere
- **Eagle integration** — every image Lab generates is auto-saved to Eagle the same way as GenerateUI's own Generate button, if enabled in the Settings tab; the Output-folder index image above is included too (v0.3.90) once saved
- **Select vs. edit, and keyframe reordering** (v0.4.8) — a single click on a keyframe cell now only selects it (blue outline); double-click to open its edit modal as before. Each column's header (Model / Prompt / KSampler) also gets **▲ / ▼** buttons that swap the selected keyframe with its immediate neighbor, reordering keyframes without retyping them; keyframe #1 (the live-reflecting baseline) can never move, and nothing can be swapped into its slot
- **PG — apply a Prompt tab preset group** (v0.4.8) — a **PG** button on the Prompt column header opens a picker for the Prompt tab's Table-view preset groups (the same groups the Batch tab's checklist uses); choosing one replaces the entire Prompt column with one keyframe per preset in that group's order, starting at #1 (#1 is overwritten, not appended after). If the group has more presets than the current Batch count, Batch count is raised automatically to fit (capped at 50, the Batch input's own limit); anything still beyond that shows the existing "keyframes beyond Batch count" warning instead of being dropped
- **Video workflow support** (v0.5.2) — loading a MiniMax H3 (or other all-in-one video-generation) workflow into GenerateUI and running Lab now works end to end: the Prompt column writes to its `prompt` widget, the KSampler column auto-hides (same "no matching node" treatment as Model sub-columns) since the sampler wired internally is a fixed part of the model's own preset rather than something meant to be tuned per keyframe, the Results grid plays mp4 results inline, and the contact-sheet index image draws each video result's last frame instead of failing silently onto a black square
- **Use generated image for next, now video-aware** (v0.5.2) — when a Run's output is a video, the "Use generated image for next" chain extracts its last frame client-side (canvas) and uploads it as the next iteration's source image, instead of trying to feed the raw mp4 into a LoadImage node
</details>
<details>
<summary><h3>Prompt Tab</h3></summary>
- **3-column layout** — AI Assistant (left), Presets/Preset Manager tab-panel (center), Wildcard/Style support (right)
- **AI chat assistant** — generate and refine prompts interactively using Ollama, LM Studio, Lemonade, or Unsloth (multi-backend: v0.5.4)
- **⚙ Settings modal** (v0.5.4) — replaces the old central Settings-tab panel; opens a dedicated modal (Backend / Connection / Model / Generation / Unload / Save) scoped to this tab only, saved under its own `localStorage` key so it stays independent of the Tagger tab's VLM settings; **Thinking mode** and **Max tokens** apply to every chat request, and an **Unload** button frees the selected model from Ollama/LM Studio/Lemonade (Unsloth has no such API and is shown as unsupported)
- **Image attachment** — attach reference images for vision-capable models
- **Translation** — JA/EN/ZH translation buttons for multilingual prompt creation
- **Prompt presets** — save/load reusable prompt templates (positive & negative) with category support
@@ -71,8 +191,32 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
- **Group management** — create groups, assign/remove presets, delete groups from the Presets panel
- **Clipboard copy** — copy positive/negative prompts individually (PP Copy / NP Copy)
- **GenUI Set** — apply preset prompts directly to the GenerateUI interface
- **Wildcard/Style tab bar** (v0.3.96) — the right pane switches between the wildcard tools below and a Style manager (same pane, two modes)
- **Wildcard input toolbar** — one-click buttons to insert `{|}`, `{n$|}`, `__|__`, `<lora::1:LBW=;>` and other wildcard syntax; wraps selected text when applicable
- **Wildcard file manager** — create, view, and edit `.txt` / `.yaml` wildcard files stored in `user/default/Workflow-Studio/wildcard/`; click a filename in the file picker to insert `__filename__` at cursor
- **Style manager** (v0.3.96) — create, edit, and delete registered Styles (the same ones used by GenerateUI's Style dropdown, the Batch tab, and the Style Catalog), using the same list→editor CRUD pattern as the Wildcard file manager above; each entry has a Name, a Positive prompt (supports the `{prompt}` placeholder, or appends if omitted), and an optional Negative prompt
- **Source-file badge & in-place editing** — each list entry shows its defining file as a small badge next to its name (e.g. `sdxl_styles_diva.json`); renaming a style keeps its position in that same file rather than moving it; a name must be unique across all styles
- **New styles go to a dedicated file** — created via **+ New**, a style is appended to its own `custom.json` inside the style folder, so the bundled style packs are never modified directly
- **+ Add to this file** — while editing an existing style, this button clears the form for a brand-new entry that gets appended to that *same* file instead of the default `custom.json` — the way to add a style into one of the bundled packs
- Saving, renaming, or deleting a style immediately refreshes GenerateUI's Style dropdown, the Batch tab's checklist, and the Style Catalog's name list — no reload needed
- **Form / Table toggle** (v0.4.6) — two top-level tabs at the top of Prompt Tab: **Form** is the one-item-at-a-time editor described above; **Table** shows the same Presets / Wildcards / Style data all at once as editable spreadsheets, useful once there are more than a handful of items to manage
- **Table view — Presets / Presets Group / Wildcards / Style** (v0.4.6) — four sub-tabs, each an editable table built from the exact same data as the Form tab above (changes on either side stay in sync)
- **Row selection & bulk delete** — every table shares a left-most auto-numbered **#** column; click a number to select that row (multiple at once), then use the toolbar's **Delete** button to remove every selected row in one confirm, or **Deselect** to clear the selection — replacing per-row delete buttons, which were too easy to misclick
- **Double-click to edit in a modal** — double-clicking a row's number opens a larger prompt-editing modal instead of the small in-table textarea; Presets/Style show Positive/Negative toggle buttons above one shared textarea (switching preserves unsaved text on the other side), Wildcards shows just the file content; Save writes back and closes the modal, Close discards changes
- **Wildcard syntax toolbar in the Presets modal** (v0.4.7) — the same `{|}` / `__|__` / `<lora>` / file-picker toolbar as the Form tab's Wildcard composer appears above the Presets modal's textarea, since that's where a wildcard reference typically ends up; not shown in the Wildcards or Style modals (the Wildcard modal edits the raw file content itself, and Style prompts have no such wildcard-composer connection)
- **+ New row** — the toolbar's **+ New ...** button adds a blank editable row with small ✓ (Add) / ✕ (Cancel) icons in place of its number
- **Presets table** — **★** (favorite) and **B** (Batch group) columns work as toggle switches, same as the Form tab's Preset Manager; the toolbar's **BC** button clears the whole Batch group at once; **PP Copy** / **NP Copy** copy the single selected row's positive/negative prompt to the clipboard; a **group select + Add to Group** control bulk-adds every selected preset to a chosen group in one click — searching/selecting from the table itself (rather than a long per-group preset picker) keeps group assignment usable once there are many presets
- **★ / B sort toggles** (v0.4.7) — toolbar buttons next to the search box bring favorited and/or batch-selected presets to the top of the list; both can be enabled together (★ takes priority, B breaks ties), and everything else keeps its original relative order; toggling a row's own ★/B while a sort is active re-sorts immediately
- **Presets Group table** — create, rename, and delete groups, with each group's members shown as removable badges; the reserved **Batch** group is not listed here — it's managed entirely through the Presets table's B column and BC button instead
- **Wildcards table** — same files as the Form tab's Wildcard file manager above; editing the File path or the Ext dropdown renames the file (saves the content under the new name, then removes the old file)
- **Style table** — same styles as the Form tab's Style manager above, editable inline the same way as Presets
- **+ Add to this file** (v0.4.8) — select exactly one row whose File badge isn't `custom.json` to enable this toolbar button, bringing the Form tab's same-file-add capability (above) to the Table view too; it adds a blank row targeting that same file (shown as a badge in the File column even before saving); custom.json entries and multi-row selections leave it disabled — use the regular + New Style button for those instead
</details>
<details>
<summary><h3>Settings Tab</h3></summary>
### Settings Tab
- **2-column layout** — left column for all settings; right column shows the Theme panel fixed in place (sticky)
- **Collapsible sections** — all settings organized in accordion panels for a clean layout
- **Theme selection** — 13 built-in themes with visual swatch preview (Dark, Pop, Minimalist, Cyberpunk, Glassmorphism, Neumorphism, Retro Pixel, Pastel, Brutalism, Earthy, Material, Monotone, Corporate)
@@ -80,62 +224,272 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
- **Workflows directory** — configure which folder to scan for workflows
- **Gallery output directory** — configure which output folder the Gallery tab scans for images
- **Eagle connection** — set Eagle API endpoint for auto-save
- **Ollama connection** — configure Ollama server URL
- **CivitAI Host** — choose which site opens when clicking a model link: `civitai.com` (SFW only) or `civitai.red` (unrestricted); saved to `settings.json` and synced to `localStorage` for the Models tab to use without extra fetches
- **CivitAI API Key** — optional Bearer token for authenticated CivitAI access; stored in `settings.json` (excluded from data exports); environment variable `CIVITAI_API_KEY` takes priority if set
- **Default workflow** — set a workflow to auto-load on startup
- **Default Checkpoint** (v0.3.73) — optional checkbox to force every checkpoint loader node's model to a chosen default whenever a workflow is loaded into GenerateUI; a safeguard against generation errors or garbled images from a stale/mismatched checkpoint saved in the workflow file
- ~~AI Assistant Settings~~ (removed in v0.5.4) — the central Ollama backend/URL/model panel that used to live here was replaced by a ⚙ Settings button + modal directly in the Prompt tab and the Tagger tab, each with its own independent configuration (backend, URL, model, Thinking mode, Max tokens, and a model Unload button) — see those tabs below; the AI TOOL tab's own Settings pane is unaffected
- **Video Playback Volume** (v0.5.4) — the video preview's volume is remembered here and shared across every video player in the plugin (Video tab, Gallery tab), instead of resetting to maximum whenever a different video is opened
- **Data Management** — export core settings/metadata/prompts/CivitAI cache to a single JSON file; import to restore data (useful when migrating or reinstalling); API keys are excluded from exports for security
- **Full Backup (ZIP)** (v0.5.2) — additionally covers what the JSON bundle can't represent: folder-based data (AI Skills, Lab Plans, Video Plans, Style presets) and the Tagger SQLite database; two opt-in checkboxes can also include ComfyUI's default workflows folder (`user/default/workflows`) and the Impact Pack's wildcard folder in the export — both of those are export-only and stored under an `_external/` prefix in the ZIP that Restore always skips, since auto-overwriting files a different plugin/ComfyUI core manages would be unsafe; copy them back by hand if needed. Restoring overwrites existing files; restart ComfyUI afterward for either restore path
- **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 prompts, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings
- **RAW JSON Colors** — customize the 6 syntax highlight colors for the Raw JSON editor in Generate UI: Default Text (base), Name/Scheduler (yellow), Title (pink), Width/Height (green), Prompt/Text (cyan), Image/File (red); changes apply immediately on color pick; Reset Defaults restores the original scheme; saved to `localStorage` under `wfm_settings.jsonColors` and applied on startup
- **GenerateUI Model Tab Highlight** (v0.3.98) — pick the color used to mark Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork labels and the LoRA column header in GenerateUI's Model tab when the loaded workflow actually contains that type of node; default bright green; changes apply immediately, Reset Defaults restores it; saved to `localStorage` under `wfm_settings.modelTabActiveColor`; the same color and mechanism also drives the Video tab's field highlighting (v0.5.4, see above)
- **Wildcard Integration** — link the WFS wildcard directory to ComfyUI-Impact-Pack's `wildcards/` directory (directory junction on Windows, symlink on other OS); existing WFS wildcard files are automatically migrated; requires [ComfyUI-Impact-Pack](https://github.com/ltdrdata/ComfyUI-Impact-Pack)
- **G'MIC-Qt Integration** — set the path to `gmic_qt.exe` for the Image Edit Filter tool; download G'MIC-Qt Standalone from `gmic.eu/download.html` (Windows: `gmic_qt-win64.zip`), extract anywhere, then enter the full path to `gmic_qt.exe` and click Save
- **Language** — English / Japanese / Chinese
### Gallery Tab (v0.2.7)
</details>
<details>
<summary><h3>Gallery Tab (v0.3.44)</h3></summary>
- **Output / ImagePrompt / Style_Catalog / Metadata sub-tabs** (v0.3.94, v0.3.95, v0.4.6) — four sub-tabs at the top of the Gallery tab: **Output** (the image browser described below), **ImagePrompt** and **Style_Catalog** (separate visual libraries — see their own sections below), and **Metadata** (embeds the full Metadata tab — see its own section below)
- **Image browser** — browse ComfyUI output images (Thumbnail / Table views) with server-side scanning optimized for 6,000+ image libraries
- **Folder tree root label** (v0.3.90) — the root entry in the folder tree is labeled simply **[root]**, no longer suffixed with the scanned folder's own directory name (which could be a misleading, environment-specific name — e.g. StabilityMatrix installs where the output folder is a symlink named `Text2Img` — even though the folder holds every kind of generated output, not just text-to-image results)
- **Thumbnail / Table views** — switch view modes; Favorites column shown leftmost in Table view
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch tag/group/favorite operations
- **Folder management** — create subfolders ("+ New") or delete the selected folder with all contents ("Del") from the folder tree header
- **File operations** — move or delete individual images from the detail panel's Info tab; bulk Move To..., Export, and Delete File from the multi-select bar
- **Download** (v0.5.0) — a dedicated orange **Download** button in the detail panel's action-button row (next to Tagger); replaces the old preview-image hover overlay, which blocked video playback controls
- **MP4 video support** (v0.5.0) — `.mp4` files are browsable, previewable (detail panel with native `<video controls>`, lightbox, and Compare), and included in favorites/tags/groups/move/delete/export alongside images; server-side thumbnails are generated from the first video frame via PyAV (falls back to a placeholder if PyAV/ffmpeg decoding isn't available); a small ▶ badge overlays video thumbnails in the grid
- **MP4 embedded metadata** (v0.5.1) — the Prompt and JSON tabs now also work for `.mp4` files: reads the `workflow`/`prompt` container tags ComfyUI's `SaveVideo` writes into the mp4 (via PyAV server-side), including all-in-one video-generation nodes that carry their prompt directly on a `prompt` input rather than a separate `CLIPTextEncode`-style node (e.g. `MiniMaxH3ImageToVideo`)
- **Info tab: dimensions & duration** (v0.5.1) — the detail panel's Info tab now also shows image dimensions (width×height) or video duration, in addition to filename, size, date, tags, and memo
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch operations: select group → "Add to Group" / "Remove from Group"; Favorite All / Unfavorite All; Compare (2–4 images); Move To...; **Export** (downloads all selected images as a ZIP file); **Create PSD** (v0.6.0, combines the selected images into one layered PSD file, positioned top-left on a canvas sized to the largest image); **Edit as Layers** (v0.6.0, opens all selected images in the Image Edit tab at once, each as its own layer); Delete File
- **Image Compare** — select 2–4 images with Ctrl+click, then click "Compare" in the Bulk Bar to open a side-by-side lightbox; grid adapts to the number of selected images
- **Prompt search** — text search covers filename, tags, memo, and prompt text (A1111 `parameters` field cached on first detail panel open)
- **Server-side filtering** — filter by group, favorites, or tags with fast server-side set lookup (no full rescan)
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab; **`__Feeder__`** is a reserved group (🔒 prefix) that cannot be renamed or deleted; used by the Feeder Gallery mode to define the generation queue; **FC** button in the toolbar clears all members without deleting the group
- **Thumbnail F button** — cyan overlay button (top-left of each image card) toggles the image's membership in the `__Feeder__` group; cyan and always-visible when the image is in the group; visible on hover only when inactive
- **Favorites** — star images inline without reopening the detail panel
- **Detail panel** — view filename, path, tags, groups, and metadata in a slide-out panel
- **Detail panel** — view filename, path, tags, groups, and metadata in a slide-out panel; four tabs — **Info** / **JSON** / **Groups** / **Prompt**
- **Prompt tab** (v0.4.7) — selected by default (the most frequently checked piece of info shouldn't need an extra click); lists every positive/negative prompt candidate found in the embedded workflow with POS/NEG badges, reusing the exact same list→click→full-text UI as the Metadata tab; extracts from the API-format embedding when available rather than the UI-format one, since a workflow with independent top-level and subgraph sampling chains (e.g. Krea-2) can otherwise have some of its prompts missed
- **Workflow viewer** — Metadata tab displays workflow JSON from PNG embedded data (`prompt` / `workflow` keys) or from workflow saved by the Generate UI tab; **Copy & Send Canvas** button copies the JSON to the clipboard and sends the workflow directly to the ComfyUI canvas (UI and API formats both supported)
- **GenUI button** (renamed from "Load GenUI" in v0.5.0 for readability) — loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab; shows a warning toast if no workflow is embedded or the format is unsupported; Metadata button is styled green, GenUI button uses the primary accent color
- **Image Edit button** — toolbar button; sends the selected image directly to the Image Edit tab as the base layer; PSD files (v0.6.0) are fully decomposed into their original layers instead of being flattened into one image
- **Send GenUI Image button** — toolbar button (next to Image Edit); uploads the selected image to ComfyUI and sets it as the input for the first LoadImage node in the GenerateUI tab; automatically switches to GenerateUI → Input → Image; requires a workflow with at least one LoadImage node to be loaded
- **Send to LI node button** (v0.5.2) — toolbar button (next to Send GenUI Image); uploads the selected image and writes its filename into the `image` widget of the node currently selected on the ComfyUI canvas (falling back to the first LoadImage-type node found) — same destination and cross-window bridge as the Image Edit tab's **Send to LI node** button (renamed from "Send to Workflow" in this same release), so both entry points now share one consistent name; requires Workflow Studio to have been opened from ComfyUI's top menu button
- **Send CC button** (v0.3.69) — toolbar button, shown only when this Gallery tab is embedded as an iframe inside ComfyUI Comic Creator (a separate custom node); sends the selected image directly into Comic Creator's currently selected panel/overlay
- **Search clear (✕)** — inline ✕ button appears inside the search box whenever text is entered; click to clear immediately
- **Clear all filters (✕ Clear)** — toolbar button next to the view-mode (Thumbnail/Table) switch (v0.5.2, moved from the toolbar's rightmost position so it sits with the other display-affecting controls); resets search text, tag filter, group filter, and favorites filter in one click (sort order is preserved)
- **Workflow auto-save** — images generated from the Generate UI tab have their workflow automatically saved to gallery metadata
- **Output folder configurable** — set the scanned output folder from Settings tab
- **Performance** — with folder-level mtime cache (30s TTL) for fast incremental refresh
- **SVG file support** (v0.3.77) — `.svg` files are browsable, previewable (detail panel and lightbox), and included in favorites/tags/groups/move/delete/export alongside raster formats; served as-is with no rasterized thumbnail, since `<img>` scales vector graphics natively at any size
- **PSD file support** (v0.6.0) — `.psd` files are browsable alongside other formats; thumbnails and full-size previews show every layer merged together (hidden layers excluded), rendered server-side via `psd-tools` and disk-cached; the underlying PSD file itself is never modified — only the Gallery preview is a flattened rendering
- **Performance** — server-side 256px JPEG thumbnail generation with disk cache (`data/thumb_cache/`); infinite-scroll paging (50 images per page, IntersectionObserver); folder-level mtime cache (60s TTL); bulk operations use single-request API endpoints
</details>
<details>
<summary><h3>ImagePrompt Gallery subtab (v0.3.94, renamed from Style/Prompt in v0.3.95)</h3></summary>
- **Visual prompt library** — a Gallery sub-tab for browsing reference images and building prompts from them visually, separate from the Output browser; manages a dedicated `ws_image_prompt` folder, created automatically inside the ComfyUI output directory
- **3-column layout** — folder tree (left) | thumbnail grid (center) | prompt builder (right); selecting any folder (including a parent category folder) recursively shows every image in its subfolders too, both in the grid and in the tree's count badges
- **Prompt builder (right pane)** — clicking a thumbnail previews it and its prompt text without adding it yet; **+ Add** appends it as a removable chip under "Selected Prompts" (**Clear All** to reset); **Save** edits and persists the prompt text for that image; **Final Prompt** combines all chips into one comma-separated, freely-editable text; **Copy** sends it to the clipboard
- **Plain-text prompt storage** — each image's prompt lives in a `.txt` sidecar file next to it (same base name, no database) — anyone can add their own entries by dropping an image + matching `.txt` file into a subfolder; the Output Gallery's own detail panel reads and displays the same file when browsing into `ws_image_prompt`
- **ponyxlWildcardsVault format support** — if no `.txt` sidecar exists, prompts are resolved on the fly from a `*.yaml` + `thumbnails/` (also `thumbnails_option2/`) pack placed directly under the folder, using the same key/tag structure as Navimixu's [PonyXL Wildcards Vault](https://civitai.com/models/615967/ponyxl-wildcards-vault) packs — just drop the downloaded pack folder in, no import step required
- **Seed data importer** — `tools/import_style_prompt_seed.py` (dev tool, ships no image data) pre-processes a wildcards-vault-style source folder into portable image + `.txt` pairs under `ws_image_prompt`, for archiving a stable, portable copy instead of relying on the on-the-fly YAML fallback
</details>
<details>
<summary><h3>Style_Catalog Gallery subtab (v0.3.95)</h3></summary>
- **Visual Style picker** — a third Gallery sub-tab for picking a registered GenerateUI Style (`user/default/Workflow-Studio/style/*.json`) by its preview image instead of its name in a dropdown; manages a dedicated `ws_style_catalog` folder, created automatically inside the ComfyUI output directory; populated by GenerateUI's **Create Catalog** button (see GenerateUI Tab above)
- **3-column layout** — folder tree (left) | thumbnail grid (center) | Positive/Negative prompt panel (right); like ImagePrompt, selecting a parent folder recursively shows every image in its subfolders
- **Positive/Negative panel** — clicking a thumbnail reads the Positive/Negative prompt actually embedded in that generated image (reusing the Metadata tab's extraction logic — no separate metadata store), each with its own **Copy** button
- **Select as Style button** — matches the selected image's filename (without extension) against a registered Style name and switches the GenerateUI tab's Style dropdown to it; a visual shortcut into the existing named-Style system, not a one-off apply of the embedded prompt — if the Style was renamed or deleted since the catalog image was created, a "no matching style" toast is shown instead
- **Load in GenerateUI / Open in Metadata Tab buttons** (v0.3.96) — read the workflow embedded in the catalog image itself (a byte-identical copy of the original output image, so it carries the same PNG metadata) and either load it straight into the GenerateUI editor or open the image in the Metadata tab — no need to hunt down the original file in the Output folder, and works even on catalog images created before this feature existed
- **Double-click to enlarge** (v0.3.96) — double-click a thumbnail in the center grid, or the selected-image preview in the right panel, for the same full-size lightbox view as the Output Gallery
</details>
<details>
<summary><h3>Metadata Gallery subtab (v0.3.8, moved from a top-level tab in v0.4.6)</h3></summary>
- **Now inside Gallery** (v0.4.6) — this used to be its own top-level tab; it's now the fourth Gallery sub-tab, to the right of Style_Catalog — everything below works exactly the same as before
- **3-column layout** — Drop zone (left) | Model info (center) | LoRA + Prompt (right)
- **File drop** — drop a ComfyUI-generated PNG / WebP / MP4 or workflow JSON onto the drop zone (or click to open a file picker); PNG/WebP images are shown as a preview
- **MP4 embedded metadata** (v0.5.1) — reads the `workflow`/`prompt` container tags ComfyUI's `SaveVideo` writes into the mp4's `moov/udta/meta` box (parsed client-side, no server round-trip); also recognizes all-in-one video-generation nodes that carry their prompt directly on a `prompt` input instead of a separate `CLIPTextEncode`-style node (e.g. `MiniMaxH3ImageToVideo`)
- **Model extraction** — automatically extracts Checkpoint, VAE, Diffusion Model, and Text Encoder names from the workflow; supports both standard and subgraph-based workflows (Flux.2 Dev/Klein, Qwen-Image-Edit/2511/Layered, Z-Image Base/Turbo, Ernie Image, WAN2.2, Mage-Flow, LongCat, Boogu, HiDream E1, FireRed, Krea-2 Turbo); node types covered: UNETLoader, UnetLoaderGGUF, UNETLoaderGGUF (e.g. HiDream GGUF), CLIPLoader, DualCLIPLoader, TripleCLIPLoader, QuadrupleCLIPLoader (e.g. HiDream 4-CLIP)
- **LoRA extraction** — lists all LoRA models with `strength_model / strength_clip` values
- **Prompt extraction** — lists prompts with POS / NEG badges when positive/negative can be determined; when distinction is not possible (e.g. `SamplerCustomAdvanced`, intermediate nodes, cross-level connections), prompts are shown without a badge as plain **Text**; click any entry to view the full text below
- **CLIP Text Encode edit+ support** (v0.3.92) — `CLIPTextEncodeEditPlus` nodes are resolved using the same RAW / EDIT / front / back combination rule as the node itself, correctly merging the linked `text1` (e.g. a Lora Manager's trigger words) with the editable `text_edit` field instead of showing only one side
- **Prompt actions** — Copy to clipboard, **GenUI:P/N** (set GenerateUI positive/negative prompt), **Prompt:P/N** (set Prompt tab preset positive/negative)
- **Format support** — ComfyUI PNG/WebP/MP4/JSON (standard + Flux.2 / Qwen-Image / Z-Image / Ernie Image / WAN2.2 / Mage-Flow / LongCat / Boogu / HiDream E1 / FireRed / Krea-2 Turbo subgraph workflows), SD WebUI, SD Forge, Fooocus
- **Format note** — supported formats and covered model types are always shown in the left column
</details>
<details>
<summary><h3>Nodes Tab (v0.1.7)</h3></summary>
### Nodes Tab (v0.1.7)
- **Node Browser** — browse all installed ComfyUI nodes from `/object_info` API with Card/Table views
- **Search & Filter** — full-text search, filter by category, package, tags, groups, and favorites
- **Package badges** — color-coded badges generated from package names
- **Node detail panel** — view I/O specifications, edit tags, manage groups
- **Node Sets** — save multiple nodes + connections as reusable sets from the ComfyUI canvas
- **Right-click context menu** — "Save as Node Set" option on any node in ComfyUI
- **Multi-select** — Ctrl+click to toggle individual nodes, Shift+click for range selection; bulk action bar appears with: add to group / remove from group / create & add group / bulk favorite / unfavorite
- **Search clear (✕)** — inline ✕ button appears inside the search box whenever text is entered; click to clear immediately
- **Clear all filters (✕ Clear)** — rightmost toolbar button; resets search text, category, package, tag, group, and favorites filter in one click
</details>
<details>
<summary><h3>Models Tab (v0.2.3)</h3></summary>
### Models Tab (v0.2.3)
- **Model Browser** — browse all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding) with sub-tab switching
- **Thumbnail / Card / Table views** — switch between view modes with pagination (24 items per page)
- **Thumbnail / Table views** — switch between view modes with pagination (24 items per page); Table view includes **Type** and **Base Model** columns sourced from cached CivitAI data, displayed between the Subdirectory and Extension columns; Enable/Disable column labeled **E/D**
- **Table column sort** — click any column header to sort ascending (▲), click again for descending (▼), click a third time to clear; active column highlighted in accent color
- **Search & Filter** — full-text search, filter by tags, groups, and favorites
- **User-defined badges** — assign free-label badges to models; badge colors shared with the Workflow tab palette
- **Side panel tabs** — Info (file path display with click-to-copy, tags, memo), Groups management, CivitAI integration
- **CivitAI integration** — fetch model metadata by SHA256 hash, view base model, trained words, tags, and model page link
- **Batch CivitAI fetch** — one-click batch fetch for all models of a type with SSE progress streaming
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder)
- **Group management** — create, rename, delete groups and assign/remove models
- **Side panel tabs** — opens to CivitAI tab by default when a model is selected; Info (file path display with click-to-copy, tags, memo), Groups management, CivitAI integration
- **CivitAI integration** — fetch model metadata by SHA256 hash; side panel shows **Type** (badge), **Base Model**, **Hash** (BLAKE3/SHA256, click to copy), trained words, tags, and model page link; model link opens in the site selected in Settings (civitai.com or civitai.red)
- **CivitAI panel — Info / Sample sub-tabs** — Info tab shows model details (name, type, base model, hash, trigger words, tags, description); Sample tab shows all sample images (count shown in tab label); clicking any image opens the full-size version in a new tab
- **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, 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
- **Enable / Disable models** — hide models from ComfyUI by renaming the file extension (`.disabled` suffix); toggle per card (⏸ button), per group (Enable All / Disable All), or filter by status (All / Enabled / Disabled)
- **Multi-select & bulk operations** — click the green **Select** button to enter selection mode and check multiple models; the bulk action bar is organized in three rows:
- **Group row** — select an existing group and **Add** / **Remove**, or type a new name and **Create & Add**
- **Badge row** — select a badge and **+Badge** / **−Badge** to apply or remove from all selected
- **File row** — select a destination subfolder (or type a new folder name and create it) then **Move** to relocate the model file with all sidecar files; **Delete Files** (right end) permanently removes selected models and all associated files
- **Search clear (✕)** — inline ✕ button appears inside the search box whenever text is entered; click to clear immediately
- **Clear all filters (✕ Clear)** — rightmost toolbar button; resets search text, tag filter, folder filter, group filter, favorites filter, and status filter in one click
### Workflow Studio Library (ComfyUI Side Panel) (v0.2.5)
- **Workflows tab** — browse favorite workflows (All / ★ Favorites / Groups / By Badge sub-tabs), ★ star shown for favorites in All view
- **Nodes tab** — browse favorite nodes (All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs), ★ star shown for favorites in All view
</details>
<details>
<summary><h3>Tagger Tab (v0.3.38)</h3></summary>
- **3 sub-tabs** — Single / Batch / DB for single-image tagging, folder batch processing, and tag database management
- **Model support** — WD Tagger (ONNX, NCHW/NHWC auto-detect), SwinV2 (ONNX), DeepDanbooru (.h5, requires TensorFlow); place each model in its own subfolder under `ComfyUI/models/tagger/<model-name>/` containing the `.onnx` + `selected_tags.csv` (or `.h5` + label file)
- **Threshold sliders** — General threshold (default 0.35) and Character threshold for `character:` prefix tags (default 0.85); sliders update the display value in real time
- **VLM tagging** (v0.3.38, multi-backend: v0.5.4) — optional vision model alongside WD Tagger, running on Ollama, LM Studio, Lemonade, or Unsloth through the same unified backend used by the Prompt tab; results from both models are merged into one comma-separated tag string
- **⚙ Settings modal** (v0.5.4) — a Settings button (Single and Batch tabs) opens the same modal component as the Prompt tab's AI Assistant (Backend / Connection / Model / Generation / Unload), but saved under its own `localStorage` key so Tagger's VLM backend/model choice is independent of the Prompt tab's; **Thinking mode** and **Max tokens** apply to VLM requests too, and the **Unload** button frees the selected model (Ollama/LM Studio/Lemonade; Unsloth unsupported) — replaces the old Tagger-only direct Ollama URL/model fields
- **Single tab** — drag & drop an image onto the preview area or click Upload; Gallery detail panel **Tagger** button opens the selected image directly here
- **Single output options** — (1) **GenUI:P** — appends tags to the GenerateUI tab's positive prompt and immediately applies to the loaded workflow; (2) **Send to Prompt** — appends tags to the Prompt tab's positive textarea; (3) **Save to Gallery** — saves tags to Gallery image metadata (requires image opened from Gallery); (4) **Write to File** — embeds tags into JPEG EXIF (`ImageDescription`) or PNG `tEXt` chunk (`Tags` key), other formats get a `.tags.json` sidecar; (5) **Save to DB** — stores in internal SQLite database
- **Batch tab** — enter a folder path, configure WD Tagger thresholds and (via the same ⚙ Settings modal as Single) the VLM backend; output options: **Save to DB** (default on), **Write to File** (EXIF/PNG metadata), **Write .txt** (creates `<filename>.txt` alongside each image with all tags); real-time progress bar and log; Stop cancels after the current image
- **DB tab** — searchable SQLite database of all tagged images; click a row to open the edit panel and modify WD Tags / VLM Tags; Save updates the record, Delete removes it; Export CSV downloads all records; **bulk delete** (v0.5.8) — per-row checkboxes plus a header checkbox to select/deselect all, a confirmation dialog before deleting the selected records
- **Dependencies** — install into ComfyUI's embedded Python: `python_embedded\python.exe -m pip install -r requirements.txt`; for GPU inference use `onnxruntime-gpu`; TensorFlow (DeepDanbooru) is optional and commented out in `requirements.txt`
</details>
<details>
<summary><h3>Image Edit Tab (v0.3.65)</h3></summary>
- **Layer-based image editor** — compose images with multiple layers (Image, Text, Draw, Mask types) and export the composite as PNG or a fully layered PSD
- **Loading images** — drag & drop onto the canvas, **File Open** button (renamed from Upload in v0.6.0), or send from the Gallery tab via the **Image Edit** toolbar button; first image becomes Layer 1 (auto-locked), subsequent images are added as new layers scaled to fit the canvas
- **Open PSD button** (v0.6.0, next to File Open) — loads a layered PSD file from disk and decomposes it into individual layers, restoring each layer's position, size, visibility, opacity, and blend mode; groups and non-raster layers (adjustment layers, etc.) are flattened into their rendered appearance
- **Close button** (v0.6.0, next to Open PSD) — closes the current document after a confirmation prompt, discarding all layers and unsaved edits and returning to the empty placeholder view
- **New button** — create a blank canvas with custom dimensions (WxH prompt); clears all existing layers and automatically adds an empty Layer 1 (v0.3.70)
- **Tools** — Select (V), Draw (B), Text (T), Shape (S), Fill (G), Mask (🎭), Blur (≈), BG Remove (⬚), Filter (★), Inpaint (🩹); tool options bar updates per active tool
- **Select** — click to select; drag to move; drag corner handles to resize; drag circle handle to rotate; Flip H / Flip V / Rotate angle in the options bar; double-click a text layer to re-edit its content
- **Draw** — freehand brush; options: color, brush size, blend mode; paints directly onto the active draw layer while all other layers remain visible; brush cursor shown as a size-accurate circle; strokes can start from outside the canvas margin and continue past the edge; **pen tablet support** (v0.6.2) — brush size and opacity respond to pen pressure (mouse behaves exactly as before); the canvas listens for Pointer Events so pen, touch, and mouse all work through the same code path
- **Text** — click to place; configure font, size, bold/italic, align, and color; placed as an exact-size text layer sized to the measured bounding box; double-click to re-edit
- **Shape** — drag to draw geometric shapes (Rect / Ellipse / Line / FreeLine); options: shape type, Rounded toggle (Rect/Ellipse), Fill color, Stroke color + width, Opacity; each committed shape becomes an independent draw layer; Stroke None hidden for Line/FreeLine (stroke always active)
- **Fill** (v0.6.2) — bucket fill; click a contiguous same-color region on the active layer to flood-fill it (scanline-based, ported from the Comic Creator plugin's Image tab); **Properties pane**: Mode (Solid / Gradient) — Solid: Color picker; Gradient: Shape (Linear / Radial), a draggable color-stop Ramp (click a stop to select it, drag to reposition, +/- to add/remove stops, color swatch to edit the selected stop's color), and a Direction dial (drag to set angle/radius); both Tolerance (0–255, color-match threshold) and Opacity apply to either mode; Ramp and Direction dial are pointer-event based with pointer capture, so pen tablets work the same as mouse
- **Mask** — 7 sub-tools for painting masks onto a dedicated mask layer; click **Mask** on the second row of the Layers header (renamed from "M" and moved to its own row in v0.6.0) to add a mask layer (Mask tool activates automatically); clicking a mask layer in the list also switches to the Mask tool; **Tool Options bar**: sub-tool buttons (Paint / Color / Alpha / Text / Vector / Shape / SAM3), Invert checkbox, Overlay color picker (default red), Blur slider (0–50 px); the overlay is only shown for the currently active mask layer, other mask layers stay hidden until selected (v0.3.70); SAM3 requires Mask Editor One (disabled when not installed); Color / Alpha / Text / Vector / Shape work without Mask Editor One; **Properties pane — Paint**: Mode (Add / Erase), Size (1–200 px), Hardness (0–100%); brush size responds to pen pressure on a tablet (v0.6.2, same as the Draw tool); **MASK EDITOR ONE section** (Paint sub-tool, visible when installed): Select opens the ABR stamp-brush library; ✕ clears back to Circle; when an image brush is active, Hardness is disabled and Spacing (5–100%), Angle (0–359°), Sz Jitter (0–100%), Rot. Jitter (on/off) appear; **Edit in Mask Editor One →** (v0.4.0) — sends the current canvas composite (plus the active mask layer's content, if one is selected) to a MaskEditorOne node on the ComfyUI canvas — the currently selected node if it is one, otherwise the first MaskEditorOne node found in the graph (same selection logic as **Send to LI node**) — and opens its full interactive editor (paint, SAM3, BiRefNet, shapes, etc.) in the ComfyUI browser tab; clicking Apply there imports the result back here as a new mask layer; requires Workflow Studio to have been launched from ComfyUI's top-menu button and at least one MaskEditorOne node to exist on the ComfyUI canvas; **Properties pane — Color**: click canvas to flood-select pixels by color similarity; Mode (Add / Subtract), Tolerance (0–255), Feather % (0–100); **Properties pane — Alpha**: extract the active layer's transparency as a mask; Threshold, Invert checkbox, Extract Alpha button; **Properties pane — Text**: click canvas to open a stamp overlay — enter text, set Font / Size / Bold / Italic / Align / Mode (Add / Erase), Stamp or Ctrl+Enter to apply; multi-line supported; **Properties pane — Vector**: click to add Catmull-Rom spline points; Enter (or click first point) closes and fills the polygon; Backspace removes the last point; Esc resets; Mode (Add / Erase); **Properties pane — Shape**: drag to draw Rect or Ellipse; hold Shift for square/circle; blue dashed outline preview while dragging; Mode (Add / Erase); **Properties pane — SAM3**: enter a text prompt, set Max candidates (3/6/9/12), click Segment; select candidate thumbnails (multi-select), Apply Selected (N) applies with current Mode; **Mask layer A/S operation**: A/S toggle — Add (green) composites normally, Subtract (red) cuts the mask from below; **✂ clipping mask button** clips the layer below to the painted area; brush cursor shown as size-accurate circle; strokes can start from outside the canvas margin and continue past the edge
- **Blur** — **Whole Blur**: Gaussian blur to the entire active layer with intensity slider (1–50 px); **Whole Mosaic**: pixelation mosaic with block-size slider (5–100 px); **Rect Blur / Rect Mosaic**: enable the toggle then drag a rectangle on the canvas to apply blur or mosaic to that region only (blue preview for blur, orange for mosaic); Rect Blur and Rect Mosaic are mutually exclusive; all operations support Undo
- **BG Remove** — remove the background from the active layer; **Lightweight (@imgly)**: runs entirely in the browser via CDN (no server required; ~40 MB model downloaded on first use); **BiRefNet**: high-quality removal via Mask Editor One's Python backend (requires Mask Editor One installed and `birefnet.safetensors` in `ComfyUI/models/background_removal/`); **New Layer** option (default on) adds the result as a new layer above the original; when off, replaces the active layer in-place
- **Filter (G'MIC)** — apply G'MIC-Qt filter effects to the active image layer; click **Edit with G'MIC** to launch G'MIC-Qt GUI; select a filter and click OK — a "G'MIC-Qt filter output" window appears; close it to save the result back as the active layer; requires G'MIC-Qt Standalone installed and path configured in Settings → G'MIC-Qt Executable Path
- **Inpaint** (v0.3.71) — composites the visible layers plus a Mask layer into one RGBA image (mask baked into the alpha channel) and applies it to the first inpaint-capable LoadImage node in the workflow currently loaded in GenerateUI (a node whose MASK output feeds something like `VAEEncodeForInpaint`); also supports workflows built around the **Mask Editor One** custom node (`comfyui-mask-editor-one`) instead of LoadImage — image/mask are pushed via its node_id-keyed server cache and `layer_data` widget; **Properties pane**: Positive/Negative prompts, Grow Mask By (applied to the VAE Encode (for Inpainting) node), Denoise (applied to KSampler), Run button; **Use dedicated workflow** checkbox — when off, generates against the workflow currently loaded in GenerateUI; when on, pick a saved workflow from the dropdown to load, edit, and generate entirely in the background without disturbing what's shown in GenerateUI; the result image is shown back in the Properties pane when generation completes; requires a Mask layer painted first (Mask tool)
- **Layer panel** — layer list with visibility (👁/🚫), lock (🔒/🔓), and clipping-mask (✂) toggles; opacity slider; type icons (🖼 image / T text / ✏ draw / ⬚ mask); Layer 1 is automatically locked on first image load; header is arranged in two rows (v0.6.0) — +, **⧉ Duplicate**, −, ↑, ↓ on top, **Mask** alone below
- **Duplicate layer (⧉)** (v0.6.0) — copies the active layer, including its pixels, position, size, opacity, blend mode, and visibility, and inserts the copy directly above the original as the new active layer; works on any layer type (image, draw, text, mask)
- **Layer lock** — locked layers show an orange bounding box and 🔒 icon on the canvas; move/resize/rotate are disabled while locked; click the 🔓 button in the layer row to unlock
- **Text quality** — text layers are rendered at their measured bounding-box size; resizing with the Select tool regenerates the canvas at the new display resolution so text stays sharp
- **Export** — Save PNG (download composite locally); **Save to Gallery** (saves to Gallery root folder with a timestamped default name `wfs-image-YYYYMMDDHHmmss`); **Save PSD** (v0.6.0, downloads a layered PSD file with every layer preserved separately — position, rotation, flip, and scale are baked into each layer's pixels since PSD layers cannot store a rotation angle, while opacity, blend mode, and visibility are kept as real, editable PSD layer attributes; clipping masks are merged into their target layer since PSD's native layer-mask mechanism isn't used); **Send to LI node** (renamed from "Send to Workflow" in v0.5.2) — uploads to ComfyUI's input folder via `/upload/image`, then writes the resulting filename directly into the `image` widget of the node currently selected on the ComfyUI canvas (falls back to the first LoadImage-type node found); requires Workflow Studio to have been launched from ComfyUI's top-menu button so the ComfyUI tab is reachable; the Gallery tab's toolbar has the same button (v0.5.2, see Gallery Tab below) so a selected Gallery image can be sent the same way without going through Image Edit first
- **Canvas navigation** — scroll-wheel zoom, Space + drag to pan; zoom indicator in the bottom bar
- **Undo / Redo** — Ctrl+Z / Ctrl+Y (or toolbar buttons); keyboard shortcuts: V (Select), B (Draw), T (Text), S (Shape), G (Fill), Delete (remove selected layer when 2+ exist)
</details>
<details>
<summary><h3>Video Tab (v0.5.0 – v0.5.7)</h3></summary>
- **Dedicated video generation UI, independent of GenerateUI** — a purpose-built tab for MiniMax H3 (Image to Video), LTX-2.5 (Text / Image / First & Last Frame to Video), and Wan2.2 (Text to Video) workflows (LTX-2.5/Wan2.2: v0.5.4); does not share state with the GenerateUI tab, and model selection (UNet/CLIP/VAE/Audio VAE) is fixed to the loaded workflow's own defaults rather than editable here
- **Plan / Edit subtabs** (center panel, batch redesign in v0.5.5) — a **plan** is a sequence of timeline blocks, each a fully self-contained generation job with its own Prompt, Duration, and First/Last Image; split the timeline with **+ Split** / **+ Block** / **Delete**, then **Run** to generate every block in order (Pause/Cancel work mid-run) — a plan with a single block behaves exactly like the old one-shot form. First Image can be None, an explicit image, or "use previous block's last frame" (chaining — an explicit Last Image on the previous block always wins over extracting one from its generated output). Save / Save As / Clear a plan (`ws_videoplan_*.json`, with a PNG contact-sheet thumbnail that embeds the full plan data so dropping the image back on works too); Edit is reserved for future video-editing tools
- **Base settings row** (topbar, v0.5.7) — Aspect Ratio / Megapixels / Multiple / Duration (seconds) / Noise Seed on one row — Duration always reflects the currently selected block (each block keeps its own value), the rest are plan-wide — plus a second row of model-specific fields: Width / Height (become directly editable for workflows with no Resolution Selector node, e.g. Wan2.2 and LTX-2.5's First & Last Frame to Video), Turbo Mode / Strength / Steps (MiniMax H3's turbo LoRA — Turbo Mode doubles as Wan2.2's own turbo toggle, sharing one field), and Prompt Enhance (LTX-2.5 only). Every field in both rows is enabled only when the loaded workflow actually has it — see Field highlight color below (one exception: Wan2.2's Text-to-Video variant doesn't expose Noise Seed at all, so it alone leaves that field disabled)
- **Asset / Project subtabs** (sidebar, v0.5.5) — **Asset** browses generated videos through three groups: **Video Assets** (a manually-curated keeper group you organize yourself, on your own schedule), **Video Temp** (every plan run's output lands here automatically regardless of whether the plan itself was saved — a **Clear Video Temp** button in the Gallery tab's detail panel empties it in one click), and **All Video Assets** (the union of both); selecting a video shows it in the center panel's left preview and lets you tag/memo it or jump straight to the full Gallery tab. **Project** lists every saved plan file (thumbnail, block count, last updated) — click one to load it into the Plan editor, or delete it with the × button; either sidebar panel collapses back down when its own tab is clicked again
- **Two center previews** (v0.5.5) — the left preview shows either the video currently selected in the Asset subtab or whatever's dropped/picked in the **Video Source** panel to its left (**Clear** resets it to empty); the right preview always shows the most recently generated clip. The Frame/GIF tools act on whichever preview was touched most recently
- **First Frame / Last Frame are both optional** — leaving First Image empty runs the workflow text-only (the node is simply left unconnected — a "bypass"); workflows that don't even include a LoadImage node for First Frame are supported out of the box (Wan2.2's Text-to-Video graph has neither slot at all), and a LoadImage node is only injected into the graph on the fly if an image is actually supplied
- **Semantic node lookup, not hardcoded IDs** (generalized in v0.5.4) — detects which of the three families is loaded from its subgraph's internal node types (or, for Wan2.2, the subgraph's own name — it has no distinctive internal node type), then locates its Resolution Selector and LoadImage node(s) by the subgraph's *public input label* (`prompt`, `duration`, `width`, `first_frame`, `last_frame`) rather than a fixed slot index — so it keeps working even though the three families expose those inputs under different internal names; a workflow no longer needs to match any bundled reference file's exact node IDs, and no fallback test workflow is auto-loaded on tab open
- **Field highlight color** — Prompt / Duration / First Image / Last Image / Aspect Ratio / Megapixels / Multiple / Noise Seed / Width / Height / Turbo Mode / Strength / Steps / Prompt Enhance labels turn the same highlight color as the GenerateUI Model tab (shared setting, customizable in the Settings tab — see below) when the loaded workflow actually exposes that field; e.g. a Wan2.2 workflow (no Resolution Selector node) leaves Aspect Ratio / Megapixels / Multiple unhighlighted while Width / Height light up instead
- **Load in Video** (Workflow tab) — load any workflow containing a MiniMax H3 Image-to-Video node, an LTX-2.5 Text/Image/First&Last-Frame-to-Video node, or a Wan2.2 Text-to-Video node straight into this tab from the Workflow tab's side-panel toolbar (next to Load in GenerateUI) — starts a fresh single-block plan seeded from the workflow's own current values; unsupported workflows show an error toast instead of loading
- **Frame tab** (right panel) — captures the active preview's current playback position as a still frame: play/seek to the position you want, click **Capture Frame** (client-side canvas, no server round-trip), then **Save to Output** to write it as a PNG into ComfyUI's own Output folder (auto-numbered, same pattern as other generated images)
- **GIF tab** (right panel) — converts the active preview to an animated GIF; set Start/End (seconds), FPS, and an optional Max Width, then **Convert to GIF** — the server decodes the video (PyAV) and encodes an animated GIF (Pillow), both dependencies ComfyUI itself already requires, so no ffmpeg binary or extra install is needed; the result is saved into ComfyUI's Output folder and previewed inline
- **Playback volume** — the preview player's volume is saved to the Settings tab and shared across every video player in the plugin (Video tab, Gallery tab), so it no longer resets to maximum each time a different video is opened
</details>
<details>
<summary><h3>AI TOOL Tab (v0.3.14)</h3></summary>
- **4-pane layout** — Translation | Chat | TOOLS | Settings; all panes always visible simultaneously; no sub-tab switching required
- **Translation pane** — translate text between Japanese, English, Chinese, or a custom Free language using Ollama, LM Studio, Lemonade, or Unsloth; language selectors with ⇄ swap button (swaps both language selectors and text content); selections saved automatically
- **Reliability fix** (v0.3.98) — switched from a raw single-string prompt to a system-role chat request (Ollama `/api/chat`, LM Studio/Lemonade `/v1/chat/completions` with a `system` message) so small local models follow the "translation only" instruction more reliably; output is cleaned of common LLM preambles/quotes, and a warning toast appears if the model appears to have echoed the source text unchanged instead of translating it
- **Chat pane** (v0.3.40) — multi-turn conversation with the LLM; full conversation history sent each turn for context; Enter to send, Shift+Enter for a newline; Clear button resets history; Ollama uses `/api/chat`, LM Studio, Lemonade, and Unsloth use `/v1/chat/completions`
- **Chat pane — image generation via Tool Calling** (v0.3.73) — if the selected model supports tool calling and the user asks for an image, a `generate_image` tool is invoked and the request runs through the same generation pipeline as the GenerateUI Generate button, with the result shown inline in the chat; an "Allow image generation" checkbox in the input row toggles this on/off (default on); the workflow used is the one currently loaded in GenerateUI, or a dedicated saved workflow configured in the Settings pane; models verified to work well for tool calling and vision: **Gemma 4:e4b**, **Qwen 3.5:9b**, **Ministral 3:3b** (Ollama)
- **Chat pane — generate_image extra parameters** (v0.4.4) — besides `prompt`/`negative_prompt`, the tool call also accepts optional `steps`, `cfg`, `sampler_name`, `scheduler`, `denoise`, `seed`, `width`, `height`, `batch_size` (number of images produced in that one call), and `aspect_ratio` (a ratio preset like `3:2`, resolved against the node's actual COMBO options via `/object_info` and applied only if the workflow has a **Resolution Selector** node feeding width/height — ignored otherwise); anything the model doesn't supply keeps the loaded workflow's own current setting; `batch_size` > 1 shows every generated image inline in the same chat bubble
- **TOOLS pane (VLM)** — drop an image into the 110px drop zone, select a task (Describe Image / Create Prompt / Create Tags), and click Run to analyze with a vision model; result shown in the output area with a Copy button
- **TOOLS pane — shared Chat attachment** (v0.3.74) — an image dropped in the TOOLS drop zone is also usable as the Chat pane's attachment: it's sent to the LLM as vision input, and used as the base image when `generate_image` runs image-to-image; a ✕ button clears it (from either the TOOLS preview or the Chat attachment indicator); it stays attached across turns until explicitly cleared
- **TOOLS pane (Wildcards)** (v0.3.40) — select "Create wildcards" from the task dropdown; enter a category name and count; click Run to generate plain-text wildcard entries one per line (no markdown, no numbering); result can be copied directly into wildcard `.txt` files
- **Chat pane — image-to-image (I2I)** (v0.3.74) — when an image is attached and `generate_image` is invoked, the attachment is uploaded and swapped into the target workflow's LoadImage node instead of running text-to-image; the target workflow is the one currently loaded in GenerateUI, or a dedicated I2I workflow configured in the Settings pane
- **Chat pane — SVG generation, no ComfyUI workflow involved** (v0.3.77) — the LLM can also produce SVG graphics directly as text; if a reply contains SVG code (wrapped in a markdown code fence or written directly as a bare `<svg>...</svg>`), it's rendered inline as a preview and a "Save to Gallery" button writes it as a `.svg` file to the Gallery tab's output folder; unlike the Tool Calling image generation flow above, this is plain text pattern matching, so it works with any model regardless of tool-calling support
- **Chat pane — Skills** (v0.3.79) — select a `.md` skill file from a dropdown above the message list to prepend its instructions to the conversation as a system prompt (not shown in the visible chat log); a pencil button opens an in-pane manager (list + inline editor, same pattern as the Prompt tab's wildcard file manager) to create, edit, or delete skill files stored in `user/default/Workflow-Studio/ai_skills/`; a file's `---`-delimited frontmatter (`name`/`description`) is shown in the dropdown; two starter skills are bundled — **SVG Icon Generator** (explicitly decomposes the subject into parts before drawing, which markedly improves recognizability from small local models) and **Skill Creator** (interviews you conversationally and drafts a new skill as a ```skill code block; a "Save as new skill" button appears under such replies and opens the manager pre-filled with the draft)
- **Settings pane** — choose backend (Ollama / LM Studio / Lemonade / Unsloth), set the API URL, test connection, select a model (with refresh button), and configure Free language names for translation source and destination
- **Unsloth backend** (v0.3.99) — Unsloth Desktop's OpenAI-compatible API always requires an API key, even for local access; unlike the other backends it's proxied server-side (`py/routes/unsloth_routes.py`, `POST /api/wfm/unsloth/proxy`) so the key never reaches the browser: set `UNSLOTH_API_KEY` in a `.env` file in the plugin folder (copy `.env.example`, loaded via `python-dotenv` in `prestartup_script.py`) and restart ComfyUI; also requires **"Auto model switching (OpenAI API)"** to be turned on in the Unsloth Desktop app's own Settings screen — with it off, requests fail with HTTP 404 unless a model was already manually loaded in the Unsloth Studio UI
- **Settings pane — Chat Image Generation** (v0.3.73) — "Use dedicated workflow" checkbox lets Chat-triggered image generation use a saved workflow of your choice instead of the one currently loaded in GenerateUI, without disturbing what's shown there (same pattern as Image Edit's Inpaint dedicated workflow)
- **Settings pane — Chat I2I Generation** (v0.3.74) — same "Use dedicated workflow" pattern as above, but for image-to-image generation when an image is attached; independent of the text-to-image dedicated workflow setting
- **Settings pane — Generation** (v0.3.98) — **Thinking mode** toggle (off by default; sends Ollama's `think` flag, and regardless of backend, any `<think>...</think>` block is stripped from the output when off so reasoning models don't clutter Translation/Chat/TOOLS results) and **Max tokens** (Ollama: `options.num_predict`; LM Studio/Lemonade/Unsloth: `max_tokens`; `0` = unlimited)
- **Model unload** (v0.5.4) — an Unload button next to the model selector frees VRAM/memory by unloading the currently selected model from Ollama (`keep_alive:0` via `/api/generate`, the officially documented method — Ollama has no dedicated unload endpoint), LM Studio (`/api/v1/models/unload`), or Lemonade (`/api/v1/unload`); Unsloth exposes no equivalent API and the button is disabled for that backend
- **Settings shared** — settings saved to `localStorage` under `wfm_ai_settings`; shared with the Library panel's AI TOOL tab so configuration is consistent across both interfaces
- **Backend support** — Ollama (`/api/generate` for text, `/api/chat` for conversations, `/api/tags` for model list); LM Studio and Lemonade via the OpenAI-compatible API directly from the browser (`/v1/chat/completions`, `/v1/models`); Unsloth via the same OpenAI-compatible API but relayed through a server-side proxy that attaches the `Authorization: Bearer` header; VLM images sent as base64 (`images:[]` for Ollama, `image_url` content block for LM Studio/Lemonade/Unsloth)
- **URL security** — backend URL validated via `new URL()` to enforce `http://` or `https://` scheme
- **Lemonade's other endpoints (not integrated)** — Lemonade Server also exposes OpenAI-compatible image generation (`/v1/images/generations`), text-to-speech (`/v1/audio/speech`), and transcription (`/v1/audio/transcriptions`) endpoints; these are not wired up — image generation would duplicate the existing ComfyUI-workflow-based `generate_image` tool call, and audio/TTS has no corresponding UI yet, so both are future considerations rather than a natural extension of the current backend switch
</details>
<details>
<summary><h3>Workflow Studio Library (ComfyUI Side Panel) (v0.3.9)</h3></summary>
- **Tab layout (W / N / P / M / I / A)** — compact single-letter tabs with full name shown on hover
- **W — Workflows tab** — browse favorite workflows (All / ★ Favorites / Groups / By Badge sub-tabs), ★ star shown for favorites in All view
- **N — Nodes tab** — browse favorite nodes (All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs), ★ star shown for favorites in All view
- **Category sub-tab** — dropdown to filter nodes by top-level category
- **Package sub-tab** — dropdown to filter nodes by custom node package name
- **Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs)
- **Prompts tab** — browse prompt presets with All / Favorites / Categories sub-tabs
- **M — Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs); LoRA groups show an **All N LoRAs** item — drag to canvas to place a `Lora Loader (LoraManager)` node with all LoRAs pre-loaded
- **P — Prompts tab** — browse prompt presets with All / ★ Favorites / Categories sub-tabs; **Groups sub-tab** (row 2) — view presets by group (shared with the Batch tab's `wfm_prompt_preset_groups`)
- **I — Information tab** — drop a ComfyUI-generated PNG/WebP/MP4 or workflow JSON in the side panel to view its metadata; detects LoRAs from `LoraLoader`, `LoraLoaderModelOnly`, and `Lora Loader (LoraManager)` nodes (API format supported); supports `UnetLoaderGGUF` and `QuadrupleCLIPLoader` node types; preview area fixed at 110px
- **MP4 embedded metadata** (v0.5.1) — reads the `workflow`/`prompt` container tags ComfyUI's `SaveVideo` writes into the mp4's `moov/udta/meta` box, parsed entirely client-side (same box-walking logic as the Gallery tab's Metadata sub-tab); also recognizes all-in-one video-generation nodes that carry their prompt directly on a `prompt` input rather than a separate `CLIPTextEncode`-style node (e.g. `MiniMaxH3ImageToVideo`)
- **A — AI TOOL tab** — Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama, LM Studio, Lemonade, or Unsloth; Chat supports multi-turn conversations (full history sent each turn); TOOLS includes VLM image analysis and wildcard generation; settings (backend, URL, model) shared with the SPA AI TOOL tab via `localStorage`
- **model sub-tab** — Checkpoint, VAE, Diffusion Model, and Text Encoder; drag items to canvas to place the corresponding loader node (Checkpoint → `CheckpointLoaderSimple`, VAE → `VAELoader`, Diffusion Model → `UNETLoader`, Text Encoder → `CLIPLoader`); double-click also places at canvas center
- **lora sub-tab** — detects LoRAs from `LoraLoader`, `LoraLoaderModelOnly`, and `Lora Loader (LoraManager)` nodes (API format `inputs.loras.__value__` supported); shows `strength_model / strength_clip` values; drag individual LoRA to place `LoraLoader`; **Multiple LORA** section (appears for 1+ LoRAs) drags all LoRAs into a single `Lora Loader (LoraManager)` node with LoRA syntax pre-filled
- **Prompts sub-tab** — POS / NEG badge list; drag a prompt to place `CLIPTextEncode` with text pre-filled; click any entry to view full text + Copy button
- **Drag & drop workflows** — drag a workflow onto the canvas to load it
- **Drag & drop nodes** — drag nodes/node sets onto the canvas to place them
- **Drag & drop prompts** — drag a preset onto the canvas to create a WFS_PromptText node with positive/negative prompts
- **Send to Canvas** — clicking "Send to Canvas" (Workflow tab toolbar / detail modal) sends the workflow directly to the ComfyUI canvas via `window.opener` when available (UI and API formats both supported); if Workflow Studio was opened from a bookmark instead of the ComfyUI toolbar (or in another tab), it filters the Library's **W** tab down to that workflow's card instead (v0.4.7) — drag the card onto the canvas yourself; this replaced the old title-drag fallback, which had no thumbnail and didn't work for API-format workflows at all. "Copy & Send Canvas" (Gallery tab JSON panel) still uses only `window.opener` + title-drag for UI-format workflows, since the embedded workflow it sends isn't a saved Library file to filter down to
- **Copy prompts** — copy individual positive (P) or negative (N) prompts from sidebar items
- **Double-click** — load workflows or place nodes without dragging
- **Search** — search within each sub-tab to quickly find items
- **⚙ Theme settings** — customize panel background, sub-header background, text, border, and secondary text colors; saved to localStorage and applied on every open
### Help & Support Tab (v0.1.3)
</details>
<details>
<summary><h3>Help &amp; Support Tab (v0.1.3)</h3></summary>
- **Sidebar navigation** — 2-column layout: left sidebar (15 topics) + right content pane; click any topic to switch the displayed content
- **Support** — fixed at the bottom of the sidebar; shows GitHub, Ko-fi, **ComfyUI Image Feeder**, and **Mask Editor One** repository links in the right pane
- **Feature list** — overview of all features organized by tab
- **Tips** — quick tips for drag & drop import, favorites, and default workflow
- **Support links** — GitHub repository and Ko-fi donation page
- **Keyboard Shortcuts** and **Troubleshooting** sections included
</details>
---
@@ -156,6 +510,22 @@ Restart ComfyUI after installation.
---
## Sample Workflows
Sample workflows are included in the `workflows/` folder. You can open them directly in ComfyUI via drag & drop, or load them from the Workflow tab.
> **Note:** Some sample workflows require additional custom nodes.
> If a node is shown as missing (red/unknown) after loading, install the required custom nodes via **ComfyUI Manager** or by cloning the repository from GitHub into your `ComfyUI/custom_nodes/` directory.
>
> ```bash
> cd ComfyUI/custom_nodes
> git clone <repository-url>
> ```
>
> After installation, restart ComfyUI to activate the new nodes.
---
## Usage
### Launch
@@ -190,118 +560,26 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
### Optional
- **[Ollama](https://ollama.com/)** — for AI chat assistant and translation features
- **[Ollama](https://ollama.com/)** — for AI chat assistant, translation, and VLM features
- **[LM Studio](https://lmstudio.ai/)** — alternative backend for translation and VLM (OpenAI-compatible API)
- **[Lemonade Server](https://lemonade-server.ai/)** — alternative backend for translation, chat, and VLM (OpenAI-compatible API)
- **[Unsloth](https://unsloth.ai/)** — alternative backend for translation, chat, and VLM (OpenAI-compatible API); always requires an API key, set via `UNSLOTH_API_KEY` in a `.env` file — `pip install -r requirements.txt` for `python-dotenv`
- **[Eagle](https://eagle.cool/)** — for auto-saving generated images with metadata
- **[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
---
## Supported Languages
| Language | Status |
|----------|--------|
| -------- | ------ |
| English | Full |
| Japanese | Full |
| Chinese | Full |
---
## Changelog
### v0.2.7
- **Gallery tab** — new image browser for ComfyUI output folder; Thumbnail/Table views, multi-select with Bulk Bar, server-side group/tag/favorite filtering, group management (rename support), performance-optimized with + mtime folder cache
- **Group UI unified** — Workflow, Nodes, and Gallery group panels rebuilt to match the Models tab 4-section pattern (Current Groups / Add to Group / Create New Group / Manage Groups); Rename support added to Workflow and Nodes tabs
- **Settings 2-column layout** — Theme panel fixed on the right (50% width, sticky); all other settings flow continuously on the left with no visual gap
- **Gallery output directory setting** — configure the output folder scanned by Gallery tab from Settings
- **Help tab** — Gallery tab description card added
### v0.2.5
- **Sidebar Category/Package sub-tabs** — added 📂 Category and 🧩 Package sub-tabs to the Nodes tab in Workflow Studio Library; each shows a dropdown to filter nodes by category or custom node package (reads `/object_info` for accurate package detection)
- **Sidebar theme settings** — added ⚙ button in the panel header to customize background, sub-header background, text, border, and secondary text colors with live preview; settings saved to localStorage
- **Sidebar TextEncoder (By Type)** — fixed TextEncoder not appearing in Models → By Type; now uses `DualCLIPLoader` → `CLIPLoader` fallback to retrieve `clip_name1` list
- **Hide `.index.json`** — excluded `.index.json` from both the Workflow tab and the Workflow Studio Library side panel
### v0.2.4
- **GenerateUI tab redesign** — reorganized from 5 tabs (Prompt/Image/Model/Settings/Raw JSON) to 3 tabs (Input/Model/Settings); each tab shows a Raw JSON column (540px) for instant JSON preview and direct editing from any tab
- **Input tab** — Prompt and Image stacked vertically in the left column
- **Settings tab** — KSampler and LatentImage stacked vertically in the left column
- **Raw JSON tab removed** — Raw JSON is now always visible as a right-column panel within each tab
### v0.2.3
- **Badge system unified** — Workflow and Models tabs now share a single badge palette (`⚙ Badge` button); workflow auto-analysis model type system removed in favor of user-defined free-label badges
- **GenUI Model button** — apply any model from the Models tab directly to the corresponding node in GenerateUI's current workflow (available in detail modal and side panel; Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)
- **Sidebar Models tab** — added All / ★ Favorites / Groups / By Type sub-tabs to the Models section of Workflow Studio Library
- **Sidebar All views** — ★ star displayed for favorite items in Workflows and Nodes All sub-tabs
- **Sidebar panel width** — widened from 280px to 310px
### v0.2.2
- **Models tab** — browse, search, and manage all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder) with Thumbnail/Card/Table views
- **CivitAI integration** — fetch model metadata by SHA256 hash (individual or batch per model type) with SSE progress streaming
- **Model groups** — create, rename, delete groups and assign/remove models for organization
- **Model metadata** — persistent favorites, tags, memo, and SHA256 hash per model
- **Preview images** — auto-detect and display preview images, change via file upload in detail modal
- **Table view memo column** — memo displayed in table view with compact subdir/extension columns
- **Side panel file path** — display full file path with click-to-copy in model info panel
- **Node card redesign** — removed package badge, added left border color-coding by package
- **Toolbar pagination** — pagination controls moved to toolbar for all tabs (Models, Workflows, Nodes)
- **Help tab updated** — Models Tab section added to feature list
### v0.2.0
- **Prompt presets in sidebar** — added Prompts tab to Workflow Studio Library (ComfyUI side panel) with All / Favorites / Categories sub-tabs
- **WFS_PromptText custom node** — drag prompt presets onto the canvas to create nodes with positive/negative prompt outputs
- **Preset Manager** — 3-column layout in Prompt tab: AI Assistant | Presets editor | Preset Manager (All / Favorites / Groups)
- **Group management** — create groups, assign/remove presets, delete groups from the Presets panel
- **GenUI Set** — renamed "Apply" button to clarify its purpose (applies presets to GenerateUI)
- **Sidebar P/N copy buttons** — copy positive or negative prompts individually from sidebar items
- **Panel renamed** — "WF & Node Library" renamed to "Workflow Studio Library"
- **Backend API for presets** — presets migrated from localStorage to server-side API with one-time migration
- **Help tab updated** — Prompt Tab and Workflow Studio Library sections reflect new features
### v0.1.9
- **Side panel 2-row sub-tabs** — Workflows: row 1 (Workflows / Favorites / Groups), row 2 (Model Type); Nodes: row 1 (Nodes / Favorites / Groups), row 2 (Sets)
- **Save dialog** — canvas snapshot now shows a filename edit dialog instead of auto-naming
- **API/App format badge** — workflow items in side panel show red (API) or orange (APP) badge
- **Group auto-cleanup** — deleted workflows are automatically removed from groups on refresh
### v0.1.8
- **WF & Node Library side panel** — renamed from "Node Library", added two top-level tabs (Workflows / Nodes) accessible from ComfyUI top bar
- **Workflows tab** — browse favorite workflows, filter by model type, filter by group with collapsible sections
- **Workflow drag & drop** — drag workflows from the side panel onto the canvas to load them instantly
- **Help tab update** — added Nodes Tab and WF & Node Library sections to the feature list
### v0.1.7
- **Nodes tab** — browse, search, and filter all installed ComfyUI nodes with Card/Table views, pagination (50 nodes/page), package color badges, and node detail side panel with I/O specs
- **Node Sets** — save selected nodes + connections from ComfyUI canvas as reusable sets via right-click context menu
- **Node Library side panel** — accessible from ComfyUI top bar with Favorites, Sets, and Groups tabs, drag & drop placement
- **3 top bar buttons** — Workflow Studio, Canvas Snapshot, and Node Library buttons in ComfyUI's action bar
### v0.1.6
- **Security fix** — path traversal vulnerability in `workflow_service.py` (reported via ComfyUI-Manager PR review)
### v0.1.5
- **Theme system** — 13 built-in themes selectable from Settings tab with instant preview (Deep Ocean Dark, Pop & Vibrant, Light Minimalist, Cyberpunk, Glassmorphism, Neumorphism, Retro 8-bit, Pastel Dream, Brutalism, Earthy, Material UI, Monotone + Accent, Corporate Trust)
- Theme preference persisted in localStorage and restored on page load (no flash)
- Special CSS effects per theme: neon glow (Cyberpunk), backdrop blur (Glassmorphism), dual shadow (Neumorphism), pixel borders (Retro/Brutalism)
### v0.1.4
- **App format support** — detect `.app.json` workflows (ComfyUI App mode), show "App Format" badge, block loading in GenerateUI with guidance message
- **Preset clipboard copy** — added PP Copy / NP Copy buttons to copy positive/negative prompts to clipboard
- **Analysis bugfix** — fixed workflow analysis crash when `widgets_values` contains non-string values (e.g. integers)
### v0.1.3
- Added **Help & Support tab** — feature list, tips, and support links (GitHub, Ko-fi)
- Multi-language support (EN/JA/ZH) for all help content
### v0.1.2
- Added **Canvas Snapshot** button to ComfyUI top bar — capture workflow canvas as PNG thumbnail with embedded workflow metadata
- Added **Thumbnail tab** to the workflow side panel for quick visual preview
- Added **Thumbnail section** to the workflow detail modal
- Snapshot images are auto-imported as workflows with thumbnails
### v0.1.1
- Initial feature set: Workflow management, GenerateUI, Prompt assistant, Settings
---
## Project Structure
```
@@ -311,7 +589,8 @@ ComfyUI-Workflow-Studio/
│ ├── wfm.py # Main class & route registration
│ ├── config.py # Path configuration
│ ├── nodes/
│ │ └── prompt_text.py # WFS_PromptText custom node (positive/negative prompt)
│ │ ├── prompt_text.py # WFS_PromptText custom node (positive/negative prompt)
│ │ └── gallery_feeder_node.py # WFS_GalleryFeeder custom node (gallery group → IMAGE)
│ ├── routes/
│ │ ├── workflow_routes.py # Workflow CRUD & analysis API
│ │ ├── nodes_routes.py # Nodes metadata & node sets API
@@ -319,7 +598,8 @@ ComfyUI-Workflow-Studio/
│ │ ├── prompts_routes.py # Prompt presets CRUD API
│ │ ├── settings_routes.py # Settings API
│ │ ├── ollama_routes.py # Ollama proxy API
│ │ └── eagle_routes.py # Eagle integration API
│ │ ├── eagle_routes.py # Eagle integration API
│ │ └── gallery_routes.py # Gallery tab API (Output + ImagePrompt + Style_Catalog sub-tabs)
│ └── services/
│ ├── workflow_service.py # Workflow file operations
│ ├── nodes_service.py # Node metadata & node sets
@@ -328,9 +608,11 @@ ComfyUI-Workflow-Studio/
│ ├── prompts_service.py # Prompt presets persistence
│ ├── workflow_analyzer.py # Model/node detection
│ ├── settings_service.py # Settings persistence
│ └── png_extractor.py # PNG metadata extraction
│ ├── png_extractor.py # PNG metadata extraction
│ ├── gallery_service.py # Gallery image scanning, .txt sidecar & ponyxlWildcardsVault prompt resolution
│ └── gallery_metadata.py # Gallery per-image metadata store (favorites/tags/memo/groups)
├── templates/
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Settings/Nodes/Models/Help)
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Metadata/Gallery/Nodes/Models/Settings/Help/AI)
├── static/
│ ├── favicon.svg # Browser tab icon (W+S Wave)
│ ├── css/main.css # Styles
@@ -338,19 +620,30 @@ ComfyUI-Workflow-Studio/
│ ├── app.js # App initialization & routing
│ ├── workflow-tab.js # Workflow browser
│ ├── generate-tab.js # Generation UI
│ ├── feeder-tab.js # Feeder subtab (Image Loop + Gallery modes)
│ ├── gallery-tab.js # Gallery tab: Output sub-tab (image browser, groups, metadata) + sub-tab switching
│ ├── image-prompt-tab.js # Gallery tab: ImagePrompt sub-tab (visual prompt builder)
│ ├── style-catalog-tab.js # Gallery tab: Style_Catalog sub-tab (visual Style picker)
│ ├── tagger-tab.js # Tagger tab (WD Tagger, DeepDanbooru, Ollama VLM)
│ ├── prompt-tab.js # AI assistant & presets
│ ├── metadata-tab.js # Metadata extraction & display (PNG/WebP/JSON)
│ ├── settings-tab.js # Settings panel
│ ├── comfyui-client.js # ComfyUI WebSocket/API client
│ ├── nodes-tab.js # Node browser & node sets
│ ├── models-tab.js # Model browser & CivitAI integration
│ ├── ai-tab.js # AI TOOL tab (Translation | Chat | TOOLS/VLM | Settings)
│ ├── comfyui-workflow.js # UI-to-API format conversion
│ ├── comfyui-editor.js # Dynamic parameter editor
│ ├── json-highlight.js # JSON syntax highlighting
│ ├── util.js # Shared utilities (escapeHtml, readJsonStorage, getSettings)
│ └── i18n.js # Internationalization
├── web/comfyui/
│ ├── top_menu_extension.js # ComfyUI menu bar integration
│ └── node_sets_menu.js # Workflow Studio Library side panel
└── data/ # Metadata & settings storage (incl. prompts.json, model_metadata.json, civitai_cache.json)
│ ├── node_sets_menu.js # Workflow Studio Library side panel
│ └── gallery_feeder_extension.js # WFS_GalleryFeeder canvas widgets (After Gen / Run / Stop)
├── tools/
│ └── import_style_prompt_seed.py # Dev tool: pre-process a wildcards-vault source into ws_image_prompt (not run by the plugin itself)
└── data/ # Fallback data dir (used when ComfyUI user/default/ is not found)
```
---
@@ -365,6 +658,11 @@ MIT License
- [ComfyUI](https://github.com/comfyanonymous/ComfyUI) by comfyanonymous
- [ComfyUI-Custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) by pythongosssss — Canvas snapshot and PNG workflow embedding implementation reference
- [ComfyUI-Lora-Manager](https://github.com/willchil/ComfyUI-Lora-Manager) — Plugin architecture and UI pattern reference
- [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) — Plugin architecture and UI pattern reference
- [Ollama](https://ollama.com/) for local LLM inference
- [Eagle](https://eagle.cool/) for image management
- [Pillow (PIL Fork)](https://python-pillow.org/) — server-side thumbnail generation (`data/thumb_cache/`)
- [ComfyUI-Gallery](https://github.com/PanicTitan/ComfyUI-Gallery) by PanicTitan — thumbnail grid UX reference
- [infinite-image-browsing](https://github.com/zanllp/sd-webui-infinite-image-browsing) by zanllp — thumbnail caching and index strategy reference
- [Fooocus](https://github.com/lllyasviel/Fooocus) by lllyasviel — style preset JSON format reference
+4 -3
View File
@@ -9,15 +9,16 @@ WorkflowStudio.add_routes()
# Register custom nodes (isolated loading)
_NODE_MODULES = {
"WFS_PromptText": (".py.nodes.prompt_text", "WFS_PromptText"),
"WFS_PromptText": (".py.nodes.prompt_text", "WFS_PromptText", "Prompt Text (WFS)"),
"WFS_GalleryFeeder": (".py.nodes.gallery_feeder_node", "WFS_GalleryFeeder", "Gallery Feeder (WFS)"),
}
for _name, (_mod_path, _cls_name) in _NODE_MODULES.items():
for _name, (_mod_path, _cls_name, _display_name) in _NODE_MODULES.items():
try:
import importlib
_mod = importlib.import_module(_mod_path, package=__name__)
NODE_CLASS_MAPPINGS[_name] = getattr(_mod, _cls_name)
NODE_DISPLAY_NAME_MAPPINGS[_name] = "Prompt Text (WFS)"
NODE_DISPLAY_NAME_MAPPINGS[_name] = _display_name
except Exception as _e:
print(f"[WARNING] Workflow Studio: Failed to load '{_name}': {_e}")
Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 975 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

+183
View File
@@ -0,0 +1,183 @@
{
"0": "escapeHtml",
"1": "prompt-table.js",
"2": "models_routes.py",
"3": "generate-tab.js",
"4": "_openCellModal",
"5": "gallery_routes.py",
"6": "gallery-tab.js",
"7": "ImageEditTab",
"8": "ai-tab.js",
"9": "eagle_routes.py",
"10": "feeder-tab.js",
"11": "NodesService",
"12": "settings_routes.py",
"13": "metadata-tab.js",
"14": "node_sets_menu.js",
"15": "GalleryService",
"16": "settings-tab.js",
"17": "tagger_routes.py",
"18": "WildcardService",
"19": "tagger-tab.js",
"20": "renderContent",
"21": "comfyui-editor.js",
"22": "ComfyUI-Workflow-Studio",
"23": "TaggerService",
"24": "top_menu_extension.js",
"25": "nodes-tab.js",
"26": "setupAiHandlers",
"27": "workflow-tab.js",
"28": "workflow_routes.py",
"29": "GalleryMetadataStore",
"30": "WorkflowService",
"31": "LabPlanService",
"32": "skill_routes.py",
"33": "LayerManager",
"34": "SelectTool",
"35": "CivitaiService",
"36": "DrawTool",
"37": "MaskTool",
"38": "index.html Template",
"39": "gallery_service.py",
"40": "FileExport",
"41": "image-prompt-tab.js",
"42": "KSampler Node",
"43": "image-edit-tab.js",
"44": "style-catalog-tab.js",
"45": "add",
"46": "comfyui-workflow.js",
"47": "BlurTool",
"48": "MaskShapeTool",
"49": "MaskVectorTool",
"50": "ShapeTool",
"51": "gmic_routes.py",
"52": "ollama_routes.py",
"53": "TextTool",
"54": "analyze_workflow",
"55": "MaskTextTool",
"56": "lab-tab.js",
"57": ".list_images",
"58": "MaskAlphaTool",
"59": "MaskColorTool",
"60": "gallery_feeder_extension.js",
"61": "createPanel",
"62": "_runLabBatch",
"63": "BgRemove",
"64": "Workflow JSON",
"65": "WFS_GalleryFeeder",
"66": "initGenerateTab",
"67": "InpaintI2IActions",
"68": "Sam3Segmentation",
"69": "fromWorkflow",
"70": "_extractPromptsAPI",
"71": "generate_doc_index.py",
"72": "WS Inpaint Basic Workflow",
"73": "._bg_index_folder",
"74": "aiohttp",
"75": "import_style_prompt_seed.py",
"76": "Image Edit (FireRed Image Edit 1.1) node",
"77": "Version 0.3.9",
"78": "DWPose Image Feeder Workflow",
"79": "wfm.py",
"80": "README.index.md",
"81": "WFS_PromptText",
"82": "workflow_service.py",
"83": "SPA",
"84": "prompt-ai-chat.js",
"85": "Tagger Tab requirements.txt",
"86": "data directory",
"87": "t",
"88": "Chinese Language Support",
"89": "Version 0.3.95",
"90": "Windows",
"91": "add_routes",
"92": "Bounded Cache",
"93": "Business Logic",
"94": "check_lazy_status",
"95": "HF_HOME",
"96": "IS_CHANGED",
"97": "Lab Subtab",
"98": "lab_routes.py",
"99": "PowerShell",
"100": "prestartup_script.py",
"101": ".get_image_prompt_root",
"102": ".get_style_catalog_root",
"103": ".start_background_index",
"104": ".update_workflows_dir",
"105": "Version 0.4.2",
"106": "Workflow Studio Banner",
"107": "Workflow Studio Icon",
"108": "BiRefNet Model",
"109": "Chinese",
"110": "SDXL 2D Pose Editor I2I Workflow",
"111": "ComfyUI Manager",
"112": "Tagger Tab Screenshot (WD Tagger/DeepDanbooru)",
"113": "Models Tab UI Screenshot",
"114": "Workflow Studio Topbar Icon Strip",
"115": "GenerateUI LoRA Stack Tab Screenshot",
"116": "Workflow Studio Favicon Icon",
"117": "2D Pose Editor to Image Edit (FireRed) Workflow",
"118": "3D Pose Editor to Image Edit (Flux.2 Klein) Workflow",
"119": "SDXL DWPose ControlNet Workflow",
"120": "SDXL From Metadata T2I Workflow",
"121": "SDXL Img2Img + FaceDetailer Workflow",
"122": "SDXL Image Feeder Img2Img Workflow",
"123": "SDXL T2I + FaceDetailer Workflow",
"124": "GenerateUI Batch Tab Screenshot",
"125": "Multiple Select Menu Screenshot",
"126": "Image Edit Tab Screenshot",
"127": "Workflow Tab Screenshot",
"128": "Prompt Tab Input Assistance Screenshot",
"129": "GenerateUI Feeder Tab Screenshot",
"130": "Workflow Studio Library Panel (Lora Info View)",
"131": "Library Panel I Tab (Prompts) Screenshot",
"132": "Settings Tab Screenshot (Language, Theme)",
"133": "ComfyUI Workflow Studio Thumbnail",
"134": "English",
"135": "Feeder Subtab",
"136": "folder_paths",
"137": "Help & Support Tab",
"138": "i18n",
"139": "Japanese",
"140": "Metadata Tab",
"141": "NODE_CLASS_MAPPINGS",
"142": "OrderedDict",
"143": "get_output_directory",
"144": "comfyui-workflow-studio",
"145": "ComfyUI PromptServer",
"146": "py/__init__.py",
"147": "nodes/__init__.py",
"148": "routes/__init__.py",
"149": "services/__init__.py",
"150": "python-dotenv",
"151": "Silent Failure Diagnosis",
"152": "get_temp_directory",
"153": "prompts_routes.py",
"154": "VALIDATE_INPUTS",
"155": "SD1.5 Basic Text-to-Image Workflow",
"156": "SDXL Text-to-Image Basic Workflow Screenshot",
"157": "SettingsService",
"158": "on_doc_edit.py",
"159": "ComfyUI-Custom-Scripts",
"160": "ComfyUI-Gallery",
"161": "ComfyUI-Lora-Manager",
"162": "Eagle",
"163": "Fooocus",
"164": "Gallery Tab",
"165": "GenerateUI Tab",
"166": "Image Edit Tab",
"167": "infinite-image-browsing",
"168": "Lemonade Server",
"169": "LM Studio",
"170": "Ollama",
"171": "Settings Tab",
"172": "Tagger Tab",
"173": "Unsloth",
"174": "app.js",
"175": "PromptsService",
"176": "util.js",
"177": "civitai_service.py",
"178": "config.py",
"179": "createModelItem",
"180": "_renderBatchPreview"
}
+605
View File
@@ -0,0 +1,605 @@
# Graph Report - ComfyUI-Workflow-Studio (2026-08-22)
## Corpus Check
- 113 files · ~567,985 words
- Verdict: corpus is large enough that graph structure adds value.
## Summary
- 2314 nodes · 5664 edges · 181 communities (87 shown, 94 thin omitted)
- Extraction: 95% EXTRACTED · 5% INFERRED · 0% AMBIGUOUS · INFERRED: 302 edges (avg confidence: 0.88)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `ad9d06d3`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- escapeHtml
- prompt-table.js
- models_routes.py
- generate-tab.js
- _openCellModal
- gallery_routes.py
- gallery-tab.js
- ImageEditTab
- ai-tab.js
- eagle_routes.py
- feeder-tab.js
- NodesService
- settings_routes.py
- metadata-tab.js
- node_sets_menu.js
- GalleryService
- settings-tab.js
- tagger_routes.py
- WildcardService
- tagger-tab.js
- renderContent
- comfyui-editor.js
- ComfyUI-Workflow-Studio
- TaggerService
- top_menu_extension.js
- nodes-tab.js
- setupAiHandlers
- workflow-tab.js
- workflow_routes.py
- GalleryMetadataStore
- WorkflowService
- LabPlanService
- skill_routes.py
- LayerManager
- SelectTool
- CivitaiService
- DrawTool
- MaskTool
- index.html Template
- gallery_service.py
- FileExport
- image-prompt-tab.js
- KSampler Node
- image-edit-tab.js
- style-catalog-tab.js
- add
- comfyui-workflow.js
- BlurTool
- MaskShapeTool
- MaskVectorTool
- ShapeTool
- gmic_routes.py
- ollama_routes.py
- TextTool
- analyze_workflow
- MaskTextTool
- lab-tab.js
- .list_images
- MaskAlphaTool
- MaskColorTool
- gallery_feeder_extension.js
- createPanel
- _runLabBatch
- BgRemove
- Workflow JSON
- WFS_GalleryFeeder
- initGenerateTab
- InpaintI2IActions
- Sam3Segmentation
- fromWorkflow
- _extractPromptsAPI
- generate_doc_index.py
- WS Inpaint Basic Workflow
- ._bg_index_folder
- aiohttp
- import_style_prompt_seed.py
- Image Edit (FireRed Image Edit 1.1) node
- Version 0.3.9
- DWPose Image Feeder Workflow
- wfm.py
- README.index.md
- WFS_PromptText
- workflow_service.py
- SPA
- prompt-ai-chat.js
- Tagger Tab requirements.txt
- data directory
- t
- Chinese Language Support
- Version 0.3.95
- Windows
- add_routes
- Bounded Cache
- Business Logic
- check_lazy_status
- HF_HOME
- IS_CHANGED
- Lab Subtab
- lab_routes.py
- PowerShell
- prestartup_script.py
- .get_image_prompt_root
- .get_style_catalog_root
- .start_background_index
- .update_workflows_dir
- Version 0.4.2
- Workflow Studio Banner
- Workflow Studio Icon
- BiRefNet Model
- Chinese
- SDXL 2D Pose Editor I2I Workflow
- ComfyUI Manager
- Tagger Tab Screenshot (WD Tagger/DeepDanbooru)
- Models Tab UI Screenshot
- Workflow Studio Topbar Icon Strip
- GenerateUI LoRA Stack Tab Screenshot
- Workflow Studio Favicon Icon
- 2D Pose Editor to Image Edit (FireRed) Workflow
- 3D Pose Editor to Image Edit (Flux.2 Klein) Workflow
- SDXL DWPose ControlNet Workflow
- SDXL From Metadata T2I Workflow
- SDXL Img2Img + FaceDetailer Workflow
- SDXL Image Feeder Img2Img Workflow
- SDXL T2I + FaceDetailer Workflow
- GenerateUI Batch Tab Screenshot
- Multiple Select Menu Screenshot
- Image Edit Tab Screenshot
- Workflow Tab Screenshot
- Prompt Tab Input Assistance Screenshot
- GenerateUI Feeder Tab Screenshot
- Workflow Studio Library Panel (Lora Info View)
- Library Panel I Tab (Prompts) Screenshot
- Settings Tab Screenshot (Language, Theme)
- ComfyUI Workflow Studio Thumbnail
- English
- Feeder Subtab
- folder_paths
- Help & Support Tab
- i18n
- Japanese
- Metadata Tab
- NODE_CLASS_MAPPINGS
- OrderedDict
- get_output_directory
- comfyui-workflow-studio
- ComfyUI PromptServer
- python-dotenv
- Silent Failure Diagnosis
- get_temp_directory
- prompts_routes.py
- VALIDATE_INPUTS
- SD1.5 Basic Text-to-Image Workflow
- SDXL Text-to-Image Basic Workflow Screenshot
- SettingsService
- on_doc_edit.py
- ComfyUI-Custom-Scripts
- ComfyUI-Gallery
- ComfyUI-Lora-Manager
- Eagle
- Fooocus
- Gallery Tab
- GenerateUI Tab
- Image Edit Tab
- infinite-image-browsing
- Lemonade Server
- LM Studio
- Ollama
- Settings Tab
- Tagger Tab
- Unsloth
- app.js
- PromptsService
- util.js
- civitai_service.py
- config.py
- createModelItem
- _renderBatchPreview
## God Nodes (most connected - your core abstractions)
1. `t()` - 233 edges
2. `showToast()` - 192 edges
3. `escapeHtml()` - 73 edges
4. `ImageEditTab` - 53 edges
5. `GalleryService` - 45 edges
6. `setup_routes()` - 32 edges
7. `initSettingsTab()` - 31 edges
8. `add()` - 31 edges
9. `renderModelGrid()` - 29 edges
10. `TaggerService` - 26 edges
## Surprising Connections (you probably didn't know these)
- `beforeRegisterNodeDef()` --indirect_call--> `saveSelectedAsNodeSet()` [INFERRED]
web/comfyui/top_menu_extension.js → web/comfyui/node_sets_menu.js
- `Publish to Comfy Registry Workflow` --conceptually_related_to--> `index.html Template` [INFERRED]
.github/workflows/publish.yml → templates/index.html
- `Version 0.3.9` --references--> `Models Tab` [EXTRACTED]
DEVLOG.index.md → README.index.md
- `Version 0.3.9` --references--> `Nodes Tab` [EXTRACTED]
DEVLOG.index.md → README.index.md
- `Version 0.3.9` --references--> `Prompt Tab` [EXTRACTED]
DEVLOG.index.md → README.index.md
## Import Cycles
- 3-file cycle: `static/js/app.js -> static/js/generate-tab.js -> static/js/feeder-tab.js -> static/js/app.js`
- 3-file cycle: `static/js/feeder-tab.js -> static/js/gallery-tab.js -> static/js/generate-tab.js -> static/js/feeder-tab.js`
- 3-file cycle: `static/js/app.js -> static/js/prompt-tab.js -> static/js/prompt-presets.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/prompt-tab.js -> static/js/prompt-ai-chat.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/prompt-tab.js -> static/js/prompt-styles.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/prompt-tab.js -> static/js/prompt-wildcards.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/models-tab.js -> static/js/models/badges.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/gallery-tab.js -> static/js/image-prompt-tab.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/Sam3Segmentation.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/GmicIntegration.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/FileExport.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/MaskEditorOneBridge.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/models-tab.js -> static/js/comfyui-editor.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/comfyui-editor.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/BgRemove.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/BlurTool.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/image-edit-tab.js -> static/js/image-edit/InpaintI2IActions.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/gallery-tab.js -> static/js/style-catalog-tab.js -> static/js/app.js`
- 3-file cycle: `static/js/app.js -> static/js/generate-tab.js -> static/js/comfyui-editor.js -> static/js/app.js`
- 3-file cycle: `static/js/ai-tab.js -> static/js/app.js -> static/js/gallery-tab.js -> static/js/ai-tab.js`
## Hyperedges (group relationships)
- **Architecture Layers** — workflowstudio, add_routes, py_wfm, py_routes, py_services, business_logic, web_comfyui, static, templates, data, settings_json, metadata_json, node_metadata_json [EXTRACTED 0.80]
- **Graphify Index Generation** — readme_index, devlog_index, generate_doc_index, graphifyignore, readme, devlog, claude_hooks, git_hooks [EXTRACTED 0.85]
- **Workflow Studio UI Navigation Tabs** — templates_index_html_workflow, templates_index_html_nodes, templates_index_html_models, templates_index_html_generate, templates_index_html_prompt, templates_index_html_gallery, templates_index_html_image_edit, templates_index_html_tagger, templates_index_html_settings, templates_index_html_help, templates_index_html_ai [EXTRACTED 0.85]
- **Workflow JSON Consistency Group** — last_node_id, last_link_id, links, workflow_json [EXTRACTED 0.85]
- **i18n Languages** — i18n, english, japanese, chinese [EXTRACTED 0.90]
- **Mask Editor One Inpainting Pipeline** — comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_load_checkpoint_node, comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_mask_editor_one_node, comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_clip_text_encode_positive_node, comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_clip_text_encode_negative_node, comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_vae_encode_for_inpainting_node, comfyui-workflow-studio_workflows_ws_inpaint_mask_editor_one_save_image_node [INFERRED]
## Communities (181 total, 94 thin omitted)
### Community 0 - "escapeHtml"
Cohesion: 0.09
Nodes (80): openModal(), comfyUI, badgeHtml(), bindBadgeModalEvents(), bindBadgeRowEvents(), getBadgePalette(), modelBadgesHtml(), _onGridChange() (+72 more)
### Community 1 - "prompt-table.js"
Cohesion: 0.06
Nodes (99): closeModal(), refreshStylesList(), apiCreatePreset(), apiDeletePreset(), apiUpdatePreset(), clearBatchPresets(), createPmItem(), esc() (+91 more)
### Community 2 - "models_routes.py"
Cohesion: 0.06
Nodes (55): handle_change_preview(), handle_civitai_batch(), handle_civitai_cache(), handle_civitai_fetch(), handle_delete_models(), handle_get_disabled(), handle_get_filepath(), handle_get_groups() (+47 more)
### Community 3 - "generate-tab.js"
Cohesion: 0.09
Nodes (41): _applyNamedStyle(), _applyStyleToWorkflow(), _batchGroupState, _batchStyleSelected, _blobToDataUrl(), _buildFolderTree(), _ckptBatch, _ckptState (+33 more)
### Community 4 - "_openCellModal"
Cohesion: 0.24
Nodes (12): _applyStyleToText(), _cellHtml(), _cellLabel(), _effectiveDisplayValue(), _isEmptyValue(), _isLiveDisplay(), _liveValueFor(), _openCellModal() (+4 more)
### Community 5 - "gallery_routes.py"
Cohesion: 0.10
Nodes (54): add_to_group(), bulk_favorite(), bulk_group(), clear_group_images(), create_folder_route(), create_group(), delete_folder_route(), delete_group() (+46 more)
### Community 6 - "gallery-tab.js"
Cohesion: 0.10
Nodes (53): addTag(), API, apiFetch(), _appendNextPage(), _applySelectionToDOM(), _attachScrollSentinel(), bindEvents(), bulkAddToGroup() (+45 more)
### Community 8 - "ai-tab.js"
Cohesion: 0.09
Nodes (52): appendChatBubble(), _appendSkillSaveButton(), _appendSvgPreview(), _applyGenOptions(), buildTranslationMessages(), callChat(), callLLM(), callVLM() (+44 more)
### Community 9 - "eagle_routes.py"
Cohesion: 0.14
Nodes (20): _eagle_add(), _eagle_add_from_path(), _eagle_test(), handle_add(), handle_test(), Application, Request, Response (+12 more)
### Community 10 - "feeder-tab.js"
Cohesion: 0.10
Nodes (50): _applyGalToWorkflow(), _applyPreset(), _applyToGalNode(), _applyToNode(), _applyToWorkflow(), _deletePreset(), _deselectAll(), _feederNodes() (+42 more)
### Community 11 - "NodesService"
Cohesion: 0.09
Nodes (27): handle_create_set(), handle_delete_set(), handle_export_set(), handle_get_groups(), handle_get_metadata(), handle_list_sets(), handle_save_groups(), handle_save_metadata() (+19 more)
### Community 12 - "settings_routes.py"
Cohesion: 0.09
Nodes (44): _apply_import_bundle(), _build_export_bundle(), _find_style(), _get_comfyui_output_dir(), handle_create_style(), handle_delete_style(), handle_export(), handle_get() (+36 more)
### Community 13 - "metadata-tab.js"
Cohesion: 0.11
Nodes (40): buildLoRAItem(), buildModelItem(), buildPromptItem(), collectAllNodes(), collectUnique(), extractAllMetadata(), fromWorkflow(), extractCheckpoints() (+32 more)
### Community 14 - "node_sets_menu.js"
Cohesion: 0.08
Nodes (38): AI_BACKEND_DEFAULT_URLS, AI_LANG_NAMES, convertApiToUiWorkflow(), _extractAllMetadata(), _extractWorkflowFromEXIF(), fetchGroups(), fetchMetadata(), fetchNodeSets() (+30 more)
### Community 15 - "GalleryService"
Cohesion: 0.10
Nodes (13): GalleryService, Path, 許可するルートパスを更新する(Settings変更時に呼ぶ), ComfyUI実outputフォルダの不変ルートを設定する(起動時に一度だけ呼ぶ), パスが許可ルート配下かチェック(パストラバーサル防止)。 Output ギャラリーの _allowed_root、またはComfyUI実outputフォルダの…, outputフォルダのフォルダツリーを返す, 画像と同名の.txtサイドカーにプロンプトテキストを保存する, ワークフローを抽出する。 優先順位: PNG[workflow] > PNG[prompt] > gallery_metadata.json[workflow] (+5 more)
### Community 16 - "settings-tab.js"
Cohesion: 0.09
Nodes (40): getLang(), getLanguageOptions(), getSummaryLang(), getSummaryLanguageOptions(), getSummaryPrompt(), LANGUAGE_OPTIONS, LANGUAGES, setLang() (+32 more)
### Community 17 - "tagger_routes.py"
Cohesion: 0.14
Nodes (24): Connection, handle_batch_start(), handle_batch_status(), handle_batch_stop(), handle_db_delete(), handle_db_export(), handle_db_list(), handle_db_save() (+16 more)
### Community 18 - "WildcardService"
Cohesion: 0.12
Nodes (21): handle_create_link(), handle_delete(), handle_get_content(), handle_link_status(), handle_list(), handle_remove_link(), handle_save(), Application (+13 more)
### Community 19 - "tagger-tab.js"
Cohesion: 0.14
Nodes (29): _applyI18n(), _batchStart(), _batchStop(), _dbDelete(), _dbExport(), _dbLoad(), _dbSave(), _dbSearch() (+21 more)
### Community 20 - "renderContent"
Cohesion: 0.16
Nodes (28): createDraggableItem(), createDraggablePromptItem(), createDraggableWfItem(), esc(), extractPackageName(), getNodeCategory(), getNodePackage(), getWfBadges() (+20 more)
### Community 21 - "comfyui-editor.js"
Cohesion: 0.08
Nodes (28): _applyLoraToNode(), _attachPromptWeightControl(), _buildLoraManagerSyntax(), _buildLoraSyntax(), _buildPresetOptions(), _compositeImageWithMask(), _I2I_PLACEHOLDER_DEFAULT, _imageInputToDataURL() (+20 more)
### Community 22 - "ComfyUI-Workflow-Studio"
Cohesion: 0.50
Nodes (4): CivitAI, ComfyUI-Workflow-Studio, Mask Editor One, Version 0.3.65
### Community 23 - "TaggerService"
Cohesion: 0.14
Nodes (5): Image, Path, WD Tagger / DeepDanbooru / Ollama VLM 推論サービス。, パストラバーサル防止: セパレータ・NUL・相対参照を拒否, TaggerService
### Community 24 - "top_menu_extension.js"
Cohesion: 0.14
Nodes (27): ../../scripts/ui/components/button.js, ../../scripts/ui/components/buttonGroup.js, getNodeSetsIcon(), NODE_SETS_TOOLTIP, attachTopMenuButton(), beforeRegisterNodeDef(), captureCanvasSnapshot(), compareVersions() (+19 more)
### Community 25 - "nodes-tab.js"
Cohesion: 0.11
Nodes (40): _applyNodeSelectionToDOM(), bulkNodeAddToGroup(), bulkNodeCreateAndAddToGroup(), bulkNodeRemoveFromGroup(), bulkNodeSetFavorite(), categoryBadgeHtml(), createNodeCard(), createNodeSet() (+32 more)
### Community 26 - "setupAiHandlers"
Cohesion: 0.11
Nodes (28): _aiApplyGenOptions(), aiCallChat(), aiCallLLM(), aiCallVLM(), aiFetchModels(), aiFileToBase64(), aiLooksUntranslated(), aiSkillDeleteFile() (+20 more)
### Community 27 - "workflow-tab.js"
Cohesion: 0.13
Nodes (34): readJsonStorage(), badgeHtml(), _buildStructuredSummaryText(), _buildSummarySourceText(), clearBatch(), closeSidePanel(), deleteWorkflow(), fetchWorkflows() (+26 more)
### Community 28 - "workflow_routes.py"
Cohesion: 0.15
Nodes (26): handle_analyze(), handle_change_thumbnail(), handle_delete(), handle_import(), handle_list(), handle_metadata(), handle_raw(), handle_reanalyze_all() (+18 more)
### Community 29 - "GalleryMetadataStore"
Cohesion: 0.13
Nodes (9): GalleryMetadataStore, Path, グループ名を変更し、全画像のgroupsフィールドも更新する, gallery_metadata.json の構造: { "images": { "<abs_path>": { "favorite": bool,…, 存在しないパスをグループから一括削除する(1回の保存で完結), グループメンバーのパスをsetで返す(高速フィルタ用), グループ内の全画像を除外する(グループ自体は残す), 画像のパスキーを変更する(ファイル移動後のメタデータ引継ぎ) (+1 more)
### Community 30 - "WorkflowService"
Cohesion: 0.13
Nodes (13): Get raw workflow JSON content., Save metadata (tags, memo, summary, etc.) for a workflow., Manages workflow files and metadata., Import workflow files. Returns list of results., Rename workflow and its associated thumbnail., Delete workflow JSON and associated thumbnail., Re-analyze a workflow and save results to metadata., Re-analyze all workflows and update metadata. (+5 more)
### Community 31 - "LabPlanService"
Cohesion: 0.23
Nodes (4): LabPlanService, Path, Lab tab plan file management service (JSON plan + optional PNG index thumbnail)., Saves the contact-sheet index image into ComfyUI's own output folder, alongside…
### Community 32 - "skill_routes.py"
Cohesion: 0.14
Nodes (16): handle_delete(), handle_get_content(), handle_list(), handle_save(), Application, Request, Response, AI skill (.md system prompt) file management API routes. (+8 more)
### Community 35 - "CivitaiService"
Cohesion: 0.15
Nodes (11): CivitaiService, Build request headers, optionally including Bearer token., Calculate SHA256 hash of a file., Fetch model version info from CivitAI by SHA256 hash (GET). 429/5xx…, POST /model-versions/by-hash でハッシュリストを一括取得(最大100件/リクエスト)。 レスポンスの…, Extract relevant fields from CivitAI API response., Batch fetch CivitAI info for multiple model files. Phase 1: SHA256…, Clear cache for a specific hash or all. (+3 more)
### Community 38 - "index.html Template"
Cohesion: 0.10
Nodes (22): actions/checkout@v4, Comfy-Org/publish-node-action@main, DEVLOG.md, Publish to Comfy Registry Workflow, graphifyignore, main Branch, pyproject.toml, README.md (+14 more)
### Community 39 - "gallery_service.py"
Cohesion: 0.10
Nodes (13): Gallery Metadata Store - ギャラリー画像のメタデータ永続化, _clean_vault_tags(), _decode_image_data_url(), _FolderCache, _parse_vault_yaml_leaves(), Gallery Service - outputフォルダの画像管理、メタデータ閲覧, フォルダ単位の画像スキャン結果キャッシュ。 フォルダのmtimeが変わった場合、またはTTL超過時に再スキャンする。, data URL (data:<mime>;base64,<data>) をデコードし (バイト列, 拡張子) を返す。 ヘッダが無ければPNG扱い(旧互換)。 (+5 more)
### Community 41 - "image-prompt-tab.js"
Cohesion: 0.21
Nodes (20): activateImagePromptTab(), addSelectedToChips(), API, apiFetch(), cleanPromptText(), clearAllChips(), copyFinalPrompt(), createThumbCard() (+12 more)
### Community 42 - "KSampler Node"
Cohesion: 0.19
Nodes (20): CLIP Text Encode Negative Prompt Node, CLIP Text Encode Positive Prompt Node, Inpaint with Mask Editor One (Workflow Screenshot), Load Checkpoint Node, Mask Editor One Node, Save Image Node, VAE Encode (for Inpainting) Node, 3D Pose Editor Node (comfyui-vrm-pose-editor) (+12 more)
### Community 43 - "image-edit-tab.js"
Cohesion: 0.12
Nodes (8): comfyEditor, comfyWorkflow, GmicIntegration, MaskEditorOneBridge, MASK_TEXT_FONTS, fitToCanvas(), TOOL_DEFS, TEXT_FONTS
### Community 44 - "style-catalog-tab.js"
Cohesion: 0.22
Nodes (18): selectStyleByName(), activateStyleCatalogTab(), API, apiFetch(), copyText(), createThumbCard(), debounce(), initStyleCatalogTab() (+10 more)
### Community 45 - "add"
Cohesion: 0.22
Nodes (19): add(), fetchWorkflowRaw(), getCanvasDropPos(), handleInfoFile(), installCanvasDropHandler(), loadWorkflowOnCanvas(), placeClipTextEncodeNode(), placeLoraMgrNode() (+11 more)
### Community 46 - "comfyui-workflow.js"
Cohesion: 0.20
Nodes (13): _CONTROL_AFTER_GENERATE, _findInjectedWidgetIndex(), _flattenSubgraphs(), _getDynamicComboSubNames(), _getWidgetInputNames(), _getWidgetInputTypes(), _isExtraWidgetValue(), _isLinkedWidgetName() (+5 more)
### Community 51 - "gmic_routes.py"
Cohesion: 0.21
Nodes (14): _gmic_run_gui(), handle_open(), handle_result(), handle_status(), Application, Request, Response, G'MIC-Qt integration API routes. (+6 more)
### Community 52 - "ollama_routes.py"
Cohesion: 0.23
Nodes (14): _get_ollama_config(), handle_chat(), handle_models(), handle_test(), Application, Request, Response, Ollama API proxy routes. (+6 more)
### Community 54 - "analyze_workflow"
Cohesion: 0.20
Nodes (13): analyze_workflow(), _clip_type_from_ui_node(), _collect_all_ui_nodes(), _detect_model_type_from_name(), _model_name_from_api_node(), _model_name_from_ui_node(), Workflow analyzer - detects model types and counts input/output nodes., Analyze workflow JSON and return model types, input/output node counts. (+5 more)
### Community 56 - "lab-tab.js"
Cohesion: 0.12
Nodes (41): _applyPlanData(), _buildIndexImageDataUrl(), _buildPlanData(), _clearPlan(), COLUMN_KEYS, _defaultValueFor(), _emptyColumns(), _emptyLabState() (+33 more)
### Community 57 - ".list_images"
Cohesion: 0.17
Nodes (6): os.scandir() で画像ファイルを1回のシステムコールで列挙。 キャッシュがあればそれを返す。 Returns: [(name,…, os.walk() でフォルダ配下を再帰的に列挙する(サブフォルダの画像も含む)。 ImagePrompt/Style…, 指定フォルダ内の画像一覧を返す(recursive=Trueならサブフォルダも含める), 画像のプロンプトテキストを返す。 1. 画像と同名の .txt サイドカーがあればそれを使う 2. 無ければ ponyxlWildcardsVault 形式…, image_path の祖先を辿り、直下に thumbnails(_option2) を持つフォルダ…, ponyxlWildcardsVault形式のフォールバック解決。 thumbnails_option2 の "{leaf}.preview3.ext"…
### Community 60 - "gallery_feeder_extension.js"
Cohesion: 0.36
Nodes (11): beforeRegisterNodeDef(), fetchGroupImages(), getInputWidget(), getOrCreate(), _ns, setWidgetValue(), startLoop(), stopLoop() (+3 more)
### Community 61 - "createPanel"
Cohesion: 0.22
Nodes (13): applyTheme(), buildThemePanel(), createPanel(), fetchModelGroups(), fetchModelMetadata(), fetchPrompts(), fetchWorkflows(), injectStyles() (+5 more)
### Community 62 - "_runLabBatch"
Cohesion: 0.20
Nodes (10): _annotatedImageRef(), _applyLabLoraToWorkflow(), _buildLoraPromptInjection(), _buildWorkflowForIteration(), _fetchLabLoraMetadataCache(), _labTriggerWordsFor(), _runLabBatch(), _setRunUiState() (+2 more)
### Community 64 - "Workflow JSON"
Cohesion: 0.20
Nodes (10): EXTRA_PNGINFO, last_link_id, last_node_id, links array, Position Index, PROMPT, widgets_values, workflow_analyzer.py (+2 more)
### Community 65 - "WFS_GalleryFeeder"
Cohesion: 0.27
Nodes (4): Path, WFS_GalleryFeeder – Feeds images from a gallery group into a workflow., Gallery グループ内の画像をインデックス順に1枚ずつ出力するノード。, WFS_GalleryFeeder
### Community 66 - "initGenerateTab"
Cohesion: 0.22
Nodes (7): initGenerateTab(), _loadStyles(), _renderStyleDropdown(), updateStatus(), highlightJSON(), syncJsonHighlight(), syncScroll()
### Community 69 - "fromWorkflow"
Cohesion: 0.36
Nodes (10): _collectAllNodes(), _collectUnique(), fromWorkflow(), _extractCheckpoints(), _extractDiffusionModels(), _extractLoRAs(), _extractMarkdownNoteModels(), addU() (+2 more)
### Community 70 - "_extractPromptsAPI"
Cohesion: 0.33
Nodes (10): _extractPrompts(), _extractPromptsAPI(), _extractPromptsFromNodeSet(), _extractPromptsLiteGraph(), _isPromptStylerNode(), _isSamplerNode(), _isTextEncoderNode(), _resolveEditPlusText() (+2 more)
### Community 71 - "generate_doc_index.py"
Cohesion: 0.53
Nodes (5): generate_devlog_index(), generate_readme_index(), main(), Path, Regenerate README.index.md / DEVLOG.index.md from README.md / DEVLOG.md.…
### Community 72 - "WS Inpaint Basic Workflow"
Cohesion: 0.53
Nodes (9): CLIP Text Encode (Prompt) - negative conditioning, CLIP Text Encode (Prompt) - positive conditioning, KSampler node (ddim sampler, 30 steps, cfg 4.0, denoise 1.00), Load Checkpoint node (hayochamixIDXL_v11+_bl checkpoint), Load Image node (clipspace painted mask input), Save Image node (ComfyUI filename prefix), VAE Decode node, VAE Encode (for Inpainting) node with grow_mask_by (+1 more)
### Community 73 - "._bg_index_folder"
Cohesion: 0.25
Nodes (5): Event, バックグラウンドスレッドで未キャッシュ画像のprompt_cacheを構築する。 10枚処理するたびに50msスリープしてメインスレッドへの影響を最小化。, PNG/JPEGからメタデータを抽出し、保存済みメタと合わせて返す, PNGのtEXtチャンクからメタデータを抽出, JPEGのEXIF/commentからメタデータを抽出(簡易)
### Community 74 - "aiohttp"
Cohesion: 0.16
Nodes (14): aiohttp, py/routes, _get_api_key(), handle_proxy(), _is_allowed_base_url(), Application, Request, Response (+6 more)
### Community 75 - "import_style_prompt_seed.py"
Cohesion: 0.36
Nodes (8): clean_tags(), import_category(), main(), parse_yaml_leaves(), Path, Style/Prompt ギャラリー用シードデータ投入スクリプト。 comfyui_prompt_gallery / prompt_builder_proto…, comfyui_prompt_gallery の parseYamlForImages と同じ簡易パーサ(PyYAML不要)。 「key:」行の直後が「-…, 1カテゴリ分を投入する。戻り値: (copied, images_without_prompt, leaves_total)
### Community 76 - "Image Edit (FireRed Image Edit 1.1) node"
Cohesion: 0.32
Nodes (8): 3D Pose Editor node, FireRed-Image-Edit-1.1_fp8mixed_comfy.safetensors, FireRed-Image-Edit-1.0-Lightning-8steps-v1.0.safetensors (LoRA), Image Edit (FireRed Image Edit 1.1) node, qwen_2.5_vl_7b_fp8_scaled.safetensors (CLIP), qwen_image_vae.safetensors (VAE), Save Image node, 3D Pose Editor to Image Edit (Fire Red) Workflow
### Community 77 - "Version 0.3.9"
Cohesion: 0.18
Nodes (11): AI TOOL Tab, Models Tab, Nodes Tab, Prompt Tab, Version 0.1.2, Version 0.1.7, Version 0.2.3, Version 0.3.14 (+3 more)
### Community 78 - "DWPose Image Feeder Workflow"
Cohesion: 0.52
Nodes (7): DWPose Image Feeder Workflow, Apply ControlNet Node, DWPose Estimator Node (comfyui-controlnet-aux), Image Feeder Node (comfyui-image-feeder), KSampler Node, Load Checkpoint Node (animagineXLRealistic_v6), Load ControlNet Model Node (OpenPoseXL2)
### Community 79 - "wfm.py"
Cohesion: 0.21
Nodes (12): Jinja2, Request, Response, Serve the main SPA page., Serve files from the current workflows directory (dynamic path)., Serve files (index thumbnails) from the Lab plan directory., Main entry point for Workflow Studio plugin., Register all routes with ComfyUI's server. (+4 more)
### Community 80 - "README.index.md"
Cohesion: 0.40
Nodes (6): on_doc_edit.py, DEVLOG.index.md, generate_doc_index.py, pre-commit, graphify, README.index.md
### Community 81 - "WFS_PromptText"
Cohesion: 0.33
Nodes (3): WFS_PromptText – Prompt preset node with positive/negative STRING outputs., Outputs positive and negative prompt strings., WFS_PromptText
### Community 82 - "workflow_service.py"
Cohesion: 0.40
Nodes (4): extract_png_workflow(), Extract ComfyUI workflow JSON from PNG metadata., Extract ComfyUI workflow JSON from PNG byte data. Returns dict or None., Workflow CRUD and metadata management service.
### Community 83 - "SPA"
Cohesion: 0.40
Nodes (5): ComfyUI, SPA, static, templates, web/comfyui
### Community 84 - "prompt-ai-chat.js"
Cohesion: 0.34
Nodes (14): addChatMessage(), applyToGenerateUI(), attachFile(), chatWithAi(), clearChat(), fetchAiModels(), getPromptAiConfig(), initAiChatUI() (+6 more)
### Community 85 - "Tagger Tab requirements.txt"
Cohesion: 0.40
Nodes (5): Tagger Tab requirements.txt, onnxruntime (WD Tagger / SwinV2), piexif (JPEG EXIF tag writing), python-dotenv (Unsloth .env loading), tensorflow (optional, DeepDanbooru)
### Community 86 - "data directory"
Cohesion: 0.50
Nodes (4): data directory, metadata.json, node_metadata.json, settings.json
### Community 87 - "t"
Cohesion: 0.25
Nodes (20): showToast(), _applyDefaultCheckpointIfEnabled(), loadWorkflowIntoEditor(), saveCurrentWorkflow(), t(), _initPlanDropZone(), _loadPlanFromFile(), _loadPlanFromIndexImage() (+12 more)
### Community 88 - "Chinese Language Support"
Cohesion: 1.00
Nodes (3): Chinese Language Support, English Language Support, Japanese Language Support
### Community 89 - "Version 0.3.95"
Cohesion: 0.67
Nodes (3): ImagePrompt Gallery Subtab, Style_Catalog Subtab, Version 0.3.95
### Community 90 - "Windows"
Cohesion: 0.67
Nodes (3): LongPathsEnabled, MAX_PATH, Windows
### Community 98 - "lab_routes.py"
Cohesion: 0.42
Nodes (10): handle_delete(), handle_get_content(), handle_list(), handle_save(), handle_save_index_to_output(), Application, Request, Response (+2 more)
### Community 153 - "prompts_routes.py"
Cohesion: 0.25
Nodes (13): handle_create(), handle_delete(), handle_list(), handle_update(), Application, Request, Response, Prompt presets API routes. (+5 more)
### Community 157 - "SettingsService"
Cohesion: 0.28
Nodes (4): Return CivitAI API key. Env var CIVITAI_API_KEY takes priority over…, Merge updates into existing settings., Manages application settings (data/settings.json)., SettingsService
### Community 174 - "app.js"
Cohesion: 0.22
Nodes (8): applyI18nToHtml(), initModal(), _onHelpSearch(), initI18n(), applyJsonColors(), applyModelTabActiveColor(), applyTextareaFontSize(), getSettings()
### Community 176 - "util.js"
Cohesion: 0.43
Nodes (7): AI_BACKEND_DEFAULT_URLS, _bytesToDataUrl(), _dataUrlToBytes(), embedPngTextChunk(), _joinBytes(), _n2b(), _pngCrc32()
### Community 177 - "civitai_service.py"
Cohesion: 0.33
Nodes (5): _get_ssl_context(), _make_ssl_context(), CivitAI API integration service., Return an SSL context with CA verification. 1. certifi CA bundle (available in…, Download an image from URL and save to save_path. Returns True on success.
### Community 178 - "config.py"
Cohesion: 0.22
Nodes (5): Resolve workflows dir from settings, falling back to default., _resolve_workflows_dir(), Node metadata and node sets management service., Prompt presets management service., Settings management service.
### Community 179 - "createModelItem"
Cohesion: 0.57
Nodes (7): createModelItem(), fetchModelList(), matchesModelSearch(), renderModelAll(), renderModelByType(), renderModelFavorites(), renderModelGroups()
### Community 180 - "_renderBatchPreview"
Cohesion: 0.20
Nodes (18): _buildSimpleGroupList(), _getGroupSelCount(), _getGroupSelCountFrom(), initBatchTab(), _loadBatchCheckpointGroups(), _loadBatchLoraGroups(), _loadPromptGroupsForBatch(), _loadWorkflowGroupsForBatch() (+10 more)
## Knowledge Gaps
- **216 isolated node(s):** `comfyui-workflow-studio`, `LANG_NAMES`, `VLM_PROMPTS`, `IMAGE_GEN_TOOLS`, `skillFiles` (+211 more)
These have ≤1 connection - possible missing edges or undocumented components.
- **94 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `showToast()` connect `t` to `escapeHtml`, `prompt-table.js`, `generate-tab.js`, `_openCellModal`, `gallery-tab.js`, `ImageEditTab`, `ai-tab.js`, `feeder-tab.js`, `settings-tab.js`, `tagger-tab.js`, `comfyui-editor.js`, `nodes-tab.js`, `workflow-tab.js`, `FileExport`, `image-prompt-tab.js`, `image-edit-tab.js`, `style-catalog-tab.js`, `app.js`, `BlurTool`, `lab-tab.js`, `_runLabBatch`, `BgRemove`, `initGenerateTab`, `InpaintI2IActions`, `Sam3Segmentation`, `prompt-ai-chat.js`?**
_High betweenness centrality (0.071) - this node is a cross-community bridge._
- **Why does `t()` connect `t` to `escapeHtml`, `prompt-table.js`, `generate-tab.js`, `_openCellModal`, `gallery-tab.js`, `ai-tab.js`, `feeder-tab.js`, `metadata-tab.js`, `settings-tab.js`, `tagger-tab.js`, `comfyui-editor.js`, `nodes-tab.js`, `workflow-tab.js`, `image-prompt-tab.js`, `style-catalog-tab.js`, `app.js`, `lab-tab.js`, `_runLabBatch`, `initGenerateTab`, `prompt-ai-chat.js`?**
_High betweenness centrality (0.058) - this node is a cross-community bridge._
- **Why does `ImageEditTab` connect `ImageEditTab` to `image-edit-tab.js`, `app.js`?**
_High betweenness centrality (0.028) - this node is a cross-community bridge._
- **What connects `comfyui-workflow-studio`, `LANG_NAMES`, `VLM_PROMPTS` to the rest of the system?**
_216 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `escapeHtml` be split into smaller, more focused modules?**
_Cohesion score 0.09288389513108614 - nodes in this community are weakly interconnected._
- **Should `prompt-table.js` be split into smaller, more focused modules?**
_Cohesion score 0.06366691560866318 - nodes in this community are weakly interconnected._
- **Should `models_routes.py` be split into smaller, more focused modules?**
_Cohesion score 0.0554954954954955 - nodes in this community are weakly interconnected._
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+890
View File
@@ -0,0 +1,890 @@
{
"CLAUDE.md": {
"mtime": 1787279658.5963283,
"seen": 1787380810.3754587,
"ast_hash": "b2c014309df240903aa90a26914c8c19",
"semantic_hash": "b2c014309df240903aa90a26914c8c19"
},
".claude/settings.json": {
"mtime": 1787279595.344592,
"seen": 1787380810.2925637,
"ast_hash": "cd2c4308b55c5d1aa1b647cdec814b79",
"semantic_hash": "cd2c4308b55c5d1aa1b647cdec814b79"
},
"__init__.py": {
"mtime": 1781939762.254596,
"seen": 1787279199.0011544,
"ast_hash": "72d9ef06026dff7be74da81ff98a306a",
"semantic_hash": "72d9ef06026dff7be74da81ff98a306a"
},
"prestartup_script.py": {
"mtime": 1787036267.332648,
"seen": 1787279199.0011563,
"ast_hash": "7b5d482ef21a480d1b38356e8d82970b",
"semantic_hash": "7b5d482ef21a480d1b38356e8d82970b"
},
"py/__init__.py": {
"mtime": 1773797715.629029,
"seen": 1787279199.0011575,
"ast_hash": "d41d8cd98f00b204e9800998ecf8427e",
"semantic_hash": "d41d8cd98f00b204e9800998ecf8427e"
},
"py/config.py": {
"mtime": 1786245317.3352194,
"seen": 1787279199.001159,
"ast_hash": "b013c27bb7cd9a79449961539fdcd30f",
"semantic_hash": "b013c27bb7cd9a79449961539fdcd30f"
},
"py/nodes/__init__.py": {
"mtime": 1774423045.6646452,
"seen": 1787279199.00116,
"ast_hash": "d41d8cd98f00b204e9800998ecf8427e",
"semantic_hash": "d41d8cd98f00b204e9800998ecf8427e"
},
"py/nodes/gallery_feeder_node.py": {
"mtime": 1781943269.5205867,
"seen": 1787279199.0011609,
"ast_hash": "d37c520b0f76e70e60ec7c72db904bf4",
"semantic_hash": "d37c520b0f76e70e60ec7c72db904bf4"
},
"py/nodes/prompt_text.py": {
"mtime": 1774423045.6669831,
"seen": 1787279199.0011618,
"ast_hash": "43cf16f182b9eda5fade2b52c2439372",
"semantic_hash": "43cf16f182b9eda5fade2b52c2439372"
},
"py/routes/__init__.py": {
"mtime": 1773797716.663036,
"seen": 1787279199.0011628,
"ast_hash": "d41d8cd98f00b204e9800998ecf8427e",
"semantic_hash": "d41d8cd98f00b204e9800998ecf8427e"
},
"py/routes/eagle_routes.py": {
"mtime": 1785464911.9023821,
"seen": 1787279199.0011635,
"ast_hash": "edd32039935a892317c55b434c9839ab",
"semantic_hash": "edd32039935a892317c55b434c9839ab"
},
"py/routes/gallery_routes.py": {
"mtime": 1786682156.6899943,
"seen": 1787279199.001165,
"ast_hash": "59e4c5d34ee2329ab9e0a66f841d1676",
"semantic_hash": "59e4c5d34ee2329ab9e0a66f841d1676"
},
"py/routes/gmic_routes.py": {
"mtime": 1782544784.03979,
"seen": 1787279199.0011659,
"ast_hash": "b909c65af6590c0ca058136cb0b9234e",
"semantic_hash": "b909c65af6590c0ca058136cb0b9234e"
},
"py/routes/lab_routes.py": {
"mtime": 1786322410.571655,
"seen": 1787279199.0011666,
"ast_hash": "48e94f71b11f2e494bb98bb7113e2baa",
"semantic_hash": "48e94f71b11f2e494bb98bb7113e2baa"
},
"py/routes/models_routes.py": {
"mtime": 1782289767.1073005,
"seen": 1787279199.0011675,
"ast_hash": "067aa9c89085fa3e077fdfacbb6be2cd",
"semantic_hash": "067aa9c89085fa3e077fdfacbb6be2cd"
},
"py/routes/nodes_routes.py": {
"mtime": 1774255599.0841086,
"seen": 1787279199.0011685,
"ast_hash": "dc5f7b12dce346631ff945c31bf03ac9",
"semantic_hash": "dc5f7b12dce346631ff945c31bf03ac9"
},
"py/routes/ollama_routes.py": {
"mtime": 1784126582.1613884,
"seen": 1787279199.0011694,
"ast_hash": "80552c0676f7bbd4209eb95cf7a03f5b",
"semantic_hash": "80552c0676f7bbd4209eb95cf7a03f5b"
},
"py/routes/prompts_routes.py": {
"mtime": 1774423045.6696556,
"seen": 1787279199.0011702,
"ast_hash": "53b5641f3ad6f65e8ae665601c4739d7",
"semantic_hash": "53b5641f3ad6f65e8ae665601c4739d7"
},
"py/routes/settings_routes.py": {
"mtime": 1786681377.025748,
"seen": 1787279199.001171,
"ast_hash": "bb2f332c04474ee39319c2d0b8107db9",
"semantic_hash": "bb2f332c04474ee39319c2d0b8107db9"
},
"py/routes/skill_routes.py": {
"mtime": 1785634791.033795,
"seen": 1787279199.0011723,
"ast_hash": "3318c506163c720c5412ec0f8ff3a28a",
"semantic_hash": "3318c506163c720c5412ec0f8ff3a28a"
},
"py/routes/tagger_routes.py": {
"mtime": 1781503496.8879485,
"seen": 1787279199.001173,
"ast_hash": "9c0559b594a69354882da0b1643e11f0",
"semantic_hash": "9c0559b594a69354882da0b1643e11f0"
},
"py/routes/unsloth_routes.py": {
"mtime": 1787036726.267709,
"seen": 1787279199.001174,
"ast_hash": "93d4de97937f472f9618a35a0b4211d6",
"semantic_hash": "93d4de97937f472f9618a35a0b4211d6"
},
"py/routes/wildcard_routes.py": {
"mtime": 1777370036.4121041,
"seen": 1787279199.0011756,
"ast_hash": "1d0ea981a44ffab77d62c214951f4536",
"semantic_hash": "1d0ea981a44ffab77d62c214951f4536"
},
"py/routes/workflow_routes.py": {
"mtime": 1773896239.095392,
"seen": 1787279199.0011766,
"ast_hash": "e64f3e7b5d0dfe3543ffbfeb137aacb3",
"semantic_hash": "e64f3e7b5d0dfe3543ffbfeb137aacb3"
},
"py/services/__init__.py": {
"mtime": 1773797717.739297,
"seen": 1787279199.0011773,
"ast_hash": "d41d8cd98f00b204e9800998ecf8427e",
"semantic_hash": "d41d8cd98f00b204e9800998ecf8427e"
},
"py/services/civitai_service.py": {
"mtime": 1780233122.7587051,
"seen": 1787279199.001178,
"ast_hash": "3b4a2a118bc56dd27e768a2819b401e7",
"semantic_hash": "3b4a2a118bc56dd27e768a2819b401e7"
},
"py/services/gallery_metadata.py": {
"mtime": 1786170828.9941547,
"seen": 1787279199.0011792,
"ast_hash": "9d02a71d56b7ca2a88cdf8c56fadf912",
"semantic_hash": "9d02a71d56b7ca2a88cdf8c56fadf912"
},
"py/services/gallery_service.py": {
"mtime": 1786638406.9058151,
"seen": 1787279199.0011802,
"ast_hash": "c8b9858f015f7f4a934c4b630e905107",
"semantic_hash": "c8b9858f015f7f4a934c4b630e905107"
},
"py/services/lab_plan_service.py": {
"mtime": 1786322396.0192728,
"seen": 1787279199.001181,
"ast_hash": "5d2c928c077ad7b788f15419b39ef51f",
"semantic_hash": "5d2c928c077ad7b788f15419b39ef51f"
},
"py/services/models_service.py": {
"mtime": 1782393318.5989842,
"seen": 1787279199.0011816,
"ast_hash": "0885cc6852199fa45271192ea0d6713a",
"semantic_hash": "0885cc6852199fa45271192ea0d6713a"
},
"py/services/nodes_service.py": {
"mtime": 1774255599.0862236,
"seen": 1787279199.0011828,
"ast_hash": "8819590ffdc136fb2912d9c5696e26e0",
"semantic_hash": "8819590ffdc136fb2912d9c5696e26e0"
},
"py/services/png_extractor.py": {
"mtime": 1773797967.5810304,
"seen": 1787279199.0011837,
"ast_hash": "1282b6032d78cba2a4bbbfb876126bc1",
"semantic_hash": "1282b6032d78cba2a4bbbfb876126bc1"
},
"py/services/prompts_service.py": {
"mtime": 1774423045.6711988,
"seen": 1787279199.0011845,
"ast_hash": "79a98e220d2b556106e8530054547155",
"semantic_hash": "79a98e220d2b556106e8530054547155"
},
"py/services/settings_service.py": {
"mtime": 1773798498.9270506,
"seen": 1787279199.0011854,
"ast_hash": "dade5ea667a2c6408434ad3061c76db7",
"semantic_hash": "dade5ea667a2c6408434ad3061c76db7"
},
"py/services/skill_service.py": {
"mtime": 1785637306.8654232,
"seen": 1787279199.0011866,
"ast_hash": "5ebe579995c1c674e4219e58b3bd5855",
"semantic_hash": "5ebe579995c1c674e4219e58b3bd5855"
},
"py/services/tagger_db_service.py": {
"mtime": 1781503496.8949444,
"seen": 1787279199.0011873,
"ast_hash": "de0ca007db5159484e8ff3b8a36a3b84",
"semantic_hash": "de0ca007db5159484e8ff3b8a36a3b84"
},
"py/services/tagger_service.py": {
"mtime": 1781503496.8969479,
"seen": 1787279199.0011883,
"ast_hash": "7bfde3ebe93f6fa0062a6aecba3f10d9",
"semantic_hash": "7bfde3ebe93f6fa0062a6aecba3f10d9"
},
"py/services/wildcard_service.py": {
"mtime": 1777380000.0054882,
"seen": 1787279199.0011892,
"ast_hash": "5814ed3cf2e31bf8b4abaa15c697b0cd",
"semantic_hash": "5814ed3cf2e31bf8b4abaa15c697b0cd"
},
"py/services/workflow_analyzer.py": {
"mtime": 1785474766.4736228,
"seen": 1787279199.00119,
"ast_hash": "937d6b02a6235795cb22ceb39e81f719",
"semantic_hash": "937d6b02a6235795cb22ceb39e81f719"
},
"py/services/workflow_service.py": {
"mtime": 1775439760.4805496,
"seen": 1787279199.0011911,
"ast_hash": "a2e47c0b8780ec7ca292310b16733a8c",
"semantic_hash": "a2e47c0b8780ec7ca292310b16733a8c"
},
"py/wfm.py": {
"mtime": 1787036294.0749958,
"seen": 1787279199.0011919,
"ast_hash": "cb1c96536f67edb380d1010b6165d74d",
"semantic_hash": "cb1c96536f67edb380d1010b6165d74d"
},
"pyproject.toml": {
"mtime": 1787378263.2900941,
"seen": 1787380810.3265483,
"ast_hash": "f514fae02a3b48726f5073e932cfa1b3",
"semantic_hash": "f514fae02a3b48726f5073e932cfa1b3"
},
"static/js/ai-tab.js": {
"mtime": 1787293482.4888227,
"seen": 1787380810.3265514,
"ast_hash": "960b474155386a36000e6961b0b2e0c3",
"semantic_hash": "960b474155386a36000e6961b0b2e0c3"
},
"static/js/app.js": {
"mtime": 1787377516.2436306,
"seen": 1787380810.3265538,
"ast_hash": "7df994a3e8f6c34d27a1ccd88b207a5c",
"semantic_hash": "7df994a3e8f6c34d27a1ccd88b207a5c"
},
"static/js/comfyui-client.js": {
"mtime": 1786676208.2330563,
"seen": 1787279199.0011961,
"ast_hash": "bb546a6ae7bd35d1c16fee311681be73",
"semantic_hash": "bb546a6ae7bd35d1c16fee311681be73"
},
"static/js/comfyui-editor.js": {
"mtime": 1787293462.7015421,
"seen": 1787380810.3274822,
"ast_hash": "fe27626a41d18f02bdea2b89aaaf740b",
"semantic_hash": "fe27626a41d18f02bdea2b89aaaf740b"
},
"static/js/comfyui-workflow.js": {
"mtime": 1787293410.2500806,
"seen": 1787380810.3274848,
"ast_hash": "255cfe0c2172639ed698a5e9397d7144",
"semantic_hash": "255cfe0c2172639ed698a5e9397d7144"
},
"static/js/feeder-tab.js": {
"mtime": 1781939989.0796032,
"seen": 1787279199.0011988,
"ast_hash": "dcd5977c5fe691b87e2379cd0e018a12",
"semantic_hash": "dcd5977c5fe691b87e2379cd0e018a12"
},
"static/js/gallery-tab.js": {
"mtime": 1787368748.1550386,
"seen": 1787380810.328425,
"ast_hash": "0144bbe48e21eccc498714404e29e29e",
"semantic_hash": "0144bbe48e21eccc498714404e29e29e"
},
"static/js/generate-tab.js": {
"mtime": 1787401222.9019487,
"seen": 1787401432.6967273,
"ast_hash": "dbfc96b6400bd780990725e390f275c9",
"semantic_hash": ""
},
"static/js/i18n.js": {
"mtime": 1787377822.448605,
"seen": 1787380810.32843,
"ast_hash": "d925b681cc485326659fbc24f5a87dda",
"semantic_hash": "d925b681cc485326659fbc24f5a87dda"
},
"static/js/image-edit-tab.js": {
"mtime": 1787199901.562169,
"seen": 1787279199.001202,
"ast_hash": "be7b15d85bb185e2fd3492f4d5657f21",
"semantic_hash": "be7b15d85bb185e2fd3492f4d5657f21"
},
"static/js/image-edit/BgRemove.js": {
"mtime": 1787126632.8601232,
"seen": 1787279199.0012033,
"ast_hash": "add6a58068bdadc0c7641202f36ddb27",
"semantic_hash": "add6a58068bdadc0c7641202f36ddb27"
},
"static/js/image-edit/BlurTool.js": {
"mtime": 1787126263.0542421,
"seen": 1787279199.0012043,
"ast_hash": "1e52bc3757110a271ec17d923784a91b",
"semantic_hash": "1e52bc3757110a271ec17d923784a91b"
},
"static/js/image-edit/DrawTool.js": {
"mtime": 1782717315.6436062,
"seen": 1787279199.001205,
"ast_hash": "a97a6a97ae28c804a7c5fa50448a2c87",
"semantic_hash": "a97a6a97ae28c804a7c5fa50448a2c87"
},
"static/js/image-edit/FileExport.js": {
"mtime": 1787192008.741717,
"seen": 1787279199.0012057,
"ast_hash": "cf645b775e537ad276c9e070c7849349",
"semantic_hash": "cf645b775e537ad276c9e070c7849349"
},
"static/js/image-edit/GmicIntegration.js": {
"mtime": 1787125777.3889306,
"seen": 1787279199.0012069,
"ast_hash": "023d9d19e57d8fa6ebedc3c489ecf7ca",
"semantic_hash": "023d9d19e57d8fa6ebedc3c489ecf7ca"
},
"static/js/image-edit/InpaintI2IActions.js": {
"mtime": 1787127273.4351766,
"seen": 1787279199.0012076,
"ast_hash": "9ea57922985b63d4ec8eb44219a8341b",
"semantic_hash": "9ea57922985b63d4ec8eb44219a8341b"
},
"static/js/image-edit/LayerManager.js": {
"mtime": 1782717943.772222,
"seen": 1787279199.0012085,
"ast_hash": "596cd1906208fe72e1c2953d4d7f7135",
"semantic_hash": "596cd1906208fe72e1c2953d4d7f7135"
},
"static/js/image-edit/MaskEditorOneBridge.js": {
"mtime": 1787199887.897264,
"seen": 1787279199.0012095,
"ast_hash": "db2ef8c024c7e72baa0dfdb79b8abd4d",
"semantic_hash": "db2ef8c024c7e72baa0dfdb79b8abd4d"
},
"static/js/image-edit/MaskEditorOneTools.js": {
"mtime": 1782719665.7021136,
"seen": 1787279199.0012105,
"ast_hash": "b6b16c43ce528f7c9921eab0f4eda335",
"semantic_hash": "b6b16c43ce528f7c9921eab0f4eda335"
},
"static/js/image-edit/MaskTool.js": {
"mtime": 1782699721.4711535,
"seen": 1787279199.0012114,
"ast_hash": "116469f33829c5b2e6270f4b278b2b9c",
"semantic_hash": "116469f33829c5b2e6270f4b278b2b9c"
},
"static/js/image-edit/Sam3Segmentation.js": {
"mtime": 1787126893.774897,
"seen": 1787279199.0012121,
"ast_hash": "98c3a330ae7ea3369c00168c54c66d53",
"semantic_hash": "98c3a330ae7ea3369c00168c54c66d53"
},
"static/js/image-edit/SelectTool.js": {
"mtime": 1782368193.2572634,
"seen": 1787279199.0012128,
"ast_hash": "cb8db6bd5ee742b15f3beee4a5173377",
"semantic_hash": "cb8db6bd5ee742b15f3beee4a5173377"
},
"static/js/image-edit/ShapeTool.js": {
"mtime": 1782375200.0253434,
"seen": 1787279199.001214,
"ast_hash": "36d00bf6b80ebea13314d2853528c44f",
"semantic_hash": "36d00bf6b80ebea13314d2853528c44f"
},
"static/js/image-edit/TextTool.js": {
"mtime": 1782368193.2592669,
"seen": 1787279199.0012147,
"ast_hash": "88f9e60251c2f78957e42c33ed5196f8",
"semantic_hash": "88f9e60251c2f78957e42c33ed5196f8"
},
"static/js/image-prompt-tab.js": {
"mtime": 1786638406.9362252,
"seen": 1787279199.0012157,
"ast_hash": "cf39285a30e3f8b79f6f51dfe13f86b5",
"semantic_hash": "cf39285a30e3f8b79f6f51dfe13f86b5"
},
"static/js/json-highlight.js": {
"mtime": 1773834925.1977189,
"seen": 1787279199.0012164,
"ast_hash": "e83e7a7a507d160b9cd503235a79135c",
"semantic_hash": "e83e7a7a507d160b9cd503235a79135c"
},
"static/js/lab-tab.js": {
"mtime": 1787310963.3056493,
"seen": 1787380810.343902,
"ast_hash": "11a5776c4163e2a97ef490e85de7db63",
"semantic_hash": "11a5776c4163e2a97ef490e85de7db63"
},
"static/js/metadata-tab.js": {
"mtime": 1787377525.9536967,
"seen": 1787380810.3439052,
"ast_hash": "5ac004dd3708aa4dc8890256232fd99e",
"semantic_hash": "5ac004dd3708aa4dc8890256232fd99e"
},
"static/js/models-tab.js": {
"mtime": 1787145102.2314196,
"seen": 1787279199.001219,
"ast_hash": "dcee8a68713cd300d0862b1c376d442f",
"semantic_hash": "dcee8a68713cd300d0862b1c376d442f"
},
"static/js/models/badges.js": {
"mtime": 1787143926.3653927,
"seen": 1787279199.00122,
"ast_hash": "0c1901a90a12f1b23df416d9eef11e1d",
"semantic_hash": "0c1901a90a12f1b23df416d9eef11e1d"
},
"static/js/models/detail-panel.js": {
"mtime": 1787144898.6748104,
"seen": 1787279199.0012212,
"ast_hash": "9907a4af0524b35d80e3b9fc7925324e",
"semantic_hash": "9907a4af0524b35d80e3b9fc7925324e"
},
"static/js/models/filters.js": {
"mtime": 1787144201.7602522,
"seen": 1787279199.001222,
"ast_hash": "afd754f68d01f64c51995929b3841e56",
"semantic_hash": "afd754f68d01f64c51995929b3841e56"
},
"static/js/models/grid-view.js": {
"mtime": 1787144745.5522888,
"seen": 1787279199.0012226,
"ast_hash": "492e91fff2b8743a5243f85a736eb689",
"semantic_hash": "492e91fff2b8743a5243f85a736eb689"
},
"static/js/models/helpers.js": {
"mtime": 1787144193.741004,
"seen": 1787279199.0012236,
"ast_hash": "1c7b796f2507f55403fa5d11f304580a",
"semantic_hash": "1c7b796f2507f55403fa5d11f304580a"
},
"static/js/models/selection-bulk.js": {
"mtime": 1787144787.0092065,
"seen": 1787279199.0012245,
"ast_hash": "d445ff4dc4e9810afea73ff53c76b05b",
"semantic_hash": "d445ff4dc4e9810afea73ff53c76b05b"
},
"static/js/models/state.js": {
"mtime": 1787143674.705312,
"seen": 1787279199.0012252,
"ast_hash": "172ced5fdc4c96095f2760d7ef12d77d",
"semantic_hash": "172ced5fdc4c96095f2760d7ef12d77d"
},
"static/js/nodes-tab.js": {
"mtime": 1782619197.3828287,
"seen": 1787279199.0012262,
"ast_hash": "3467d4682a8c20a2b209b5db224ce6e2",
"semantic_hash": "3467d4682a8c20a2b209b5db224ce6e2"
},
"static/js/prompt-tab.js": {
"mtime": 1787399045.1690862,
"seen": 1787399276.0028682,
"ast_hash": "184961647ceccdf98c8c031c4da96889",
"semantic_hash": ""
},
"static/js/settings-tab.js": {
"mtime": 1787227602.6323576,
"seen": 1787279199.001228,
"ast_hash": "85b55cac9901afc9e94e32f0aa220d2b",
"semantic_hash": "85b55cac9901afc9e94e32f0aa220d2b"
},
"static/js/style-catalog-tab.js": {
"mtime": 1786678976.6511285,
"seen": 1787279199.001229,
"ast_hash": "a2956544bf800ac34f8084b8acd0714b",
"semantic_hash": "a2956544bf800ac34f8084b8acd0714b"
},
"static/js/tagger-tab.js": {
"mtime": 1781503496.933307,
"seen": 1787279199.0012298,
"ast_hash": "5e1c858a13e95148eeac1d5b5be5e4f3",
"semantic_hash": "5e1c858a13e95148eeac1d5b5be5e4f3"
},
"static/js/util.js": {
"mtime": 1787036300.7369778,
"seen": 1787279199.001231,
"ast_hash": "29774ed440f2b60a708c70db1b3ae208",
"semantic_hash": "29774ed440f2b60a708c70db1b3ae208"
},
"static/js/workflow-tab.js": {
"mtime": 1785474064.011484,
"seen": 1787279199.001232,
"ast_hash": "65caea21e8e02d81f2e85c75c7231dca",
"semantic_hash": "65caea21e8e02d81f2e85c75c7231dca"
},
"tools/import_style_prompt_seed.py": {
"mtime": 1786616195.405381,
"seen": 1787279199.0012326,
"ast_hash": "02997888c17a6061b7910cddfdd4d89a",
"semantic_hash": "02997888c17a6061b7910cddfdd4d89a"
},
"web/comfyui/gallery_feeder_extension.js": {
"mtime": 1781943835.232655,
"seen": 1787279199.0012345,
"ast_hash": "0048b031e64a433e29a5f7112e82012d",
"semantic_hash": "0048b031e64a433e29a5f7112e82012d"
},
"web/comfyui/node_sets_menu.js": {
"mtime": 1787199930.9575465,
"seen": 1787279199.0012355,
"ast_hash": "a9d7ad5d194ac2f4b125978a7b048042",
"semantic_hash": "a9d7ad5d194ac2f4b125978a7b048042"
},
"web/comfyui/top_menu_extension.js": {
"mtime": 1782696309.9055538,
"seen": 1787279199.0012362,
"ast_hash": "2c74498722b46d42bcc15f61ec35dfc4",
"semantic_hash": "2c74498722b46d42bcc15f61ec35dfc4"
},
"workflows/ws_2d_pose_editor_to_Image_Edit( FireRed ).json": {
"mtime": 1779256606.5720088,
"seen": 1787279199.0012372,
"ast_hash": "52801ad2b42eca5e3a5f8fc51332d2c3",
"semantic_hash": "52801ad2b42eca5e3a5f8fc51332d2c3"
},
"workflows/ws_3d_pose_editor_to_Image_Edit( Fire Red).json": {
"mtime": 1779257129.3572881,
"seen": 1787279199.001238,
"ast_hash": "8260ca467693c21c497f98113abf37f9",
"semantic_hash": "8260ca467693c21c497f98113abf37f9"
},
"workflows/ws_3d_pose_editor_to_Image_Edit( Flux2 Klein ).json": {
"mtime": 1779257864.2496417,
"seen": 1787279199.001239,
"ast_hash": "7eba746ab9fdca0aefabdc7c7c7bd13e",
"semantic_hash": "7eba746ab9fdca0aefabdc7c7c7bd13e"
},
"workflows/ws_dwpose_image_feeder.json": {
"mtime": 1779255324.1402953,
"seen": 1787279199.0012398,
"ast_hash": "282ce14b11b8b88ddc91e1d318756c0d",
"semantic_hash": "282ce14b11b8b88ddc91e1d318756c0d"
},
"workflows/ws_inpaint_basic.json": {
"mtime": 1784801838.7836998,
"seen": 1787279199.0012407,
"ast_hash": "43e83496dec4856ab9d97c8b950148ec",
"semantic_hash": "43e83496dec4856ab9d97c8b950148ec"
},
"workflows/ws_inpaint_mask_editor_one.json": {
"mtime": 1784801946.0336668,
"seen": 1787279199.001242,
"ast_hash": "ac0a865c1dacd2b30c489f08f8b4df4d",
"semantic_hash": "ac0a865c1dacd2b30c489f08f8b4df4d"
},
"workflows/ws_sd15_t2i_basic.json": {
"mtime": 1779253098.1947012,
"seen": 1787279199.0012426,
"ast_hash": "cb1b5f84ac1b37af8715bf2ab0b38a51",
"semantic_hash": "cb1b5f84ac1b37af8715bf2ab0b38a51"
},
"workflows/ws_sdxl_2d_pose_editor_i2i.json": {
"mtime": 1779256158.4671156,
"seen": 1787279199.0012436,
"ast_hash": "cfe237775d6fb844ac726639e3ae928b",
"semantic_hash": "cfe237775d6fb844ac726639e3ae928b"
},
"workflows/ws_sdxl_3d pose editor_dwpose.json": {
"mtime": 1779255768.6302803,
"seen": 1787279199.0012448,
"ast_hash": "0e1955da91149ba6280d39db7a54db6f",
"semantic_hash": "0e1955da91149ba6280d39db7a54db6f"
},
"workflows/ws_sdxl_dwpose.json": {
"mtime": 1779255037.8698418,
"seen": 1787279199.0012455,
"ast_hash": "d670222d71df92e262ce8cb7299fd531",
"semantic_hash": "d670222d71df92e262ce8cb7299fd531"
},
"workflows/ws_sdxl_from_metadata_t2i.json": {
"mtime": 1779254360.9712114,
"seen": 1787279199.0012462,
"ast_hash": "463fca53dd0a4030555ff639661f2772",
"semantic_hash": "463fca53dd0a4030555ff639661f2772"
},
"workflows/ws_sdxl_i2i_facedetailer.json": {
"mtime": 1779253668.0067616,
"seen": 1787279199.0012474,
"ast_hash": "e2c677ee6670e37b466829c43ff9cd96",
"semantic_hash": "e2c677ee6670e37b466829c43ff9cd96"
},
"workflows/ws_sdxl_image_feeder_i2i.json": {
"mtime": 1779254714.0149894,
"seen": 1787279199.0012484,
"ast_hash": "8f14f2e0d1ebed40f95a8b728a5ecc79",
"semantic_hash": "8f14f2e0d1ebed40f95a8b728a5ecc79"
},
"workflows/ws_sdxl_t2i_basic.json": {
"mtime": 1779253180.3940487,
"seen": 1787279199.0012493,
"ast_hash": "beacbe857606b44d13aa2fc2f4872b76",
"semantic_hash": "beacbe857606b44d13aa2fc2f4872b76"
},
"workflows/ws_sdxl_t2i_facedetaller.json": {
"mtime": 1779253367.7975926,
"seen": 1787279199.00125,
"ast_hash": "0706c31d93f980b581e0e6eb376c0bcc",
"semantic_hash": "0706c31d93f980b581e0e6eb376c0bcc"
},
"DEVLOG.index.md": {
"mtime": 1787378424.0888915,
"seen": 1787399276.0029197,
"ast_hash": "f5e13974b9f8770e6f49bf74fc2c421e",
"semantic_hash": ""
},
"README.index.md": {
"mtime": 1787378423.9177885,
"seen": 1787399276.0029216,
"ast_hash": "4eaa4581c6f969c663176b216fde4596",
"semantic_hash": ""
},
"requirements.txt": {
"mtime": 1787036261.1817627,
"seen": 1787279199.0012598,
"ast_hash": "5942e1febf9611227a9145b3f9a91c6e",
"semantic_hash": "5942e1febf9611227a9145b3f9a91c6e"
},
"assets/banner.svg": {
"mtime": 1776081443.419675,
"seen": 1787279199.0012608,
"ast_hash": "059ec317eaba9e353d220d883477927a",
"semantic_hash": "059ec317eaba9e353d220d883477927a"
},
"assets/icon.svg": {
"mtime": 1776081443.4219253,
"seen": 1787279199.0012615,
"ast_hash": "9689aa0178236c19d5240250e08a303e",
"semantic_hash": "9689aa0178236c19d5240250e08a303e"
},
"docs/10_GenUI_Batch.png": {
"mtime": 1781057457.561953,
"seen": 1787279199.0012627,
"ast_hash": "351c1647aa5becfb4a2dbfa7da043b24",
"semantic_hash": "351c1647aa5becfb4a2dbfa7da043b24"
},
"docs/11_multiple_select_menu.png": {
"mtime": 1781057528.0140572,
"seen": 1787279199.0012636,
"ast_hash": "b3082324b8200a4eac8868f94ec4e6c7",
"semantic_hash": "b3082324b8200a4eac8868f94ec4e6c7"
},
"docs/12_Tagger.png": {
"mtime": 1782551031.7107866,
"seen": 1787279199.0012643,
"ast_hash": "42806369c4c08140c87daea348b6fc0f",
"semantic_hash": "42806369c4c08140c87daea348b6fc0f"
},
"docs/13_ImageEdit.png": {
"mtime": 1782550946.6263509,
"seen": 1787279199.0012655,
"ast_hash": "25a313806ba3c2396c9361b42599b063",
"semantic_hash": "25a313806ba3c2396c9361b42599b063"
},
"docs/1_workflowtab.png": {
"mtime": 1779078100.5980048,
"seen": 1787279199.0012662,
"ast_hash": "5aa53a79b8bd9e7b11a76f1ff89c9297",
"semantic_hash": "5aa53a79b8bd9e7b11a76f1ff89c9297"
},
"docs/2_modelstab.png": {
"mtime": 1779077971.8302422,
"seen": 1787279199.0012672,
"ast_hash": "2c89e877f01e8de3151e655f305df6aa",
"semantic_hash": "2c89e877f01e8de3151e655f305df6aa"
},
"docs/3_PromptInputAssistance.png": {
"mtime": 1779077804.0445502,
"seen": 1787279199.001268,
"ast_hash": "6634ec20d561648ce223807d2fb010cc",
"semantic_hash": "6634ec20d561648ce223807d2fb010cc"
},
"docs/4_GenUI_feeder.png": {
"mtime": 1779077729.1484556,
"seen": 1787279199.001269,
"ast_hash": "e6b3607b7c53a2f601aff487c278a3fb",
"semantic_hash": "e6b3607b7c53a2f601aff487c278a3fb"
},
"docs/5_topbar.png": {
"mtime": 1779076905.6012611,
"seen": 1787279199.0012698,
"ast_hash": "bafc74e7452f83ae9c585aa11f76f208",
"semantic_hash": "bafc74e7452f83ae9c585aa11f76f208"
},
"docs/6_ws_library.png": {
"mtime": 1781057870.2308166,
"seen": 1787279199.0012705,
"ast_hash": "6645a6c3d9ea09d75d34255c76cfc68b",
"semantic_hash": "6645a6c3d9ea09d75d34255c76cfc68b"
},
"docs/7_library_Infomation.png": {
"mtime": 1779076410.2629254,
"seen": 1787279199.0012715,
"ast_hash": "acb54f299c244fd41457f8fe4ccfc1d6",
"semantic_hash": "acb54f299c244fd41457f8fe4ccfc1d6"
},
"docs/8_Customize.png": {
"mtime": 1779077388.8494852,
"seen": 1787279199.0012722,
"ast_hash": "c9f979d40753ce41c015b2d594007658",
"semantic_hash": "c9f979d40753ce41c015b2d594007658"
},
"docs/9_GenUI_LoraStack.png": {
"mtime": 1781057821.3736062,
"seen": 1787279199.0012734,
"ast_hash": "e2b08e5f2059554d305563c63286bd74",
"semantic_hash": "e2b08e5f2059554d305563c63286bd74"
},
"docs/thumb.png": {
"mtime": 1778457744.7955222,
"seen": 1787279199.0012743,
"ast_hash": "92a0dcf2c3457777f2945f6df2dff017",
"semantic_hash": "92a0dcf2c3457777f2945f6df2dff017"
},
"static/favicon.svg": {
"mtime": 1773877378.0368707,
"seen": 1787279199.0012753,
"ast_hash": "0cd547c25c922d632890be287d6084ff",
"semantic_hash": "0cd547c25c922d632890be287d6084ff"
},
"workflows/ws_2d_pose_editor_to_Image_Edit( FireRed ).png": {
"mtime": 1779256606.562932,
"seen": 1787279199.0012763,
"ast_hash": "79b9d1e5e1303b523349b539d3dc1af3",
"semantic_hash": "79b9d1e5e1303b523349b539d3dc1af3"
},
"workflows/ws_3d_pose_editor_to_Image_Edit( Fire Red).png": {
"mtime": 1779257129.3453796,
"seen": 1787279199.001277,
"ast_hash": "02c572ab1c659d71dfd56e6b2b0334a5",
"semantic_hash": "02c572ab1c659d71dfd56e6b2b0334a5"
},
"workflows/ws_3d_pose_editor_to_Image_Edit( Flux2 Klein ).png": {
"mtime": 1779257864.2375357,
"seen": 1787279199.001278,
"ast_hash": "bb03ed86c7d4460a3568a4a8f90e5f40",
"semantic_hash": "bb03ed86c7d4460a3568a4a8f90e5f40"
},
"workflows/ws_dwpose_image_feeder.png": {
"mtime": 1779255324.1356418,
"seen": 1787279199.0012789,
"ast_hash": "e5db6889f59078e4ead6b89b8c07e91e",
"semantic_hash": "e5db6889f59078e4ead6b89b8c07e91e"
},
"workflows/ws_inpaint_basic.png": {
"mtime": 1784801838.7777002,
"seen": 1787279199.00128,
"ast_hash": "79321edb85aed7c0a8c777accc005486",
"semantic_hash": "79321edb85aed7c0a8c777accc005486"
},
"workflows/ws_inpaint_mask_editor_one.png": {
"mtime": 1784801946.027666,
"seen": 1787279199.001281,
"ast_hash": "bdd62facd6a8176c50e92264994dbbc2",
"semantic_hash": "bdd62facd6a8176c50e92264994dbbc2"
},
"workflows/ws_sd15_t2i_basic.png": {
"mtime": 1779253098.1897035,
"seen": 1787279199.0012817,
"ast_hash": "9582bb698439fff1a748315145538777",
"semantic_hash": "9582bb698439fff1a748315145538777"
},
"workflows/ws_sdxl_2d_pose_editor_i2i.png": {
"mtime": 1779256158.4621174,
"seen": 1787279199.001283,
"ast_hash": "bb7b9e26eae992abe62cd50299da9cb2",
"semantic_hash": "bb7b9e26eae992abe62cd50299da9cb2"
},
"workflows/ws_sdxl_3d pose editor_dwpose.png": {
"mtime": 1779255768.6191878,
"seen": 1787279199.0012836,
"ast_hash": "ac0fc8184ff7e42389fd0d562daa88c4",
"semantic_hash": "ac0fc8184ff7e42389fd0d562daa88c4"
},
"workflows/ws_sdxl_dwpose.png": {
"mtime": 1779255037.8606594,
"seen": 1787279199.0012846,
"ast_hash": "564f58d85a0b960154bd0a30ea111599",
"semantic_hash": "564f58d85a0b960154bd0a30ea111599"
},
"workflows/ws_sdxl_from_metadata_t2i.png": {
"mtime": 1779254360.9671092,
"seen": 1787279199.0012853,
"ast_hash": "98dfdb3ba374b0952c06995843f45171",
"semantic_hash": "98dfdb3ba374b0952c06995843f45171"
},
"workflows/ws_sdxl_i2i_facedetailer.png": {
"mtime": 1779253668.0007572,
"seen": 1787279199.0012865,
"ast_hash": "7285bb2a06aaf8dc7c5b37b84261be61",
"semantic_hash": "7285bb2a06aaf8dc7c5b37b84261be61"
},
"workflows/ws_sdxl_image_feeder_i2i.png": {
"mtime": 1779254714.0099926,
"seen": 1787279199.0012872,
"ast_hash": "13d4e7f87a87fd4c9a78427b38800cc6",
"semantic_hash": "13d4e7f87a87fd4c9a78427b38800cc6"
},
"workflows/ws_sdxl_t2i_basic.png": {
"mtime": 1779253180.3890488,
"seen": 1787279199.0012882,
"ast_hash": "9d8dda899602b8d74c6b23350e58a0d0",
"semantic_hash": "9d8dda899602b8d74c6b23350e58a0d0"
},
"workflows/ws_sdxl_t2i_facedetaller.png": {
"mtime": 1779253367.7925913,
"seen": 1787279199.0012891,
"ast_hash": "51cae742b39316023cf5332f1d794854",
"semantic_hash": "51cae742b39316023cf5332f1d794854"
},
".claude/hooks/on_doc_edit.py": {
"mtime": 1787279578.9362085,
"seen": 1787380810.2925577,
"ast_hash": "1a39a0e2ffaac441e8decccad0e1c42c",
"semantic_hash": "1a39a0e2ffaac441e8decccad0e1c42c"
},
"tools/generate_doc_index.py": {
"mtime": 1787279532.9148839,
"seen": 1787380810.3572273,
"ast_hash": "d0cdaf32b36fdef641a9396fd4ec403f",
"semantic_hash": "d0cdaf32b36fdef641a9396fd4ec403f"
},
".github/workflows/publish.yml": {
"mtime": 1778460176.5699222,
"seen": 1787380810.3754551,
"ast_hash": "a83dab23e8d09fdc8626689e96dfeb0e",
"semantic_hash": "a83dab23e8d09fdc8626689e96dfeb0e"
},
"templates/index.html": {
"mtime": 1787377487.6004047,
"seen": 1787380810.3754609,
"ast_hash": "639c4691eb3439d1707cd972bbed1402",
"semantic_hash": "639c4691eb3439d1707cd972bbed1402"
},
"static/js/prompt-table.js": {
"mtime": 1787400288.156035,
"seen": 1787400419.0870566,
"ast_hash": "bb722a8d63b1a7578f136bf99798f679",
"semantic_hash": ""
},
"static/js/prompt-ai-chat.js": {
"mtime": 1787398970.5236483,
"seen": 1787399276.0028632,
"ast_hash": "cdb87c58d22faa43d64b4f71a8d8e0f7",
"semantic_hash": ""
},
"static/js/prompt-presets.js": {
"mtime": 1787398926.1807213,
"seen": 1787399276.0028653,
"ast_hash": "7fd37f214f881138d21559c267241c5d",
"semantic_hash": ""
},
"static/js/prompt-styles.js": {
"mtime": 1787399033.0976152,
"seen": 1787399276.0028667,
"ast_hash": "800e1d042f6800d057b60801461d80aa",
"semantic_hash": ""
},
"static/js/prompt-wildcards.js": {
"mtime": 1787399711.3928645,
"seen": 1787399943.1509204,
"ast_hash": "0e1312911fa197ab5a1858fa449dfc69",
"semantic_hash": ""
}
}
+24
View File
@@ -0,0 +1,24 @@
"""Runs before ComfyUI imports any custom node — the only place early enough
to populate os.environ for code that reads env vars at import/request time.
Loads a .env file (if present) from this plugin's root directory so the
Unsloth backend's API key (UNSLOTH_API_KEY) can be set without editing
settings.json or exposing it to the frontend.
"""
from pathlib import Path
PLUGIN_DIR = Path(__file__).resolve().parent
ENV_FILE = PLUGIN_DIR / ".env"
if ENV_FILE.exists():
try:
from dotenv import load_dotenv
load_dotenv(ENV_FILE)
except ImportError:
print(
"[WARNING] Workflow Studio: .env file found but python-dotenv is not installed "
"(pip install -r requirements.txt). UNSLOTH_API_KEY will not be loaded from .env."
)
except Exception as e:
print(f"[WARNING] Workflow Studio: failed to load .env file: {e}")
+22 -4
View File
@@ -10,13 +10,22 @@ PLUGIN_DIR = Path(__file__).resolve().parent.parent
# Directory paths
TEMPLATES_DIR = PLUGIN_DIR / "templates"
STATIC_DIR = PLUGIN_DIR / "static"
DATA_DIR = PLUGIN_DIR / "data"
# Default workflows directory: ComfyUI's user/default/workflows
# PLUGIN_DIR is custom_nodes/ComfyUI-Workflow-Studio
# ComfyUI root is custom_nodes/../../ = two levels up
_COMFYUI_ROOT = PLUGIN_DIR.parent.parent
_COMFYUI_WORKFLOWS = _COMFYUI_ROOT / "user" / "default" / "workflows"
COMFYUI_ROOT = _COMFYUI_ROOT # exposed for external use
# Data directory: prefer ComfyUI's user/default/Workflow-Studio/, fallback to plugin data/
_COMFYUI_USER_DEFAULT = _COMFYUI_ROOT / "user" / "default"
if _COMFYUI_USER_DEFAULT.is_dir():
DATA_DIR = _COMFYUI_USER_DEFAULT / "Workflow-Studio"
logger.info("Workflow Studio: Using user data dir: %s", DATA_DIR)
else:
DATA_DIR = PLUGIN_DIR / "data"
logger.info("Workflow Studio: user/default not found, using plugin data dir: %s", DATA_DIR)
# Default workflows directory: ComfyUI's user/default/workflows
_COMFYUI_WORKFLOWS = _COMFYUI_USER_DEFAULT / "workflows"
# Use ComfyUI workflows dir if it exists, otherwise fallback to plugin data dir
if _COMFYUI_WORKFLOWS.is_dir():
@@ -59,3 +68,12 @@ NODE_METADATA_FILE = DATA_DIR / "node_metadata.json"
NODE_SETS_FILE = DATA_DIR / "node_sets.json"
PROMPTS_FILE = DATA_DIR / "prompts.json"
MODEL_METADATA_FILE = DATA_DIR / "model_metadata.json"
WILDCARD_DIR = DATA_DIR / "wildcard"
AI_SKILLS_DIR = DATA_DIR / "ai_skills"
LAB_PLAN_DIR = DATA_DIR / "lab_plan"
VIDEO_PLAN_DIR = DATA_DIR / "video_plan"
# Tagger
TAGGER_DB_FILE = DATA_DIR / "tagger.db"
TAGGER_SETTINGS_FILE = DATA_DIR / "tagger_settings.json"
TAGGER_MODELS_DIR = _COMFYUI_ROOT / "models" / "tagger"
+95
View File
@@ -0,0 +1,95 @@
"""WFS_GalleryFeeder – Feeds images from a gallery group into a workflow."""
import json
import random
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# Feeder専用グループ名(gallery_metadata.json 内で予約される)
FEEDER_GROUP = "__Feeder__"
class WFS_GalleryFeeder:
"""Gallery グループ内の画像をインデックス順に1枚ずつ出力するノード。"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"group_name": ("STRING", {"default": FEEDER_GROUP}),
"index": ("INT", {"default": 0, "min": 0, "max": 99999}),
"sort_mode": (["filename_asc", "filename_desc", "random"],),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "execute"
CATEGORY = "Workflow Studio"
OUTPUT_NODE = False
@classmethod
def IS_CHANGED(cls, **kwargs):
# 毎回実行させる(インデックスが変わるため)
return float("NaN")
def execute(self, group_name: str, index: int, sort_mode: str, seed: int):
import torch
import numpy as np
from PIL import Image as PILImage
paths = self._get_sorted_paths(group_name, sort_mode, seed)
if not paths:
logger.warning("WFS_GalleryFeeder: group '%s' is empty or not found", group_name)
return (torch.zeros(1, 64, 64, 3),)
img_path = paths[index % len(paths)]
try:
img = PILImage.open(img_path).convert("RGB")
except Exception as e:
logger.error("WFS_GalleryFeeder: failed to load '%s': %s", img_path, e)
return (torch.zeros(1, 64, 64, 3),)
arr = np.array(img, dtype=np.float32) / 255.0
tensor = torch.from_numpy(arr).unsqueeze(0)
return (tensor,)
# ── 内部ヘルパー ──────────────────────────────────────────────
def _get_sorted_paths(self, group_name: str, sort_mode: str, seed: int) -> list[str]:
metadata_file = self._find_metadata_file()
if not metadata_file.exists():
return []
try:
with open(metadata_file, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
logger.error("WFS_GalleryFeeder: metadata read error: %s", e)
return []
paths = [
key for key, meta in data.get("images", {}).items()
if group_name in meta.get("groups", []) and Path(key).exists()
]
if sort_mode == "filename_asc":
paths.sort(key=lambda p: Path(p).name.lower())
elif sort_mode == "filename_desc":
paths.sort(key=lambda p: Path(p).name.lower(), reverse=True)
elif sort_mode == "random":
rng = random.Random(seed)
rng.shuffle(paths)
return paths
@staticmethod
def _find_metadata_file() -> Path:
# py/nodes/ -> py/ -> plugin root -> ComfyUI/custom_nodes/ -> ComfyUI root
plugin_root = Path(__file__).resolve().parent.parent.parent
comfyui_root = plugin_root.parent.parent
user_default = comfyui_root / "user" / "default"
if user_default.is_dir():
return user_default / "Workflow-Studio" / "gallery_metadata.json"
return plugin_root / "data" / "gallery_metadata.json"
+103 -2
View File
@@ -3,6 +3,7 @@
import asyncio
import json
import logging
import os
import urllib.request
import urllib.error
@@ -17,6 +18,84 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/eagle/test", handle_test)
def _resolve_local_path(filename, subfolder, type_name):
"""filename/subfolder/type を ComfyUI 出力ディレクトリ上の実パスに解決する。
ComfyUI と Eagle が同一マシン上で動作している場合のみ有効なパスが返る
(別マシンの場合は None を返し、呼び出し側は addFromURL にフォールバックする)。"""
try:
import folder_paths # type: ignore
except Exception:
return None
base_dir = folder_paths.get_directory_by_type(type_name or "output")
if not base_dir:
return None
base_dir = os.path.abspath(base_dir)
filename = os.path.basename(filename or "")
if not filename:
return None
full_dir = os.path.abspath(os.path.join(base_dir, subfolder or ""))
# Windowsはパス比較で大文字小文字を区別しないため normcase で正規化してから比較する
if os.path.commonpath((os.path.normcase(full_dir), os.path.normcase(base_dir))) != os.path.normcase(base_dir):
# ディレクトリトラバーサル対策: base_dir 配下以外は拒否
return None
full_path = os.path.join(full_dir, filename)
if not os.path.isfile(full_path):
return None
return full_path
def _resolve_absolute_svg_path(abs_path):
"""comfyui-tosvg の Save SVG String ノードなどが返す絶対パスを検証する。
ComfyUI管理下(output/input/temp)ディレクトリ配下の実在する .svg ファイルのみ許可する
(任意の絶対パスをそのまま信頼すると、外部からこのAPIを叩かれた際に
ローカルの任意ファイルを送信させられてしまうため)。"""
if not abs_path or not abs_path.lower().endswith(".svg"):
return None
try:
import folder_paths # type: ignore
except Exception:
return None
abs_path = os.path.abspath(abs_path)
if not os.path.isfile(abs_path):
return None
for type_name in ("output", "temp", "input"):
base_dir = folder_paths.get_directory_by_type(type_name)
if not base_dir:
continue
base_dir = os.path.abspath(base_dir)
try:
# Windowsはパス比較で大文字小文字を区別しないため normcase で正規化してから比較する
if os.path.commonpath((os.path.normcase(abs_path), os.path.normcase(base_dir))) == os.path.normcase(base_dir):
return abs_path
except ValueError:
# Windowsで異なるドライブレターの場合 commonpath が例外を投げる
continue
return None
def _eagle_add_from_path(eagle_url, file_path, name, tags):
"""Proxy request to Eagle's addFromPath API (runs in thread).
SVG は ComfyUI の /view がセキュリティ上 application/octet-stream +
attachment で返すため、addFromURL 経由だと正しい種別で保存されないことがある。
ComfyUI と Eagle が同一マシン上にある場合はローカルパスを直接渡す方が確実。"""
eagle_url = eagle_url.rstrip("/")
payload = json.dumps({"path": file_path, "name": name, "tags": tags}).encode("utf-8")
req = urllib.request.Request(
f"{eagle_url}/api/item/addFromPath",
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
def _eagle_add(eagle_url, image_url, name, tags):
"""Proxy request to Eagle API (runs in thread)."""
eagle_url = eagle_url.rstrip("/")
@@ -71,11 +150,33 @@ async def handle_add(request: web.Request) -> web.Response:
image_url = body.get("url", "")
name = body.get("name", "image.png")
tags = body.get("tags", [])
filename = body.get("filename", "")
subfolder = body.get("subfolder", "")
file_type = body.get("type", "output")
local_path_hint = body.get("localPath", "")
if not image_url:
if not image_url and not local_path_hint:
return web.json_response({"status": "error", "message": "No URL provided"}, status=400)
result = await asyncio.to_thread(_eagle_add, eagle_url, image_url, name, tags)
# SVG は /view が application/octet-stream + attachment で返すため、
# ローカルファイルが解決できる場合は addFromPath で直接渡す
local_path = None
if local_path_hint:
# comfyui-tosvg の Save SVG String ノードなど、絶対パスが既知の場合
local_path = _resolve_absolute_svg_path(local_path_hint)
elif (filename or name or "").lower().endswith(".svg"):
local_path = _resolve_local_path(filename or name, subfolder, file_type)
if not local_path and not image_url:
return web.json_response(
{"status": "error", "message": f"Could not resolve local SVG path: {local_path_hint}"},
status=400,
)
if local_path:
result = await asyncio.to_thread(_eagle_add_from_path, eagle_url, local_path, name, tags)
else:
result = await asyncio.to_thread(_eagle_add, eagle_url, image_url, name, tags)
return web.json_response(result)
except urllib.error.URLError as e:
logger.error("Eagle URL error: %s", e)
+466 -5
View File
@@ -1,6 +1,7 @@
"""
Gallery Routes - ギャラリータブ用APIエンドポイント
"""
import asyncio
import json
import mimetypes
import logging
@@ -15,21 +16,82 @@ logger = logging.getLogger(__name__)
_service = GalleryService(DATA_DIR)
def _init_allowed_root() -> None:
"""起動時に保存済みの出力ディレクトリで _allowed_root を初期化する。
Gallery タブを開く前に Feeder タブの Gallery モードが serve_image を呼んでも
404 にならないようにするために必要。"""
try:
settings_file = DATA_DIR / "settings.json"
if settings_file.exists():
with open(settings_file, "r", encoding="utf-8") as f:
settings = json.load(f)
saved_root = settings.get("gallery_output_dir", "").strip()
if saved_root and Path(saved_root).is_dir():
_service.update_output_root(saved_root)
return
except Exception as e:
logger.warning("GalleryRoutes: failed to load saved gallery root: %s", e)
# フォールバック: ComfyUI のデフォルト output フォルダ
try:
import folder_paths # type: ignore
output_dir = folder_paths.get_output_directory()
if output_dir and Path(output_dir).is_dir():
_service.update_output_root(output_dir)
except Exception as e:
logger.warning("GalleryRoutes: failed to get ComfyUI output dir: %s", e)
# ImagePrompt/Style Catalogギャラリー用に実outputフォルダを常に別途保持する
# (Settingsで_allowed_rootが別フォルダに変更されていても影響しないようにするため)
try:
import folder_paths # type: ignore
output_dir = folder_paths.get_output_directory()
if output_dir and Path(output_dir).is_dir():
_service.set_comfy_output_root(output_dir)
except Exception as e:
logger.warning("GalleryRoutes: failed to get ComfyUI output dir for image-prompt root: %s", e)
_init_allowed_root()
def setup_routes(app: web.Application):
app.router.add_get("/wfm/gallery/folders", list_folders)
app.router.add_get("/wfm/gallery/images", list_images)
app.router.add_get("/wfm/gallery/image/meta", get_image_meta)
app.router.add_get("/wfm/gallery/image/workflow", get_image_workflow)
app.router.add_get("/wfm/gallery/image/serve", serve_image)
app.router.add_get("/wfm/gallery/image/thumb", serve_thumb)
app.router.add_post("/wfm/gallery/image/meta", save_image_meta)
app.router.add_get("/wfm/gallery/image-prompt/root", get_image_prompt_root)
app.router.add_post("/wfm/gallery/image/image-prompt", save_image_prompt)
app.router.add_get("/wfm/gallery/style-catalog/root", get_style_catalog_root)
app.router.add_post("/wfm/gallery/image/save", save_image_to_gallery)
app.router.add_post("/wfm/gallery/image/save-to-folder", save_image_to_folder_route)
app.router.add_post("/wfm/gallery/output-image/delete", delete_output_image)
app.router.add_post("/wfm/gallery/image/favorite", toggle_favorite)
app.router.add_get("/wfm/gallery/groups", list_groups)
app.router.add_post("/wfm/gallery/groups", create_group)
app.router.add_put("/wfm/gallery/groups/{name}", rename_group)
app.router.add_delete("/wfm/gallery/groups/{name}", delete_group)
app.router.add_post("/wfm/gallery/groups/ensure", ensure_group)
app.router.add_post("/wfm/gallery/groups/{name}/add", add_to_group)
app.router.add_post("/wfm/gallery/groups/{name}/remove", remove_from_group)
app.router.add_post("/wfm/gallery/groups/{name}/clear", clear_group_images)
app.router.add_get("/wfm/gallery/groups/{name}/images", list_group_images)
# バルク操作
app.router.add_post("/wfm/gallery/bulk/favorite", bulk_favorite)
app.router.add_post("/wfm/gallery/bulk/group", bulk_group)
# フォルダ・ファイル操作
app.router.add_post("/wfm/gallery/folder", create_folder_route)
app.router.add_delete("/wfm/gallery/folder", delete_folder_route)
app.router.add_post("/wfm/gallery/images/delete", delete_images_route)
app.router.add_post("/wfm/gallery/images/move", move_images_route)
app.router.add_post("/wfm/gallery/images/export-zip", export_images_zip)
app.router.add_post("/wfm/gallery/images/export-psd", export_images_psd)
app.router.add_post("/wfm/gallery/image/export-psd-layers", export_psd_from_layers)
app.router.add_post("/wfm/gallery/image/import-psd-layers", import_psd_layers)
app.router.add_get("/wfm/gallery/image/psd-layers", get_psd_layers)
# ──────────────────────────────────────────────────────────────
@@ -59,19 +121,25 @@ async def list_images(request: web.Request) -> web.Response:
favorite_only = request.rel_url.query.get("favorite", "false") == "true"
tag_filter = request.rel_url.query.get("tag", "")
group_filter = request.rel_url.query.get("group", "")
recursive = request.rel_url.query.get("recursive", "false") == "true"
if not folder:
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,
favorite_only=favorite_only,
tag_filter=tag_filter,
group_filter=group_filter,
recursive=recursive,
)
# 検索なしのフォルダロード時にバックグラウンドインデックスを起動
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)
@@ -99,9 +167,15 @@ async def get_image_workflow(request: web.Request) -> web.Response:
return web.json_response({"error": "path required"}, status=400)
try:
wf = _service.extract_workflow_from_metadata(path)
if wf is None:
return web.json_response({"workflow": None, "has_workflow": False})
return web.json_response({"workflow": wf, "has_workflow": True})
# prompt_workflow: プロンプト抽出専用(PNG[prompt]優先)。トップレベルとサブグラフに
# 独立した複数系統を持つワークフローではUI形式(workflow)からの抽出がトップレベル
# 系統しか拾えないことがあるため、Promptタブはこちらを使う(Metadataタブと揃える)。
prompt_wf = _service.extract_prompt_workflow_from_metadata(path)
return web.json_response({
"workflow": wf,
"has_workflow": wf is not None,
"prompt_workflow": prompt_wf,
})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
@@ -111,7 +185,10 @@ async def serve_image(request: web.Request) -> web.Response:
if not path:
return web.Response(status=400)
img_path = _service.serve_image(path)
# PSDの合成処理はCPU負荷が高く同期実行するとイベントループ全体をブロックする
# (他の並行リクエスト、例えば別画像のサムネイル配信も止まってしまう)ためexecutorで実行する
loop = asyncio.get_event_loop()
img_path = await loop.run_in_executor(None, _service.serve_image, path)
if img_path is None:
return web.Response(status=404)
@@ -122,6 +199,73 @@ async def serve_image(request: web.Request) -> web.Response:
})
async def serve_thumb(request: web.Request) -> web.Response:
"""サムネイル配信。Pillowで縮小したJPEGをディスクキャッシュして返す。"""
path = request.rel_url.query.get("path", "")
if not path:
return web.Response(status=400)
try:
width = int(request.rel_url.query.get("w", "256"))
width = max(32, min(512, width))
except ValueError:
width = 256
# PSD/MP4のサムネイル生成はCPU負荷が高く同期実行するとイベントループ全体をブロックするため
# executorで実行する(他画像のサムネイル配信が巻き添えで遅延・停止するのを防ぐ)
loop = asyncio.get_event_loop()
thumb_path = await loop.run_in_executor(None, _service.serve_thumbnail, path, width)
if thumb_path is None:
return web.Response(status=404)
ext = thumb_path.suffix.lower()
if ext in (".jpg", ".jpeg"):
content_type = "image/jpeg"
elif ext == ".gif":
content_type = "image/gif"
else:
content_type = mimetypes.guess_type(str(thumb_path))[0] or "image/jpeg"
return web.FileResponse(thumb_path, headers={
"Content-Type": content_type,
"Cache-Control": "max-age=86400",
})
# ──────────────────────────────────────────────────────────────
# バルク操作
# ──────────────────────────────────────────────────────────────
async def bulk_favorite(request: web.Request) -> web.Response:
"""POST /wfm/gallery/bulk/favorite — 複数画像のお気に入りを一括設定"""
try:
body = await request.json()
paths = body.get("paths", [])
value = bool(body.get("value", True))
if not paths:
return web.json_response({"error": "paths required"}, status=400)
result = _service.bulk_set_favorite(paths, value)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def bulk_group(request: web.Request) -> web.Response:
"""POST /wfm/gallery/bulk/group — 複数画像のグループ追加/削除を一括処理"""
try:
body = await request.json()
paths = body.get("paths", [])
group = body.get("group", "").strip()
action = body.get("action", "add") # "add" or "remove"
if not paths or not group:
return web.json_response({"error": "paths and group required"}, status=400)
if action not in ("add", "remove"):
return web.json_response({"error": "action must be 'add' or 'remove'"}, status=400)
result = _service.bulk_group_op(paths, group, action)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def save_image_meta(request: web.Request) -> web.Response:
try:
body = await request.json()
@@ -135,6 +279,36 @@ async def save_image_meta(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def get_image_prompt_root(request: web.Request) -> web.Response:
"""GET /wfm/gallery/image-prompt/root — ImagePromptギャラリーのルートフォルダを返す"""
root = _service.get_image_prompt_root()
if root is None:
return web.json_response({"error": "ComfyUI output directory not resolved"}, status=500)
return web.json_response({"root": root})
async def save_image_prompt(request: web.Request) -> web.Response:
"""POST /wfm/gallery/image/image-prompt — 画像の.txtサイドカーにプロンプトを保存"""
try:
body = await request.json()
img_path = body.get("path", "")
prompt = body.get("prompt", "")
if not img_path:
return web.json_response({"error": "path required"}, status=400)
ok = _service.save_image_prompt(img_path, prompt)
return web.json_response({"ok": ok})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def get_style_catalog_root(request: web.Request) -> web.Response:
"""GET /wfm/gallery/style-catalog/root — Style Catalogギャラリーのルートフォルダを返す"""
root = _service.get_style_catalog_root()
if root is None:
return web.json_response({"error": "ComfyUI output directory not resolved"}, status=500)
return web.json_response({"root": root})
async def toggle_favorite(request: web.Request) -> web.Response:
try:
body = await request.json()
@@ -147,6 +321,78 @@ async def toggle_favorite(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def save_image_to_gallery(request: web.Request) -> web.Response:
"""Image Edit Tab / AI Chat からの画像(PNG等)やSVGをギャラリーのルートフォルダに保存する。
imageData は data URL (data:<mime>;base64,<data>) を想定。ヘッダがなければPNG扱い(旧互換)。"""
try:
body = await request.json()
filename = body.get("filename", "").strip()
image_data = body.get("imageData", "")
if not filename or not image_data:
return web.json_response({"error": "filename and imageData required"}, status=400)
if _service._allowed_root is None:
return web.json_response({"error": "Gallery root not configured. Open Gallery tab and set output folder first."}, status=500)
result = _service.save_image_to_folder(str(_service._allowed_root), filename, image_data)
if not result["ok"]:
return web.json_response({"error": result["error"]}, status=400)
logger.info("save_image_to_gallery: saved %s", result["path"])
return web.json_response({"ok": True, "path": result["path"]})
except Exception as e:
logger.error("save_image_to_gallery error: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def save_image_to_folder_route(request: web.Request) -> web.Response:
"""POST /wfm/gallery/image/save-to-folder — 任意フォルダへ画像を保存(同名なら上書き)。
Style Catalogのカタログ作成で、スタイル名をファイル名として使う際に利用する。"""
try:
body = await request.json()
folder = body.get("folder", "").strip()
filename = body.get("filename", "").strip()
image_data = body.get("imageData", "")
if not folder or not filename or not image_data:
return web.json_response({"error": "folder, filename and imageData required"}, status=400)
result = _service.save_image_to_folder(folder, filename, image_data)
if not result["ok"]:
return web.json_response({"error": result["error"]}, status=400)
return web.json_response({"ok": True, "path": result["path"]})
except Exception as e:
logger.error("save_image_to_folder_route error: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def delete_output_image(request: web.Request) -> web.Response:
"""POST /wfm/gallery/output-image/delete — ComfyUI標準の画像参照(filename/subfolder/type)から
実ファイルを削除する。Style Catalogのカタログ作成で「Outputフォルダに画像を残さない」
オプションが有効な時、カタログへコピー保存した直後の元画像を消すために使う。
type="output" 以外は拒否する(temp/inputの誤削除を防止)。"""
try:
body = await request.json()
filename = (body.get("filename") or "").strip()
subfolder = body.get("subfolder") or ""
img_type = body.get("type") or ""
if not filename or img_type != "output":
return web.json_response({"error": "filename required and type must be 'output'"}, status=400)
import folder_paths # type: ignore
output_dir = Path(folder_paths.get_output_directory())
target = output_dir / subfolder / filename
result = await asyncio.to_thread(_service.delete_images, [str(target)])
if result["deleted"]:
return web.json_response({"ok": True})
return web.json_response({"error": "; ".join(result["errors"]) or "File not found"}, status=404)
except Exception as e:
logger.error("delete_output_image error: %s", e)
return web.json_response({"error": str(e)}, status=500)
# ──────────────────────────────────────────────────────────────
# グループ管理
# ──────────────────────────────────────────────────────────────
@@ -169,10 +415,15 @@ async def create_group(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
_RESERVED_GROUPS = {"__Feeder__", "__Video Assets__", "__Video Temp__"}
async def rename_group(request: web.Request) -> web.Response:
"""PUT /wfm/gallery/groups/{name} - グループ名変更"""
try:
old_name = request.match_info.get("name", "")
if old_name in _RESERVED_GROUPS:
return web.json_response({"error": f"Group '{old_name}' is reserved and cannot be renamed"}, status=403)
body = await request.json()
new_name = body.get("new_name", "").strip()
if not old_name or not new_name:
@@ -187,6 +438,8 @@ async def rename_group(request: web.Request) -> web.Response:
async def delete_group(request: web.Request) -> web.Response:
name = request.match_info.get("name", "")
if name in _RESERVED_GROUPS:
return web.json_response({"error": f"Group '{name}' is reserved and cannot be deleted"}, status=403)
ok = _service.delete_group(name)
return web.json_response({"ok": ok})
@@ -217,3 +470,211 @@ async def list_group_images(request: web.Request) -> web.Response:
name = request.match_info.get("name", "")
images = _service.list_images_in_group(name)
return web.json_response({"images": images})
async def clear_group_images(request: web.Request) -> web.Response:
"""POST /wfm/gallery/groups/{name}/clear - グループ内の全画像を除外"""
name = request.match_info.get("name", "")
if not name:
return web.json_response({"error": "name required"}, status=400)
ok = _service.clear_group(name)
return web.json_response({"ok": ok})
async def ensure_group(request: web.Request) -> web.Response:
"""POST /wfm/gallery/groups/ensure - グループが存在しない場合のみ作成"""
try:
body = await request.json()
name = body.get("name", "").strip()
if not name:
return web.json_response({"error": "name required"}, status=400)
_service.ensure_group(name)
return web.json_response({"ok": True})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
# ──────────────────────────────────────────────────────────────
# フォルダ・ファイル操作
# ──────────────────────────────────────────────────────────────
async def create_folder_route(request: web.Request) -> web.Response:
"""POST /wfm/gallery/folder - 新規フォルダ作成"""
try:
body = await request.json()
parent = body.get("parent", "")
name = body.get("name", "").strip()
if not parent or not name:
return web.json_response({"ok": False, "error": "parent and name required"}, status=400)
result = _service.create_folder(parent, name)
return web.json_response(result, status=200 if result["ok"] else 400)
except Exception as e:
return web.json_response({"ok": False, "error": str(e)}, status=500)
async def delete_folder_route(request: web.Request) -> web.Response:
"""DELETE /wfm/gallery/folder - フォルダ削除"""
try:
body = await request.json()
folder = body.get("path", "")
if not folder:
return web.json_response({"ok": False, "error": "path required"}, status=400)
result = _service.delete_folder(folder)
return web.json_response(result, status=200 if result["ok"] else 400)
except Exception as e:
return web.json_response({"ok": False, "error": str(e)}, status=500)
async def delete_images_route(request: web.Request) -> web.Response:
"""POST /wfm/gallery/images/delete - 画像削除(単体・複数)"""
try:
body = await request.json()
paths = body.get("paths", [])
if not paths:
return web.json_response({"deleted": [], "errors": ["paths required"]}, status=400)
result = _service.delete_images(paths)
return web.json_response(result)
except Exception as e:
return web.json_response({"deleted": [], "errors": [str(e)]}, status=500)
async def move_images_route(request: web.Request) -> web.Response:
"""POST /wfm/gallery/images/move - 画像移動(単体・複数)"""
try:
body = await request.json()
paths = body.get("paths", [])
dest = body.get("dest", "")
if not paths or not dest:
return web.json_response({"moved": [], "errors": ["paths and dest required"]}, status=400)
result = _service.move_images(paths, dest)
return web.json_response(result)
except Exception as e:
return web.json_response({"moved": [], "errors": [str(e)]}, status=500)
async def export_images_zip(request: web.Request) -> web.Response:
"""POST /wfm/gallery/images/export-zip - 複数画像をZIPファイルにしてダウンロード"""
import zipfile
import io
try:
body = await request.json()
paths = body.get("paths", [])
if not paths:
return web.json_response({"error": "paths required"}, status=400)
# ZIPファイルをメモリ上に作成
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
for path in paths:
file_path = Path(path)
# セキュリティ: 許可されたディレクトリ内のみ
if not _service._check_path_allowed(file_path):
continue
if file_path.exists() and file_path.is_file():
# ファイル名のみをアーカイブに入れる(パス情報は含めない)
zf.write(file_path, arcname=file_path.name)
zip_buffer.seek(0)
return web.Response(
body=zip_buffer.getvalue(),
content_type="application/zip",
headers={"Content-Disposition": "attachment; filename=gallery_export.zip"}
)
except Exception as e:
logger.error("Error exporting images to ZIP: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def export_images_psd(request: web.Request) -> web.Response:
"""POST /wfm/gallery/images/export-psd - 複数画像を1つのPSD(レイヤー分割)にしてダウンロード"""
try:
body = await request.json()
paths = body.get("paths", [])
if not paths:
return web.json_response({"error": "paths required"}, status=400)
psd_bytes = _service.build_psd_from_images(paths)
return web.Response(
body=psd_bytes,
content_type="image/vnd.adobe.photoshop",
headers={"Content-Disposition": "attachment; filename=gallery_export.psd"}
)
except RuntimeError as e:
logger.error("PSD export dependency missing: %s", e)
return web.json_response({"error": str(e)}, status=500)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error exporting images to PSD: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def export_psd_from_layers(request: web.Request) -> web.Response:
"""POST /wfm/gallery/image/export-psd-layers - Image Editタブのレイヤー配列を1つのPSDにしてダウンロード"""
try:
body = await request.json()
width = int(body.get("width", 0))
height = int(body.get("height", 0))
layers = body.get("layers", [])
if not layers:
return web.json_response({"error": "layers required"}, status=400)
psd_bytes = _service.build_psd_from_layers(width, height, layers)
return web.Response(
body=psd_bytes,
content_type="image/vnd.adobe.photoshop",
headers={"Content-Disposition": "attachment; filename=image_edit_export.psd"}
)
except RuntimeError as e:
logger.error("PSD export dependency missing: %s", e)
return web.json_response({"error": str(e)}, status=500)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error exporting Image Edit layers to PSD: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def import_psd_layers(request: web.Request) -> web.Response:
"""POST /wfm/gallery/image/import-psd-layers - アップロードされたPSDをレイヤー配列(JSON)に分解して返す"""
try:
reader = await request.multipart()
field = await reader.next()
if field is None:
return web.json_response({"error": "file required"}, status=400)
psd_bytes = await field.read(decode=False)
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, _service.import_psd_layers, psd_bytes)
return web.json_response(result)
except RuntimeError as e:
logger.error("PSD import dependency missing: %s", e)
return web.json_response({"error": str(e)}, status=500)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error importing PSD layers: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def get_psd_layers(request: web.Request) -> web.Response:
"""GET /wfm/gallery/image/psd-layers - サーバー上のPSDファイルをレイヤー配列(JSON)に分解して返す
(Galleryから直接Image Editへ送る際、アップロードの往復を挟まずに済ませるため)"""
path = request.rel_url.query.get("path", "")
if not path:
return web.json_response({"error": "path required"}, status=400)
try:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, _service.get_psd_layers_from_path, path)
return web.json_response(result)
except RuntimeError as e:
logger.error("PSD import dependency missing: %s", e)
return web.json_response({"error": str(e)}, status=500)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error reading PSD layers: %s", e)
return web.json_response({"error": str(e)}, status=500)
+183
View File
@@ -0,0 +1,183 @@
"""G'MIC-Qt integration API routes."""
import asyncio
import base64
import datetime
import json
import logging
import mimetypes
import os
import subprocess
import threading
import uuid
from pathlib import Path
from aiohttp import web
from ..services.settings_service import SettingsService
from ..config import DATA_DIR
logger = logging.getLogger(__name__)
_settings = SettingsService()
# Global job store
# key: job_id, value: dict {status, message, result_path, error}
_gmic_jobs = {}
_gmic_jobs_lock = threading.Lock()
def _gmic_run_gui(job_id: str, input_path: str, output_path: str, gmic_exe: str):
"""Run gmic_qt.exe in a background process/thread and wait for completion.
G'MIC-Qt Standalone argument order: -o <output> <input>
After OK the "filter output" window appears; closing it saves to output_path.
"""
args = [gmic_exe, "-o", output_path, input_path]
logger.info("[gmic] Launching: %s", " ".join(args))
try:
with _gmic_jobs_lock:
_gmic_jobs[job_id]["status"] = "processing"
_gmic_jobs[job_id]["message"] = "G'MIC GUIで編集中..."
import time
kwargs = {}
if os.name == "nt":
# Required on Windows to show the GUI window from a background process
kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE
proc = subprocess.Popen(args, **kwargs)
proc.wait()
time.sleep(0.5)
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
with _gmic_jobs_lock:
_gmic_jobs[job_id]["status"] = "completed"
_gmic_jobs[job_id]["result_path"] = output_path
_gmic_jobs[job_id]["message"] = "完了"
logger.info("[gmic] Result saved: %s", output_path)
else:
raise ValueError("G'MIC GUIがキャンセルされました")
except Exception as e:
with _gmic_jobs_lock:
_gmic_jobs[job_id]["status"] = "failed"
_gmic_jobs[job_id]["error"] = str(e)
_gmic_jobs[job_id]["message"] = f"エラー: {str(e)}"
logger.error("[gmic] Error: %s", e)
def setup_routes(app: web.Application):
"""Register G'MIC API routes."""
app.router.add_post("/api/wfm/gmic/open", handle_open)
app.router.add_get("/api/wfm/gmic/status/{job_id}", handle_status)
app.router.add_post("/api/wfm/gmic/result", handle_result)
async def handle_open(request: web.Request) -> web.Response:
"""POST /api/wfm/gmic/open - Open image in G'MIC GUI."""
try:
body = await request.json()
image_b64 = body.get("image_b64", "")
if not image_b64:
return web.json_response({"error": "image_b64 field is required"}, status=400)
# Retrieve setting for gmic path
data = _settings.load()
gmic_exe = data.get("gmic_qt_path", "")
if not os.path.exists(gmic_exe):
return web.json_response({
"error": f"G'MIC executable not found at: {gmic_exe}. Please configure the path in settings."
}, status=400)
ext = ".png"
if image_b64.startswith("data:"):
header, image_b64 = image_b64.split(",", 1)
mime = header.split(";")[0].split(":")[1]
guessed = mimetypes.guess_extension(mime)
if guessed:
ext = ".jpg" if guessed == ".jpe" else guessed
img_bytes = base64.b64decode(image_b64)
temp_dir = Path(DATA_DIR) / "gmic_temp"
temp_dir.mkdir(parents=True, exist_ok=True)
now_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
input_path = str(temp_dir / f"gmic_input_{now_str}{ext}")
output_path = str(temp_dir / f"gmic_output_{now_str}_{str(uuid.uuid4())[:8]}{ext}")
with open(input_path, "wb") as f:
f.write(img_bytes)
job_id = str(uuid.uuid4())
with _gmic_jobs_lock:
_gmic_jobs[job_id] = {
"status": "pending",
"message": "G'MIC GUIを起動中...",
"result_path": None,
"error": None,
}
# Start G'MIC thread
t = threading.Thread(
target=_gmic_run_gui,
args=(job_id, input_path, output_path, gmic_exe),
daemon=True,
)
t.start()
return web.json_response({"job_id": job_id, "status": "pending", "message": "起動中"})
except Exception as e:
logger.error("[gmic] open error: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_status(request: web.Request) -> web.Response:
"""GET /api/wfm/gmic/status/{job_id} - Check job status."""
try:
job_id = request.match_info.get("job_id", "")
with _gmic_jobs_lock:
job = _gmic_jobs.get(job_id)
if job is None:
return web.json_response({"error": "Job not found"}, status=404)
return web.json_response({
"job_id": job_id,
"status": job["status"],
"message": job.get("message", ""),
"result_path": job.get("result_path"),
"error": job.get("error"),
})
except Exception as e:
logger.error("[gmic] status error: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_result(request: web.Request) -> web.Response:
"""POST /api/wfm/gmic/result - Get result image base64."""
try:
body = await request.json()
result_path = body.get("result_path", "")
if not result_path or not os.path.exists(result_path):
return web.json_response({"error": f"Result file not found: {result_path}"}, status=404)
# Path traversal guard: only allow files inside gmic_temp
allowed_dir = (Path(DATA_DIR) / "gmic_temp").resolve()
try:
Path(result_path).resolve().relative_to(allowed_dir)
except ValueError:
return web.json_response({"error": "Access denied: path outside gmic_temp"}, status=403)
with open(result_path, "rb") as f:
img_bytes = f.read()
ext = os.path.splitext(result_path)[1].lower()
mime_map = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".bmp": "image/bmp",
".tiff": "image/tiff"
}
mime = mime_map.get(ext, "image/png")
b64 = base64.b64encode(img_bytes).decode("ascii")
return web.json_response({"image_b64": f"data:{mime};base64,{b64}"})
except Exception as e:
logger.error("[gmic] result error: %s", e)
return web.json_response({"error": str(e)}, status=500)
+85
View File
@@ -0,0 +1,85 @@
"""Lab tab plan file management API routes."""
import asyncio
import logging
from aiohttp import web
from ..config import LAB_PLAN_DIR
from ..services.lab_plan_service import LabPlanService
logger = logging.getLogger(__name__)
_service = LabPlanService(LAB_PLAN_DIR)
def setup_routes(app: web.Application):
app.router.add_get("/api/wfm/lab/plans", handle_list)
app.router.add_get("/api/wfm/lab/plans/content", handle_get_content)
app.router.add_post("/api/wfm/lab/plans/save", handle_save)
app.router.add_post("/api/wfm/lab/plans/delete", handle_delete)
app.router.add_post("/api/wfm/lab/index-image/save-to-output", handle_save_index_to_output)
async def handle_list(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_service.list_plans)
return web.json_response(result)
except Exception as e:
logger.error("Error listing lab plans: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_content(request: web.Request) -> web.Response:
filename = request.rel_url.query.get("filename", "")
try:
data = await asyncio.to_thread(_service.get_plan, filename)
return web.json_response({"data": data})
except FileNotFoundError:
return web.json_response({"error": "not found"}, status=404)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error getting lab plan content: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
data = body.get("data", {})
index_image_base64 = body.get("index_image_base64")
result = await asyncio.to_thread(_service.save_plan, filename, data, index_image_base64)
return web.json_response({"status": "ok", **result})
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error saving lab plan: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
await asyncio.to_thread(_service.delete_plan, filename)
return web.json_response({"status": "ok"})
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error deleting lab plan: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save_index_to_output(request: web.Request) -> web.Response:
try:
body = await request.json()
image_base64 = body.get("image_base64", "")
if not image_base64:
return web.json_response({"error": "image_base64 required"}, status=400)
result = await asyncio.to_thread(_service.save_index_image_to_output, image_base64)
return web.json_response({"status": "ok", **result})
except Exception as e:
logger.error("Error saving lab index image to output: %s", e)
return web.json_response({"error": str(e)}, status=500)
+258 -7
View File
@@ -27,6 +27,13 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/models/civitai/batch", handle_civitai_batch)
app.router.add_post("/api/wfm/models/change-preview", handle_change_preview)
app.router.add_get("/api/wfm/models/filepath", handle_get_filepath)
app.router.add_get("/api/wfm/models/disabled", handle_get_disabled)
app.router.add_post("/api/wfm/models/toggle", handle_toggle_model)
app.router.add_post("/api/wfm/models/group-toggle", handle_toggle_group)
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 ─────────────────────────────────────────
@@ -61,9 +68,10 @@ async def handle_save_metadata(request: web.Request) -> web.Response:
async def handle_get_groups(request: web.Request) -> web.Response:
"""GET /api/wfm/models/groups"""
"""GET /api/wfm/models/groups?type=checkpoint"""
model_type = request.query.get("type", "")
try:
result = await asyncio.to_thread(_service.get_model_groups)
result = await asyncio.to_thread(_service.get_model_groups, model_type or None)
return web.json_response(result)
except Exception as e:
logger.error("Error loading model groups: %s", e)
@@ -71,10 +79,17 @@ async def handle_get_groups(request: web.Request) -> web.Response:
async def handle_save_groups(request: web.Request) -> web.Response:
"""POST /api/wfm/models/groups"""
"""POST /api/wfm/models/groups
Body: { "model_type": "checkpoint", "groups": { "groupName": [...] } }
"""
try:
groups = await request.json()
result = await asyncio.to_thread(_service.save_model_groups, groups)
body = await request.json()
model_type = body.get("model_type", "")
groups = body.get("groups", {})
if not model_type:
return web.json_response({"error": "model_type required"}, status=400)
result = await asyncio.to_thread(_service.save_model_groups, groups, model_type)
return web.json_response({"status": "ok", "groups": result})
except Exception as e:
logger.error("Error saving model groups: %s", e)
@@ -138,10 +153,24 @@ async def handle_civitai_fetch(request: web.Request) -> web.Response:
"message": "Model not found on CivitAI"
})
# Auto-set preview if none exists and CivitAI has images
preview_saved = False
if info.get("images"):
has_preview = await asyncio.to_thread(_service.find_preview_image, model_type, model_name)
if not has_preview:
image_url = info["images"][0]
preview_path = file_path.parent / (file_path.stem + ".preview.png")
preview_saved = await asyncio.to_thread(
CivitaiService.download_image, image_url, preview_path
)
if preview_saved:
logger.info("Auto-saved preview for %s from CivitAI", model_name)
return web.json_response({
"status": "ok",
"sha256": sha256,
"civitai": info,
"preview_saved": preview_saved,
})
except Exception as e:
logger.error("CivitAI fetch error: %s", e)
@@ -257,6 +286,28 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
all_meta[mname]["sha256"] = sha
_service._save_metadata(all_meta)
# Auto-set previews for models without preview image
dirs = _get_model_dirs(model_type)
preview_saved_count = 0
for model_name, result in results.items():
civitai = result.get("civitai")
if not civitai or not civitai.get("images"):
continue
if _service.find_preview_image(model_type, model_name):
continue
model_file = None
for d in dirs:
p = d / model_name
if p.is_file():
model_file = p
break
if not model_file:
continue
preview_path = model_file.parent / (model_file.stem + ".preview.png")
if CivitaiService.download_image(civitai["images"][0], preview_path):
preview_saved_count += 1
logger.info("Auto-saved preview for %s from CivitAI", model_name)
# Send final result
summary = {
"total": len(model_files),
@@ -264,6 +315,7 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
"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")),
"hashes": {name: r.get("sha256") for name, r in results.items() if r.get("sha256")},
"preview_saved": preview_saved_count,
}
await response.write(send_sse("done", summary))
await response.write_eof()
@@ -295,7 +347,7 @@ async def handle_get_preview(request: web.Request) -> web.Response:
return web.FileResponse(
preview_path,
headers={"Content-Type": content_type or "image/png",
"Cache-Control": "public, max-age=3600"},
"Cache-Control": "no-cache"},
)
except Exception as e:
logger.error("Error serving model preview: %s", e)
@@ -334,7 +386,7 @@ async def handle_change_preview(request: web.Request) -> web.Response:
if image_data is None:
return web.json_response({"error": "file required"}, status=400)
# Resolve model file path
# Resolve model file path (also check .disabled variants)
from ..services.models_service import _get_model_dirs
dirs = _get_model_dirs(model_type)
model_path = None
@@ -343,6 +395,11 @@ async def handle_change_preview(request: web.Request) -> web.Response:
if candidate.is_file():
model_path = candidate
break
# disabled モデルも対象にする
disabled_candidate = d / (model_name + ".disabled")
if disabled_candidate.is_file():
model_path = disabled_candidate
break
if not model_path:
return web.json_response({"error": "Model file not found"}, status=404)
@@ -386,3 +443,197 @@ async def handle_get_filepath(request: web.Request) -> web.Response:
except Exception as e:
logger.error("Error resolving model filepath: %s", e)
return web.json_response({"error": str(e)}, status=500)
# ── Model Enable / Disable ────────────────────────────────
async def handle_get_disabled(request: web.Request) -> web.Response:
"""GET /api/wfm/models/disabled?type=checkpoint
Returns list of disabled model names (normalized, without .disabled suffix).
"""
model_type = request.query.get("type", "")
if not model_type:
return web.json_response({"error": "type required"}, status=400)
try:
result = await asyncio.to_thread(_service.scan_disabled_models, model_type)
return web.json_response(result)
except Exception as e:
logger.error("Error scanning disabled models: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_toggle_model(request: web.Request) -> web.Response:
"""POST /api/wfm/models/toggle
Body: { "model_type": "checkpoint", "model_name": "v1-5.safetensors", "enabled": false }
Renames the model file to add/remove .disabled suffix.
"""
try:
body = await request.json()
model_type = body.get("model_type", "")
model_name = body.get("model_name", "")
enabled = body.get("enabled", True)
if not model_type or not model_name:
return web.json_response({"error": "model_type and model_name required"}, status=400)
if ".." in model_name:
return web.json_response({"error": "Invalid model name"}, status=400)
if enabled:
await asyncio.to_thread(_service.enable_model, model_type, model_name)
else:
await asyncio.to_thread(_service.disable_model, model_type, model_name)
return web.json_response({"status": "ok", "enabled": enabled})
except FileNotFoundError as e:
return web.json_response({"error": str(e)}, status=404)
except OSError as e:
logger.error("OS error toggling model: %s", e)
return web.json_response({"error": str(e)}, status=500)
except Exception as e:
logger.error("Error toggling model: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_toggle_group(request: web.Request) -> web.Response:
"""POST /api/wfm/models/group-toggle
Body: { "model_type": "checkpoint", "group_name": "MyGroup", "enabled": true }
Enables or disables all models belonging to the specified group.
"""
try:
body = await request.json()
model_type = body.get("model_type", "")
group_name = body.get("group_name", "")
enabled = body.get("enabled", True)
if not model_type or not group_name:
return web.json_response({"error": "model_type and group_name required"}, status=400)
groups = await asyncio.to_thread(_service.get_model_groups, model_type)
members = groups.get(group_name, [])
ok_list = []
error_list = []
for model_name in members:
if ".." in model_name:
continue
try:
if enabled:
await asyncio.to_thread(_service.enable_model, model_type, model_name)
else:
await asyncio.to_thread(_service.disable_model, model_type, model_name)
ok_list.append(model_name)
except Exception as e:
error_list.append({"model": model_name, "error": str(e)})
return web.json_response({
"status": "ok",
"enabled": enabled,
"ok": ok_list,
"errors": error_list,
})
except Exception as e:
logger.error("Error toggling group: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete_models(request: web.Request) -> web.Response:
"""POST /api/wfm/models/delete
Body: { "model_type": "checkpoint", "model_names": ["a.safetensors", "b.safetensors"] }
Deletes each model file and associated preview/sidecar files, then removes metadata.
"""
try:
body = await request.json()
model_type = body.get("model_type", "")
model_names = body.get("model_names", [])
if not model_type or not isinstance(model_names, list) or not model_names:
return web.json_response({"error": "model_type and model_names[] required"}, status=400)
ok_list = []
error_list = []
for model_name in model_names:
if ".." in str(model_name):
error_list.append({"model": model_name, "error": "Invalid model name"})
continue
try:
result = await asyncio.to_thread(_service.delete_model, model_type, model_name)
ok_list.append({"model": model_name, "deleted": result["deleted"]})
logger.info("Deleted model: %s (%s files)", model_name, len(result["deleted"]))
except FileNotFoundError as e:
error_list.append({"model": model_name, "error": str(e)})
except Exception as e:
logger.error("Error deleting model %s: %s", model_name, e)
error_list.append({"model": model_name, "error": str(e)})
return web.json_response({"status": "ok", "ok": ok_list, "errors": error_list})
except Exception as e:
logger.error("Error in delete_models: %s", e)
return web.json_response({"error": str(e)}, status=500)
_VALID_MODEL_TYPES = frozenset(
["checkpoint", "lora", "vae", "controlnet", "unet", "textencoder", "hypernetwork", "embedding"]
)
async def handle_get_subdirs(request: web.Request) -> web.Response:
"""GET /api/wfm/models/subdirs?type=checkpoint
Returns list of root-level subdirectory names for the given model type.
"""
try:
model_type = request.rel_url.query.get("type", "")
if model_type not in _VALID_MODEL_TYPES:
return web.json_response({"error": "Invalid model type"}, status=400)
result = await asyncio.to_thread(_service.get_subdirs, model_type)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_move_models(request: web.Request) -> web.Response:
"""POST /api/wfm/models/move
Body: { "model_type": "checkpoint", "model_names": [...], "dest": "sdxl" }
dest: "" = root, or a root-level subfolder name (no path separators, no "..").
"""
try:
body = await request.json()
model_type = body.get("model_type", "")
model_names = body.get("model_names", [])
dest_subdir = body.get("dest", "")
if model_type not in _VALID_MODEL_TYPES:
return web.json_response({"error": "Invalid model type"}, status=400)
if not isinstance(model_names, list) or not model_names:
return web.json_response({"error": "model_names must be a non-empty list"}, status=400)
if not isinstance(dest_subdir, str):
return web.json_response({"error": "dest must be a string"}, status=400)
result = await asyncio.to_thread(_service.move_models, model_type, model_names, dest_subdir)
return web.json_response(result)
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)
+3 -2
View File
@@ -82,7 +82,8 @@ async def handle_chat(request: web.Request) -> web.Response:
try:
body = await request.json()
cfg = _get_ollama_config()
model = body.get("model", cfg["model"])
model = body.get("model") or cfg["model"]
base_url = (body.get("url") or cfg["url"]).rstrip("/")
messages = body.get("messages", [])
def _chat():
@@ -92,7 +93,7 @@ async def handle_chat(request: web.Request) -> web.Response:
"stream": False,
}).encode("utf-8")
url = f"{cfg['url']}/api/chat"
url = f"{base_url}/api/chat"
req = urllib.request.Request(
url,
data=payload,
+421 -1
View File
@@ -1,18 +1,35 @@
"""Settings API routes."""
import asyncio
import io
import json
import logging
import shutil
import zipfile
from pathlib import Path
from aiohttp import web
from ..services.settings_service import SettingsService
from ..config import DEFAULT_WORKFLOWS_DIR
from ..config import DEFAULT_WORKFLOWS_DIR, DATA_DIR
logger = logging.getLogger(__name__)
_service = SettingsService()
# Data files included in export/import
_DATA_FILES = [
"settings.json",
"metadata.json",
"node_metadata.json",
"node_sets.json",
"prompts.json",
"model_metadata.json",
"gallery_metadata.json",
"tagger_settings.json",
"civitai_cache.json",
]
def setup_routes(app: web.Application):
"""Register settings API routes."""
@@ -22,6 +39,14 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/settings/workflows-dir", handle_set_workflows_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)
app.router.add_post("/api/wfm/settings/import", handle_import)
app.router.add_get("/api/wfm/settings/export-full", handle_export_full)
app.router.add_post("/api/wfm/settings/import-full", handle_import_full)
app.router.add_get("/api/wfm/styles", handle_get_styles)
app.router.add_post("/api/wfm/styles", handle_create_style)
app.router.add_put("/api/wfm/styles/{name}", handle_update_style)
app.router.add_delete("/api/wfm/styles/{name}", handle_delete_style)
async def handle_get(request: web.Request) -> web.Response:
@@ -151,3 +176,398 @@ async def handle_set_output_dir(request: web.Request) -> web.Response:
except Exception as e:
logger.error("Error setting output dir: %s", e)
return web.json_response({"error": str(e)}, status=500)
def _load_data_file(filename: str):
"""Load a single data file, return empty dict/list if missing."""
path = DATA_DIR / filename
if not path.exists():
return None
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
# エクスポートから除外するsettings.jsonのキー(APIキーなどの機密情報)
_SETTINGS_EXPORT_EXCLUDE = {"civitai_api_key"}
def _build_export_bundle() -> dict:
"""Collect all data files into a single export bundle."""
bundle = {"__version": 1, "__source": "ComfyUI-Workflow-Studio"}
for filename in _DATA_FILES:
data = _load_data_file(filename)
if data is None:
continue
if filename == "settings.json" and isinstance(data, dict):
data = {k: v for k, v in data.items() if k not in _SETTINGS_EXPORT_EXCLUDE}
bundle[filename] = data
return bundle
async def handle_export(request: web.Request) -> web.Response:
"""GET /api/wfm/settings/export - Download all data as a single JSON bundle."""
try:
bundle = await asyncio.to_thread(_build_export_bundle)
body = json.dumps(bundle, ensure_ascii=False, indent=2)
return web.Response(
body=body.encode("utf-8"),
content_type="application/json",
headers={"Content-Disposition": 'attachment; filename="wfm-data-export.json"'},
)
except Exception as e:
logger.error("Error exporting data: %s", e)
return web.json_response({"error": str(e)}, status=500)
def _apply_import_bundle(bundle: dict) -> dict:
"""Write imported bundle back to individual data files. Returns summary."""
summary = {"imported": [], "skipped": []}
DATA_DIR.mkdir(parents=True, exist_ok=True)
for filename in _DATA_FILES:
if filename not in bundle:
summary["skipped"].append(filename)
continue
try:
path = DATA_DIR / filename
with open(path, "w", encoding="utf-8") as f:
json.dump(bundle[filename], f, ensure_ascii=False, indent=2)
summary["imported"].append(filename)
except Exception as e:
logger.error("Import failed for %s: %s", filename, e)
summary["skipped"].append(filename)
return summary
async def handle_import(request: web.Request) -> web.Response:
"""POST /api/wfm/settings/import - Upload and restore a JSON bundle."""
try:
bundle = await request.json()
if not isinstance(bundle, dict):
return web.json_response({"error": "Invalid bundle format"}, status=400)
summary = await asyncio.to_thread(_apply_import_bundle, bundle)
return web.json_response({"status": "ok", **summary})
except Exception as e:
logger.error("Error importing data: %s", e)
return web.json_response({"error": str(e)}, status=500)
# Full-backup (ZIP) export/import: unlike the flat _DATA_FILES JSON bundle above, this
# covers the whole DATA_DIR — directory-shaped data (ai_skills/, lab_plan/, video_plan/,
# style/) and the SQLite tagger.db that the JSON bundle can't represent. Excludes transient/cache
# dirs, and wildcard/ specifically because it's typically a symlink into a *different*
# custom_node's folder (comfyui-impact-pack) rather than this plugin's own data.
_FULL_BACKUP_EXCLUDE_NAMES = {"gmic_temp", "thumb_cache", "wildcard"}
def _add_file_to_zip(zf: zipfile.ZipFile, path: Path, base: Path):
rel = str(path.relative_to(base)).replace("\\", "/")
if path.name == "settings.json":
# Same API-key scrubbing as the JSON-bundle export — fall through to a raw
# copy if the file turns out to be unreadable/corrupt rather than skipping it.
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
data = {k: v for k, v in data.items() if k not in _SETTINGS_EXPORT_EXCLUDE}
zf.writestr(rel, json.dumps(data, ensure_ascii=False, indent=2))
return
except Exception:
pass
zf.write(path, rel)
# Two folders this plugin doesn't own but users often want backed up alongside their
# own data: ComfyUI's own default workflows dir, and the Impact Pack's wildcard
# library (a separate custom_node — the plugin's own wildcard/ is usually just a
# symlink into this same folder, see _FULL_BACKUP_EXCLUDE_NAMES above). Opt-in only
# (see handle_export_full's include_workflows/include_wildcard query params), and
# stored under an "_external/" prefix so _apply_full_backup_zip can recognize and
# skip them on restore — see that function's docstring for why.
def _default_workflows_dir() -> Path:
from ..config import COMFYUI_ROOT
return COMFYUI_ROOT / "user" / "default" / "workflows"
def _impact_pack_wildcard_dir() -> Path:
from ..config import COMFYUI_ROOT
return COMFYUI_ROOT / "custom_nodes" / "comfyui-impact-pack" / "wildcards"
def _add_external_dir_to_zip(zf: zipfile.ZipFile, src_dir: Path, zip_prefix: str):
if not src_dir.is_dir() or src_dir.is_symlink():
return
for path in src_dir.rglob("*"):
if path.is_dir() or path.is_symlink():
continue
rel = f"{zip_prefix}/{path.relative_to(src_dir)}".replace("\\", "/")
zf.write(path, rel)
def _build_full_backup_zip(include_workflows: bool = False, include_wildcard: bool = False) -> bytes:
"""Zips everything under DATA_DIR except the excluded names above. Walks
top-level entries first so an excluded symlinked directory (wildcard/) is never
even opened, rather than filtering after a recursive walk has already followed it.
Optionally also includes the two external folders above under "_external/"."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for top in sorted(DATA_DIR.iterdir()):
if top.name in _FULL_BACKUP_EXCLUDE_NAMES or top.is_symlink():
continue
if top.is_file():
_add_file_to_zip(zf, top, DATA_DIR)
elif top.is_dir():
for path in top.rglob("*"):
if path.is_dir() or path.is_symlink():
continue
_add_file_to_zip(zf, path, DATA_DIR)
if include_workflows:
_add_external_dir_to_zip(zf, _default_workflows_dir(), "_external/default_workflows")
if include_wildcard:
_add_external_dir_to_zip(zf, _impact_pack_wildcard_dir(), "_external/wildcard")
return buf.getvalue()
def _apply_full_backup_zip(zip_bytes: bytes) -> dict:
"""Extracts a full-backup ZIP into DATA_DIR, overwriting existing files. Guards
against Zip Slip (entries whose path resolves outside DATA_DIR via '..' or an
absolute path) by checking each entry before writing it.
Entries under "_external/" (default workflows dir, Impact Pack wildcards — see
_build_full_backup_zip) are always skipped here rather than restored: they live
outside DATA_DIR and are managed by ComfyUI core / a different custom_node, so
auto-restoring them could silently overwrite files this plugin doesn't own. They
stay in the ZIP for the user to copy back manually if they want them."""
summary = {"extracted": [], "skipped": []}
DATA_DIR.mkdir(parents=True, exist_ok=True)
base = DATA_DIR.resolve()
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
for info in zf.infolist():
if info.is_dir():
continue
if info.filename.startswith("_external/"):
summary["skipped"].append(info.filename)
continue
target = (base / info.filename).resolve()
try:
target.relative_to(base)
except ValueError:
summary["skipped"].append(info.filename)
continue
target.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info) as src, open(target, "wb") as dst:
shutil.copyfileobj(src, dst)
summary["extracted"].append(info.filename)
return summary
async def handle_export_full(request: web.Request) -> web.Response:
"""GET /api/wfm/settings/export-full - Download a ZIP of the entire data
directory, including data the flat JSON bundle (handle_export) can't represent.
Optional query params include_workflows=1 / include_wildcard=1 additionally bundle
ComfyUI's default workflows dir / the Impact Pack's wildcard dir (see
_build_full_backup_zip) — both restore-excluded, export-only, manual-copy-back."""
try:
include_workflows = request.rel_url.query.get("include_workflows") == "1"
include_wildcard = request.rel_url.query.get("include_wildcard") == "1"
zip_bytes = await asyncio.to_thread(_build_full_backup_zip, include_workflows, include_wildcard)
return web.Response(
body=zip_bytes,
content_type="application/zip",
headers={"Content-Disposition": 'attachment; filename="wfm-full-backup.zip"'},
)
except Exception as e:
logger.error("Error building full backup: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_import_full(request: web.Request) -> web.Response:
"""POST /api/wfm/settings/import-full - Upload and restore a full-backup ZIP."""
try:
reader = await request.multipart()
field = await reader.next()
if field is None or field.name != "file":
return web.json_response({"error": "file field required"}, status=400)
zip_bytes = await field.read(decode=False)
summary = await asyncio.to_thread(_apply_full_backup_zip, zip_bytes)
return web.json_response({"status": "ok", **summary})
except zipfile.BadZipFile:
return web.json_response({"error": "Not a valid ZIP file"}, status=400)
except Exception as e:
logger.error("Error importing full backup: %s", e)
return web.json_response({"error": str(e)}, status=500)
def _style_files() -> list:
style_dir = DATA_DIR / "style"
if not style_dir.is_dir():
return []
return sorted(style_dir.glob("*.json"))
def _load_styles() -> list:
"""Load all style JSON files from DATA_DIR/style/ directory.
各エントリに定義元ファイル名を "file" として付与する(Promptタブの一覧表示・
「このファイルへ追加」機能で使用)。"""
styles = []
for json_file in _style_files():
try:
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
for entry in data:
if isinstance(entry, dict):
entry = dict(entry)
entry["file"] = json_file.name
styles.append(entry)
except Exception as e:
logger.warning("Failed to load style file %s: %s", json_file.name, e)
return styles
async def handle_get_styles(request: web.Request) -> web.Response:
"""GET /api/wfm/styles - Get all styles from style directory."""
try:
styles = await asyncio.to_thread(_load_styles)
return web.json_response(styles)
except Exception as e:
logger.error("Error loading styles: %s", e)
return web.json_response({"error": str(e)}, status=500)
# Promptタブ「Style」サブタブでの新規作成分の保存先。既存スタイルの編集は
# 元々そのスタイルが記載されているファイルをそのまま書き換える(他ファイルへは移動しない)。
_CUSTOM_STYLE_FILENAME = "custom.json"
def _find_style(name: str):
"""名前が一致する最初のスタイルを探し、(ファイルパス, そのファイルの全データ, インデックス) を返す。
見つからなければ None。"""
for json_file in _style_files():
try:
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
logger.warning("Failed to load style file %s: %s", json_file.name, e)
continue
if not isinstance(data, list):
continue
for i, entry in enumerate(data):
if isinstance(entry, dict) and entry.get("name") == name:
return json_file, data, i
return None
def _write_style_file(path: Path, data: list) -> None:
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
async def handle_create_style(request: web.Request) -> web.Response:
"""POST /api/wfm/styles - 新規スタイルを作成する。
body.file を指定すると既存のそのファイルへ追記する(Promptタブの「このファイルへ追加」用、
ファイル名はstyleディレクトリに実在するもののみ許可しパストラバーサルを防ぐ)。
未指定ならデフォルトのcustom.jsonへ追記する。"""
try:
body = await request.json()
name = (body.get("name") or "").strip()
prompt = body.get("prompt", "") or ""
negative_prompt = body.get("negative_prompt", "") or ""
target_file = (body.get("file") or "").strip()
if not name:
return web.json_response({"error": "name is required"}, status=400)
def _create():
if _find_style(name) is not None:
return "duplicate"
style_dir = DATA_DIR / "style"
style_dir.mkdir(parents=True, exist_ok=True)
if target_file:
path = next((f for f in _style_files() if f.name == target_file), None)
if path is None:
return "file_not_found"
else:
path = style_dir / _CUSTOM_STYLE_FILENAME
data = []
if path.is_file():
try:
with open(path, "r", encoding="utf-8") as f:
loaded = json.load(f)
if isinstance(loaded, list):
data = loaded
except Exception as e:
logger.warning("Failed to load %s, recreating: %s", path.name, e)
data.append({"name": name, "prompt": prompt, "negative_prompt": negative_prompt})
_write_style_file(path, data)
return "ok"
result = await asyncio.to_thread(_create)
if result == "duplicate":
return web.json_response({"error": f'Style "{name}" already exists'}, status=400)
if result == "file_not_found":
return web.json_response({"error": f'File "{target_file}" not found'}, status=400)
return web.json_response({"ok": True})
except Exception as e:
logger.error("Error creating style: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_update_style(request: web.Request) -> web.Response:
"""PUT /api/wfm/styles/{name} - 既存スタイルを更新する(記載元のファイルをそのまま書き換え、リネームも可)。"""
try:
original_name = request.match_info.get("name", "")
body = await request.json()
new_name = (body.get("name") or "").strip()
prompt = body.get("prompt", "") or ""
negative_prompt = body.get("negative_prompt", "") or ""
if not new_name:
return web.json_response({"error": "name is required"}, status=400)
def _update():
found = _find_style(original_name)
if found is None:
return "not_found"
path, data, idx = found
if new_name != original_name and _find_style(new_name) is not None:
return "duplicate"
data[idx] = {"name": new_name, "prompt": prompt, "negative_prompt": negative_prompt}
_write_style_file(path, data)
return "ok"
result = await asyncio.to_thread(_update)
if result == "not_found":
return web.json_response({"error": "Style not found"}, status=404)
if result == "duplicate":
return web.json_response({"error": f'Style "{new_name}" already exists'}, status=400)
return web.json_response({"ok": True})
except Exception as e:
logger.error("Error updating style: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete_style(request: web.Request) -> web.Response:
"""DELETE /api/wfm/styles/{name} - スタイルを削除する(記載元のファイルから該当エントリのみ除去)。"""
try:
name = request.match_info.get("name", "")
def _delete():
found = _find_style(name)
if found is None:
return False
path, data, idx = found
del data[idx]
_write_style_file(path, data)
return True
ok = await asyncio.to_thread(_delete)
if not ok:
return web.json_response({"error": "Style not found"}, status=404)
return web.json_response({"ok": True})
except Exception as e:
logger.error("Error deleting style: %s", e)
return web.json_response({"error": str(e)}, status=500)
+64
View File
@@ -0,0 +1,64 @@
"""AI skill (.md system prompt) file management API routes."""
import asyncio
import logging
from aiohttp import web
from ..config import AI_SKILLS_DIR
from ..services.skill_service import SkillService
logger = logging.getLogger(__name__)
_service = SkillService(AI_SKILLS_DIR)
def setup_routes(app: web.Application):
app.router.add_get("/api/wfm/skills", handle_list)
app.router.add_get("/api/wfm/skills/content", handle_get_content)
app.router.add_post("/api/wfm/skills/save", handle_save)
app.router.add_post("/api/wfm/skills/delete", handle_delete)
async def handle_list(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_service.list_skills)
return web.json_response(result)
except Exception as e:
logger.error("Error listing skills: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_content(request: web.Request) -> web.Response:
filename = request.rel_url.query.get("filename", "")
try:
content = await asyncio.to_thread(_service.get_content, filename)
return web.json_response({"content": content})
except FileNotFoundError:
return web.json_response({"error": "not found"}, status=404)
except Exception as e:
logger.error("Error getting skill content: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
content = body.get("content", "")
result = await asyncio.to_thread(_service.save_file, filename, content)
return web.json_response({"status": "ok", "file": result})
except Exception as e:
logger.error("Error saving skill: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
await asyncio.to_thread(_service.delete_file, filename)
return web.json_response({"status": "ok"})
except Exception as e:
logger.error("Error deleting skill: %s", e)
return web.json_response({"error": str(e)}, status=500)
+243
View File
@@ -0,0 +1,243 @@
"""Tagger API routes."""
import asyncio
import logging
from aiohttp import web
from ..config import TAGGER_DB_FILE, TAGGER_MODELS_DIR, TAGGER_SETTINGS_FILE
from ..services.tagger_db_service import TaggerDbService
from ..services.tagger_service import TaggerService
logger = logging.getLogger(__name__)
_svc = TaggerService(TAGGER_MODELS_DIR, TAGGER_SETTINGS_FILE)
_db = TaggerDbService(TAGGER_DB_FILE)
def setup_routes(app: web.Application):
app.router.add_get("/wfm/tagger/models", handle_models)
app.router.add_post("/wfm/tagger/predict", handle_predict)
app.router.add_get("/wfm/tagger/vlm/models", handle_vlm_models)
app.router.add_post("/wfm/tagger/vlm/predict", handle_vlm_predict)
app.router.add_post("/wfm/tagger/batch/start", handle_batch_start)
app.router.add_get("/wfm/tagger/batch/status", handle_batch_status)
app.router.add_post("/wfm/tagger/batch/stop", handle_batch_stop)
app.router.add_get("/wfm/tagger/db/list", handle_db_list)
app.router.add_get("/wfm/tagger/db/search", handle_db_search)
app.router.add_put("/wfm/tagger/db/{id}", handle_db_update)
app.router.add_delete("/wfm/tagger/db/{id}", handle_db_delete)
app.router.add_delete("/wfm/tagger/db", handle_db_delete_bulk)
app.router.add_get("/wfm/tagger/db/export", handle_db_export)
app.router.add_post("/wfm/tagger/db/save", handle_db_save)
app.router.add_post("/wfm/tagger/write_meta", handle_write_meta)
app.router.add_get("/wfm/tagger/settings", handle_settings_get)
app.router.add_post("/wfm/tagger/settings", handle_settings_save)
async def handle_models(request: web.Request) -> web.Response:
try:
models = await asyncio.to_thread(_svc.list_models)
return web.json_response({"models": models})
except Exception as e:
logger.error("handle_models: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_predict(request: web.Request) -> web.Response:
try:
body = await request.json()
b64 = body.get("image_b64", "")
model = body.get("model", "")
if not b64 or not model:
return web.json_response({"error": "image_b64 and model required"}, status=400)
result = await asyncio.to_thread(
_svc.predict, b64, model,
float(body.get("threshold", 0.35)),
float(body.get("char_threshold", 0.85)),
)
return web.json_response(result)
except Exception as e:
logger.error("handle_predict: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_vlm_models(request: web.Request) -> web.Response:
backend = request.rel_url.query.get("backend", "ollama")
api_url = request.rel_url.query.get("api_url", "http://127.0.0.1:11434")
try:
models = await asyncio.to_thread(_svc.vlm_models, backend, api_url)
return web.json_response({"models": models})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_vlm_predict(request: web.Request) -> web.Response:
try:
body = await request.json()
result = await asyncio.to_thread(
_svc.vlm_predict,
body.get("image_b64", ""),
body.get("backend", "ollama"),
body.get("api_url", "http://127.0.0.1:11434"),
body.get("model", ""),
body.get("prompt", ""),
int(body.get("max_tags", 40)),
bool(body.get("thinking_mode", False)),
int(body.get("max_tokens", 0)),
)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_batch_start(request: web.Request) -> web.Response:
try:
body = await request.json()
result = await asyncio.to_thread(
_svc.batch_start,
body.get("folder", ""),
body.get("model", ""),
float(body.get("threshold", 0.35)),
float(body.get("char_threshold", 0.85)),
bool(body.get("use_ollama", False)),
body.get("vlm_backend", "ollama"),
body.get("vlm_api_url", "http://127.0.0.1:11434"),
body.get("ollama_model", ""),
body.get("ollama_prompt", ""),
int(body.get("ollama_max_tags", 40)),
bool(body.get("save_db", True)),
bool(body.get("write_file", False)),
bool(body.get("write_txt", False)),
_db,
bool(body.get("thinking_mode", False)),
int(body.get("max_tokens", 0)),
)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_batch_status(request: web.Request) -> web.Response:
return web.json_response(_svc.batch_status())
async def handle_batch_stop(request: web.Request) -> web.Response:
_svc.batch_stop()
return web.json_response({"ok": True})
async def handle_db_list(request: web.Request) -> web.Response:
try:
limit = int(request.rel_url.query.get("limit", 100))
offset = int(request.rel_url.query.get("offset", 0))
rows = await asyncio.to_thread(_db.list, limit, offset)
total = await asyncio.to_thread(_db.total)
return web.json_response({"rows": rows, "total": total})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_search(request: web.Request) -> web.Response:
try:
q = request.rel_url.query.get("q", "")
rows = await asyncio.to_thread(_db.search, q)
return web.json_response({"rows": rows})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_update(request: web.Request) -> web.Response:
try:
row_id = int(request.match_info["id"])
body = await request.json()
await asyncio.to_thread(
_db.update, row_id,
body.get("interrogator_tags", ""),
body.get("vlm_tags", ""),
)
return web.json_response({"ok": True})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_delete(request: web.Request) -> web.Response:
try:
row_id = int(request.match_info["id"])
await asyncio.to_thread(_db.delete, row_id)
return web.json_response({"ok": True})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_delete_bulk(request: web.Request) -> web.Response:
try:
data = await request.json()
ids = data.get("ids", [])
if not ids:
return web.json_response(
{"error": "No IDs specified"},
status=400,
)
ids = [int(row_id) for row_id in ids]
deleted_count = await asyncio.to_thread(_db.delete_bulk, ids)
return web.json_response({
"ok": True,
"count": deleted_count,
})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_export(request: web.Request) -> web.Response:
try:
csv_data = await asyncio.to_thread(_db.export_csv)
return web.Response(
body=csv_data.encode("utf-8"),
content_type="text/csv",
headers={"Content-Disposition": "attachment; filename=tagger_tags.csv"},
)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_db_save(request: web.Request) -> web.Response:
try:
body = await request.json()
row_id = await asyncio.to_thread(
_db.save,
body.get("filename", ""),
body.get("interrogator_tags", ""),
body.get("vlm_tags", ""),
)
return web.json_response({"ok": True, "id": row_id})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_write_meta(request: web.Request) -> web.Response:
try:
body = await request.json()
result = await asyncio.to_thread(
_svc.write_meta_to_file,
body.get("path", ""),
body.get("tags", ""),
)
return web.json_response(result)
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
async def handle_settings_get(request: web.Request) -> web.Response:
return web.json_response(_svc.load_settings())
async def handle_settings_save(request: web.Request) -> web.Response:
try:
body = await request.json()
await asyncio.to_thread(_svc.save_settings, body)
return web.json_response({"ok": True})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
+99
View File
@@ -0,0 +1,99 @@
"""Unsloth API proxy routes.
Unlike Ollama/LM Studio/Lemonade, Unsloth Desktop requires an API key even
for local access (Authorization: Bearer sk-unsloth-...). The key lives in
UNSLOTH_API_KEY (loaded from a .env file by prestartup_script.py) and is
never sent to the frontend — the frontend calls this proxy with the target
path/method/payload, and the server attaches the Authorization header before
relaying to Unsloth's OpenAI-compatible API.
"""
import json
import logging
import os
import urllib.request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from aiohttp import web
logger = logging.getLogger(__name__)
UNSLOTH_DEFAULT_URL = "http://localhost:8888"
_ALLOWED_PATHS = {"/v1/models", "/v1/chat/completions"}
# 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"}
def _get_api_key():
"""Return the Unsloth API key from the environment (.env), or None."""
return os.environ.get("UNSLOTH_API_KEY", "").strip() or None
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)
async def handle_proxy(request: web.Request) -> web.Response:
"""POST /api/wfm/unsloth/proxy - Relay a request to Unsloth's OpenAI-compatible API.
Body: { baseUrl, path: "/v1/models" | "/v1/chat/completions", method: "GET" | "POST", payload }
"""
import asyncio
try:
body = await request.json()
base_url = (body.get("baseUrl") or UNSLOTH_DEFAULT_URL).rstrip("/")
path = body.get("path") or "/v1/models"
method = (body.get("method") or "GET").upper()
payload = body.get("payload")
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)
api_key = _get_api_key()
if not api_key:
return web.json_response({
"message": "UNSLOTH_API_KEY is not set. Copy .env.example to .env in the "
"plugin folder, fill in the key, and restart ComfyUI.",
}, status=401)
def _fetch():
data = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {"Authorization": f"Bearer {api_key}"}
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:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
return web.json_response(data)
except HTTPError as e:
detail = e.read().decode("utf-8", errors="replace") if e.fp else str(e)
logger.warning("Unsloth proxy HTTP error: %s %s", e.code, detail)
return web.json_response({"message": f"Unsloth API error: HTTP {e.code}"}, status=e.code)
except URLError as e:
logger.warning("Unsloth proxy connection error: %s", e)
return web.json_response({"message": f"Could not reach Unsloth: {e.reason}"}, status=502)
except Exception as e:
logger.error("Unsloth proxy error: %s", e)
return web.json_response({"message": str(e)}, status=500)
+133
View File
@@ -0,0 +1,133 @@
"""Video tab API routes: last-frame capture, animated GIF conversion, and
Plan (batch timeline) file management."""
import asyncio
import logging
from aiohttp import web
from ..config import VIDEO_PLAN_DIR
from ..services.video_service import VideoService
from ..services.video_plan_service import VideoPlanService
logger = logging.getLogger(__name__)
_service = VideoService()
_plan_service = VideoPlanService(VIDEO_PLAN_DIR)
def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/video/frame/save-to-output", handle_save_frame)
app.router.add_post("/api/wfm/video/to-gif", handle_to_gif)
app.router.add_get("/api/wfm/video/plans", handle_list_plans)
app.router.add_get("/api/wfm/video/plans/content", handle_get_plan_content)
app.router.add_post("/api/wfm/video/plans/save", handle_save_plan)
app.router.add_post("/api/wfm/video/plans/delete", handle_delete_plan)
app.router.add_post("/api/wfm/video/index-image/save-to-output", handle_save_index_to_output)
async def handle_save_frame(request: web.Request) -> web.Response:
try:
body = await request.json()
image_base64 = body.get("image_base64", "")
if not image_base64:
return web.json_response({"error": "image_base64 required"}, status=400)
result = await asyncio.to_thread(_service.save_frame_to_output, image_base64)
return web.json_response({"status": "ok", **result})
except Exception as e:
logger.error("Error saving video frame to output: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_to_gif(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
subfolder = body.get("subfolder", "")
type_ = body.get("type", "output")
start_time = float(body.get("start_time") or 0)
end_time_raw = body.get("end_time")
end_time = float(end_time_raw) if end_time_raw not in (None, "") else None
fps = float(body.get("fps") or 10)
max_width_raw = body.get("max_width")
max_width = int(max_width_raw) if max_width_raw not in (None, "") else None
if not filename:
return web.json_response({"error": "filename required"}, status=400)
result = await asyncio.to_thread(
_service.convert_to_gif, filename, subfolder, type_, start_time, end_time, fps, max_width
)
return web.json_response({"status": "ok", **result})
except FileNotFoundError as e:
return web.json_response({"error": str(e)}, status=404)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error converting video to GIF: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_list_plans(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_plan_service.list_plans)
return web.json_response(result)
except Exception as e:
logger.error("Error listing video plans: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_plan_content(request: web.Request) -> web.Response:
filename = request.rel_url.query.get("filename", "")
try:
data = await asyncio.to_thread(_plan_service.get_plan, filename)
return web.json_response({"data": data})
except FileNotFoundError:
return web.json_response({"error": "not found"}, status=404)
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error getting video plan content: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save_plan(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
data = body.get("data", {})
index_image_base64 = body.get("index_image_base64")
result = await asyncio.to_thread(_plan_service.save_plan, filename, data, index_image_base64)
return web.json_response({"status": "ok", **result})
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error saving video plan: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete_plan(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
await asyncio.to_thread(_plan_service.delete_plan, filename)
return web.json_response({"status": "ok"})
except ValueError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error deleting video plan: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save_index_to_output(request: web.Request) -> web.Response:
try:
body = await request.json()
image_base64 = body.get("image_base64", "")
if not image_base64:
return web.json_response({"error": "image_base64 required"}, status=400)
result = await asyncio.to_thread(_plan_service.save_index_image_to_output, image_base64)
return web.json_response({"status": "ok", **result})
except Exception as e:
logger.error("Error saving video index image to output: %s", e)
return web.json_response({"error": str(e)}, status=500)
+98
View File
@@ -0,0 +1,98 @@
"""Wildcard file management API routes."""
import asyncio
import logging
from aiohttp import web
from ..config import DATA_DIR, COMFYUI_ROOT
from ..services.wildcard_service import WildcardService
logger = logging.getLogger(__name__)
_service = WildcardService(DATA_DIR / "wildcard")
def setup_routes(app: web.Application):
app.router.add_get("/api/wfm/wildcards", handle_list)
app.router.add_get("/api/wfm/wildcards/content", handle_get_content)
app.router.add_post("/api/wfm/wildcards/save", handle_save)
app.router.add_post("/api/wfm/wildcards/delete", handle_delete)
app.router.add_get("/api/wfm/wildcards/link-status", handle_link_status)
app.router.add_post("/api/wfm/wildcards/create-link", handle_create_link)
app.router.add_post("/api/wfm/wildcards/remove-link", handle_remove_link)
async def handle_list(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_service.list_wildcards)
return web.json_response(result)
except Exception as e:
logger.error("Error listing wildcards: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_content(request: web.Request) -> web.Response:
filename = request.rel_url.query.get("filename", "")
try:
content = await asyncio.to_thread(_service.get_content, filename)
return web.json_response({"content": content})
except FileNotFoundError:
return web.json_response({"error": "not found"}, status=404)
except Exception as e:
logger.error("Error getting wildcard content: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_save(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
content = body.get("content", "")
result = await asyncio.to_thread(_service.save_file, filename, content)
return web.json_response({"status": "ok", "file": result})
except Exception as e:
logger.error("Error saving wildcard: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_delete(request: web.Request) -> web.Response:
try:
body = await request.json()
filename = body.get("filename", "")
await asyncio.to_thread(_service.delete_file, filename)
return web.json_response({"status": "ok"})
except Exception as e:
logger.error("Error deleting wildcard: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_link_status(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_service.get_link_status, COMFYUI_ROOT)
return web.json_response(result)
except Exception as e:
logger.error("Error getting wildcard link status: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_create_link(request: web.Request) -> web.Response:
try:
result = await asyncio.to_thread(_service.create_link, COMFYUI_ROOT)
return web.json_response({"status": "ok", **result})
except RuntimeError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error creating wildcard link: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_remove_link(request: web.Request) -> web.Response:
try:
await asyncio.to_thread(_service.remove_link)
return web.json_response({"status": "ok"})
except RuntimeError as e:
return web.json_response({"error": str(e)}, status=400)
except Exception as e:
logger.error("Error removing wildcard link: %s", e)
return web.json_response({"error": str(e)}, status=500)
+289 -65
View File
@@ -3,6 +3,8 @@
import hashlib
import json
import logging
import ssl
import time
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
@@ -11,9 +13,48 @@ from ..config import DATA_DIR
logger = logging.getLogger(__name__)
def _make_ssl_context():
"""Return an SSL context with CA verification.
1. certifi CA bundle (available in virtually all ComfyUI envs via torch→requests→certifi)
2. System default SSL context (OS certificate store)
Returns None if both fail — callers fall back to urlopen without context
(Python's own default, which also uses certifi when available).
SSL verification is never disabled to avoid MitM exposure.
"""
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception:
pass
try:
return ssl.create_default_context()
except Exception:
pass
logger.warning("CivitAI: could not build SSL context; falling back to urllib default")
return None
_SSL_CONTEXT = _make_ssl_context # lazy sentinel
def _get_ssl_context():
global _SSL_CONTEXT
if callable(_SSL_CONTEXT):
_SSL_CONTEXT = _make_ssl_context()
return _SSL_CONTEXT
CIVITAI_API_BASE = "https://civitai.com/api/v1"
CIVITAI_CACHE_FILE = DATA_DIR / "civitai_cache.json"
# HTTPステータスコード: 指数バックオフでリトライする対象
_RETRY_CODES = {429, 500, 502, 503, 504}
_MAX_RETRIES = 3
# POST /model-versions/by-hash は最大100件まで一括送信可能
_BATCH_CHUNK_SIZE = 100
class CivitaiService:
"""Fetch and cache CivitAI model metadata."""
@@ -21,6 +62,8 @@ class CivitaiService:
def __init__(self):
self._cache = None
# ── キャッシュ管理 ────────────────────────────────────────
def _load_cache(self):
if self._cache is not None:
return self._cache
@@ -42,12 +85,37 @@ class CivitaiService:
def get_cached(self, sha256_hash):
"""Return cached CivitAI data for a given hash, or None."""
cache = self._load_cache()
return cache.get(sha256_hash)
return cache.get(sha256_hash.lower())
def get_all_cached(self):
"""Return the full cache dict."""
return self._load_cache()
# ── APIキー / ヘッダー ────────────────────────────────────
@staticmethod
def _get_api_key():
"""Return CivitAI API key. Env var CIVITAI_API_KEY takes priority over settings.json."""
import os
env_key = os.environ.get("CIVITAI_API_KEY", "").strip()
if env_key:
return env_key
try:
from ..services.settings_service import SettingsService
return SettingsService().load().get("civitai_api_key", "").strip() or None
except Exception:
return None
def _build_headers(self):
"""Build request headers, optionally including Bearer token."""
headers = {"User-Agent": "ComfyUI-Workflow-Studio/1.0"}
api_key = self._get_api_key()
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
return headers
# ── ハッシュ計算 ──────────────────────────────────────────
@staticmethod
def calculate_sha256(file_path, chunk_size=65536):
"""Calculate SHA256 hash of a file."""
@@ -61,43 +129,130 @@ class CivitaiService:
if not chunk:
break
h.update(chunk)
return h.hexdigest()
return h.hexdigest() # 小文字16進数
# ── 単体フェッチ (GET) ────────────────────────────────────
def fetch_by_hash(self, sha256_hash):
"""Fetch model version info from CivitAI by SHA256 hash.
"""Fetch model version info from CivitAI by SHA256 hash (GET).
429/5xx は指数バックオフでリトライ。
Returns dict with model info, or None if not found.
Caches successful results.
"""
# Check cache first
sha256_lower = sha256_hash.lower()
cache = self._load_cache()
if sha256_hash in cache:
return cache[sha256_hash]
if sha256_lower in cache:
return cache[sha256_lower]
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash}"
try:
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=15) as resp:
data = json.loads(resp.read().decode("utf-8"))
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash.upper()}"
if not data or "id" not in data:
for attempt in range(_MAX_RETRIES):
try:
req = Request(url, headers=self._build_headers())
with urlopen(req, timeout=15, context=_get_ssl_context()) as resp:
data = json.loads(resp.read().decode("utf-8"))
if not data or "id" not in data:
return None
info = self._extract_info(data)
cache[sha256_lower] = info
self._save_cache()
return info
except HTTPError as e:
if e.code == 404:
logger.debug("CivitAI: model not found for hash %s", sha256_hash[:16])
return None
if e.code in _RETRY_CODES and attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI %s: retrying in %ss (attempt %d/%d)",
e.code, wait, attempt + 1, _MAX_RETRIES)
time.sleep(wait)
continue
logger.warning("CivitAI API error: %s %s", e.code, e.reason)
return None
except (URLError, Exception) as e:
if attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI request failed: %s — retrying in %ss", e, wait)
time.sleep(wait)
continue
logger.warning("CivitAI request failed: %s", e)
return None
# Extract useful fields
info = self._extract_info(data)
cache[sha256_hash] = info
self._save_cache()
return info
return None
except HTTPError as e:
if e.code == 404:
logger.debug("CivitAI: model not found for hash %s", sha256_hash[:16])
return None
logger.warning("CivitAI API error: %s %s", e.code, e.reason)
return None
except (URLError, Exception) as e:
logger.warning("CivitAI request failed: %s", e)
return None
# ── 一括フェッチ (POST) ───────────────────────────────────
def _batch_fetch_post(self, sha256_hashes):
"""POST /model-versions/by-hash でハッシュリストを一括取得(最大100件/リクエスト)。
レスポンスの files[].hashes.SHA256 でリクエストのハッシュと照合する。
Returns: { sha256_lower: info_or_none }
"""
if not sha256_hashes:
return {}
url = f"{CIVITAI_API_BASE}/model-versions/by-hash"
results = {h.lower(): None for h in sha256_hashes}
cache = self._load_cache()
for chunk_start in range(0, len(sha256_hashes), _BATCH_CHUNK_SIZE):
chunk = sha256_hashes[chunk_start:chunk_start + _BATCH_CHUNK_SIZE]
chunk_lower = {h.lower() for h in chunk}
for attempt in range(_MAX_RETRIES):
try:
body = json.dumps([h.upper() for h in chunk]).encode("utf-8")
req = Request(
url,
data=body,
headers={**self._build_headers(), "Content-Type": "application/json"},
method="POST",
)
with urlopen(req, timeout=30, context=_get_ssl_context()) as resp:
versions = json.loads(resp.read().decode("utf-8"))
# 各バージョンを files[].hashes.SHA256 でリクエストのハッシュと照合
for version_data in versions:
info = self._extract_info(version_data)
matched = False
for f in version_data.get("files", []):
file_sha256 = f.get("hashes", {}).get("SHA256", "").lower()
if file_sha256 in chunk_lower:
cache[file_sha256] = info
results[file_sha256] = info
matched = True
break
if not matched:
# files にハッシュがない場合は versionId で照合を試みる
logger.debug("CivitAI: could not match version %s to a requested hash",
version_data.get("id"))
break # チャンク成功
except HTTPError as e:
if e.code in _RETRY_CODES and attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI batch POST %s: retrying in %ss", e.code, wait)
time.sleep(wait)
continue
logger.warning("CivitAI batch POST error: %s %s", e.code, e.reason)
break
except (URLError, Exception) as e:
if attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI batch POST failed: %s — retrying in %ss", e, wait)
time.sleep(wait)
continue
logger.warning("CivitAI batch POST failed: %s", e)
break
self._save_cache()
return results
# ── 情報抽出 ──────────────────────────────────────────────
@staticmethod
def _extract_info(data):
@@ -106,101 +261,170 @@ class CivitaiService:
images = data.get("images", [])
files = data.get("files", [])
# Get primary file info
primary_file = None
for f in files:
if f.get("primary"):
primary_file = f
break
# プライマリファイルを特定
primary_file = next((f for f in files if f.get("primary")), None)
if not primary_file and files:
primary_file = files[0]
# Get image URLs (first 5)
image_urls = []
# 画像情報(URL・寸法・NSFWレベル)を最大5件取得
image_list = []
for img in images[:5]:
url = img.get("url", "")
if url:
# Optimize for thumbnail
optimized = url.replace("/original=true", "/width=450,optimized=true")
image_urls.append(optimized)
img_url = img.get("url", "")
if not img_url:
continue
image_list.append({
"url": img_url,
"width": img.get("width"),
"height": img.get("height"),
"nsfwLevel": img.get("nsfwLevel", 0),
})
# プライマリファイルのメタ情報(精度・フォーマット)
file_meta = {}
file_hashes = {}
if primary_file:
pm = primary_file.get("metadata", {})
file_meta = {
"fp": pm.get("fp"),
"size": pm.get("size"),
"format": pm.get("format"),
}
# BLAKE3, SHA256, AutoV2 等のハッシュ
file_hashes = primary_file.get("hashes", {})
stats = data.get("stats", {})
# バッチ POST API は model オブジェクト内に id を含まない場合がある
# トップレベルの modelId をフォールバックとして使用する
model_id = model.get("id") or data.get("modelId")
version_id = data.get("id", "")
return {
"versionId": data.get("id"),
"modelId": model.get("id"),
"versionId": version_id,
"modelId": model_id,
"modelName": model.get("name", ""),
"versionName": data.get("name", ""),
"type": model.get("type", ""),
"description": data.get("description") or model.get("description", ""),
"tags": model.get("tags", []),
"nsfw": model.get("nsfw", False),
"nsfwLevel": data.get("nsfwLevel", 0),
"air": data.get("air", ""),
"creator": data.get("creator", {}).get("username", ""),
"images": image_urls,
# 後方互換のため URLリストを維持しつつ詳細情報も保存
"images": [img["url"] for img in image_list],
"imageDetails": image_list,
"trainedWords": data.get("trainedWords", []),
"baseModel": data.get("baseModel", ""),
"fileSize": primary_file.get("sizeKB", 0) if primary_file else 0,
"fileMeta": file_meta,
"fileHashes": file_hashes,
"downloadUrl": data.get("downloadUrl", ""),
"modelUrl": f"https://civitai.com/models/{model.get('id', '')}?modelVersionId={data.get('id', '')}",
"modelUrl": (
f"https://civitai.com/models/{model_id}?modelVersionId={version_id}"
if model_id else (
f"https://civitai.com/model-versions/{version_id}"
if version_id else ""
)
),
"stats": {
"downloadCount": stats.get("downloadCount", 0),
"thumbsUpCount": stats.get("thumbsUpCount", 0),
"thumbsDownCount": stats.get("thumbsDownCount", 0),
},
"updatedAt": data.get("updatedAt", ""),
"publishedAt": data.get("publishedAt", ""),
}
# ── バッチフェッチ ────────────────────────────────────────
def batch_fetch(self, model_files, progress_callback=None):
"""Batch fetch CivitAI info for multiple model files.
Phase 1: SHA256 計算("hashing")
Phase 2: POST で一括取得("fetching")— キャッシュ済みはスキップ
Args:
model_files: list of (model_name, file_path) tuples
progress_callback: fn(current, total, model_name, status) called per model
Returns: dict of { model_name: { sha256, civitai_info_or_none } }
"""
import time
results = {}
total = len(model_files)
cache = self._load_cache()
# Phase 1: ハッシュ計算
hashes_needed = [] # [(model_name, sha256_lower, original_index)]
for i, (model_name, file_path) in enumerate(model_files):
if progress_callback:
progress_callback(i, total, model_name, "hashing")
# Calculate hash
sha256 = self.calculate_sha256(file_path)
if not sha256:
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
continue
results[model_name] = {"sha256": sha256, "civitai": None}
# Check cache
if sha256 in cache:
results[model_name]["civitai"] = cache[sha256]
if progress_callback:
progress_callback(i, total, model_name, "cached")
progress_callback(i + 1, total, model_name, "not_found")
continue
# Fetch from API
sha256_lower = sha256.lower()
results[model_name] = {"sha256": sha256_lower, "civitai": None}
if sha256_lower in cache:
results[model_name]["civitai"] = cache[sha256_lower]
if progress_callback:
progress_callback(i + 1, total, model_name, "cached")
else:
hashes_needed.append((model_name, sha256_lower, i))
# Phase 2: POST で一括取得(未キャッシュ分)
if hashes_needed:
if progress_callback:
progress_callback(i, total, model_name, "fetching")
progress_callback(len(results), total, "", "fetching")
info = self.fetch_by_hash(sha256)
if info:
results[model_name]["civitai"] = info
# 同一ハッシュが複数モデルに対応する場合を考慮
sha256_to_entries: dict[str, list] = {}
for name, sha256_lower, idx in hashes_needed:
sha256_to_entries.setdefault(sha256_lower, []).append((name, idx))
if progress_callback:
status = "found" if info else "not_found"
progress_callback(i, total, model_name, status)
batch_results = self._batch_fetch_post(list(sha256_to_entries.keys()))
# Rate limit: small delay between API calls
time.sleep(0.5)
for sha256_lower, info in batch_results.items():
for name, idx in sha256_to_entries.get(sha256_lower, []):
results[name]["civitai"] = info
if progress_callback:
status = "found" if info else "not_found"
progress_callback(idx + 1, total, name, status)
if progress_callback:
progress_callback(total, total, "", "done")
return results
# ── 画像ダウンロード ──────────────────────────────────────
@staticmethod
def download_image(url, save_path, timeout=15):
"""Download an image from URL and save to save_path. Returns True on success."""
try:
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 open(save_path, "wb") as f:
f.write(data)
return True
except Exception as e:
logger.warning("Failed to download preview from %s: %s", url, e)
return False
# ── キャッシュ操作 ────────────────────────────────────────
def clear_cache(self, sha256_hash=None):
"""Clear cache for a specific hash or all."""
cache = self._load_cache()
if sha256_hash:
cache.pop(sha256_hash, None)
cache.pop(sha256_hash.lower(), None)
else:
cache.clear()
self._save_cache()
+218 -54
View File
@@ -1,8 +1,10 @@
"""
Gallery Metadata Store - ギャラリー画像のメタデータ永続化
"""
import copy
import json
import logging
import threading
from pathlib import Path
logger = logging.getLogger(__name__)
@@ -24,14 +26,27 @@ class GalleryMetadataStore:
{"name": str}
]
}
self._data(特に "images" 辞書)は、バックグラウンドのフォルダインデックススレッド
(gallery_service.pyの_bg_index_folder)と、リクエストハンドラを処理するメインスレッドの
双方から並行に読み書きされる。ロックなしで辞書を反復(.items()/.values()/for key in ...や
json.dumpによるシリアライズ)している最中に別スレッドがキーを追加/削除すると
"dictionary changed size during iteration" が発生するため、_data へアクセスする
全メソッドを self._lock で保護する(re-entrant: ensure_group()がcreate_group()を
内部呼び出しするため、通常のLockではなくRLockを使う)。
"""
def __init__(self, file_path: Path):
self.file_path = file_path
self._lock = threading.RLock()
# ディスクへの実書き込み(JSONシリアライズ+ファイルI/O)を直列化するための
# 別ロック。_save_to_disk() を参照。
self._write_lock = threading.Lock()
self._data: dict = {"images": {}, "groups": []}
self._load()
def _load(self):
# コンストラクタからのみ呼ばれ、この時点ではまだ他スレッドと共有されていないためロック不要
if self.file_path.exists():
try:
with open(self.file_path, "r", encoding="utf-8") as f:
@@ -42,84 +57,233 @@ class GalleryMetadataStore:
}
except Exception as e:
logger.warning("GalleryMetadataStore: load error: %s", e)
# 破損ファイルをリネームしてバックアップしておく。ここでリネームせずに
# 空の self._data のまま次の save() が走ると、破損直前までの全メタデータ
# (タグ/メモ/グループ登録)が跡形もなく上書きされ、二度と復元できなくなる
# (実際に発生した不具合: _save_to_disk が非アトミック書き込みだったため、
# 大量画像フォルダのBGインデックス処理中の頻繁な保存とComfyUIの終了タイミング
# が重なるとファイルが不完全な状態のまま残ることがあった — _save_to_disk側は
# os.replace()によるアトミック書き込みに修正済みだが、過去に壊れたファイルや
# 他要因による破損に備えてここでも保護しておく)。
try:
backup_path = self.file_path.with_name(self.file_path.name + ".corrupt")
self.file_path.replace(backup_path)
logger.warning("GalleryMetadataStore: corrupt file backed up to %s", backup_path)
except Exception as backup_err:
logger.warning("GalleryMetadataStore: failed to back up corrupt file: %s", backup_err)
def _save_to_disk(self):
try:
self.file_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(self._data, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error("GalleryMetadataStore: save error: %s", e)
return False
# 呼び出し元(save/create_group等)が既にself._lockを保持している前提の内部メソッド。
# ここではself._lock配下でスナップショット(deepcopy)を取るだけに留め、実際のJSON
# シリアライズ+ファイルI/Oはロックの外、別途self._write_lockで直列化して行う。
# 理由: gallery_metadata.jsonは画像数が多い環境では1MBを超えることがあり、
# self._lockを保持したままjson.dump+ファイル書き込みまで行うと、その間
# 他スレッドのget()(検索リクエストなど)が丸ごとブロックされてしまう
# (実際に発生した不具合: バックグラウンドインデックス処理が10枚ごとに保存する際、
# 検索リクエストのget()呼び出しがロック待ちになり、50枚程度のフォルダに対する
# 検索でも数秒〜十数秒かかっていた)。deepcopy自体はメモリ内操作でファイルI/Oより
# 大幅に軽いため、ロック内に残しても実用上のブロック時間は無視できるレベルになる。
snapshot = copy.deepcopy(self._data)
return self._write_snapshot(snapshot)
def _write_snapshot(self, snapshot: dict) -> bool:
"""self._lockの外から呼ばれる。一時ファイルに書き出してから置き換える
(os.replace相当のPath.replace)ことで書き込みをアトミックにする。素朴な
open(path, "w") での直接上書きだと、書き込み完了前に他プロセスが読むと
不完全なJSONを掴む(torn read)うえ、書き込み中にComfyUIプロセスが終了すると
ファイルが壊れたまま残る — 大量画像フォルダのBGインデックス処理で書き込み
頻度が高い環境ほど発生しやすく、次回起動時のロード失敗→空データでの全上書き
という形でユーザーの登録済みグループ/タグ/メモが消失する原因になっていた。
self._write_lockで直列化し、複数スレッドの書き込みが競合して古いスナップショット
が新しいものを上書きしないようにする。"""
with self._write_lock:
try:
self.file_path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = self.file_path.with_name(self.file_path.name + ".tmp")
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(snapshot, f, ensure_ascii=False, indent=2)
tmp_path.replace(self.file_path)
return True
except Exception as e:
logger.error("GalleryMetadataStore: save error: %s", e)
return False
def _normalize_path(self, image_path: str) -> str:
return str(Path(image_path)).replace("\\", "/")
def get(self, image_path: str) -> dict:
key = self._normalize_path(image_path)
return dict(self._data["images"].get(key, {}))
with self._lock:
return dict(self._data["images"].get(key, {}))
def save(self, image_path: str, data: dict) -> bool:
key = self._normalize_path(image_path)
existing = self._data["images"].get(key, {})
existing.update(data)
allowed = {"favorite", "tags", "memo", "groups"}
existing = {k: v for k, v in existing.items() if k in allowed}
self._data["images"][key] = existing
return self._save_to_disk()
with self._lock:
existing = self._data["images"].get(key, {})
existing.update(data)
allowed = {"favorite", "tags", "memo", "groups", "workflow"}
existing = {k: v for k, v in existing.items() if k in allowed}
self._data["images"][key] = existing
return self._save_to_disk()
def save_batch(self, entries: dict[str, dict]) -> bool:
"""複数画像のメタデータを1回のディスク書き込みでまとめて保存する。
バックグラウンドインデックス処理のように多数の画像を連続して保存する場合、
1件ずつsave()を呼ぶと画像の数だけJSONシリアライズ+ファイルI/Oが発生してしまう
(実際に発生した不具合: gallery_metadata.jsonが1MBを超える環境で10枚ごとに
個別save()していたため、検索リクエストが完了するまで数秒〜十数秒かかっていた)。"""
if not entries:
return True
allowed = {"favorite", "tags", "memo", "groups", "workflow"}
with self._lock:
for image_path, data in entries.items():
key = self._normalize_path(image_path)
existing = self._data["images"].get(key, {})
existing.update(data)
existing = {k: v for k, v in existing.items() if k in allowed}
self._data["images"][key] = existing
return self._save_to_disk()
# ── グループ管理 ──────────────────────────────────────────────
def list_groups(self) -> list[dict]:
return list(self._data.get("groups", []))
with self._lock:
return list(self._data.get("groups", []))
def create_group(self, name: str) -> bool:
groups = self._data.get("groups", [])
if any(g["name"] == name for g in groups):
return False
groups.append({"name": name})
self._data["groups"] = groups
return self._save_to_disk()
with self._lock:
groups = self._data.get("groups", [])
if any(g["name"] == name for g in groups):
return False
groups.append({"name": name})
self._data["groups"] = groups
return self._save_to_disk()
def rename_group(self, old_name: str, new_name: str) -> bool:
"""グループ名を変更し、全画像のgroupsフィールドも更新する"""
groups = self._data.get("groups", [])
if not any(g["name"] == old_name for g in groups):
return False
if any(g["name"] == new_name for g in groups):
return False # 新名前が既に存在
# グループリスト更新
for g in groups:
if g["name"] == old_name:
g["name"] = new_name
break
# 全画像のgroupsフィールドを更新
for meta in self._data["images"].values():
img_groups = meta.get("groups", [])
if old_name in img_groups:
meta["groups"] = [new_name if g == old_name else g for g in img_groups]
return self._save_to_disk()
with self._lock:
groups = self._data.get("groups", [])
if not any(g["name"] == old_name for g in groups):
return False
if any(g["name"] == new_name for g in groups):
return False # 新名前が既に存在
# グループリスト更新
for g in groups:
if g["name"] == old_name:
g["name"] = new_name
break
# 全画像のgroupsフィールドを更新
for meta in self._data["images"].values():
img_groups = meta.get("groups", [])
if old_name in img_groups:
meta["groups"] = [new_name if g == old_name else g for g in img_groups]
return self._save_to_disk()
def delete_group(self, name: str) -> bool:
groups = [g for g in self._data.get("groups", []) if g["name"] != name]
self._data["groups"] = groups
# 画像のgroupsからも削除
for meta in self._data["images"].values():
if name in meta.get("groups", []):
meta["groups"] = [g for g in meta["groups"] if g != name]
return self._save_to_disk()
with self._lock:
groups = [g for g in self._data.get("groups", []) if g["name"] != name]
self._data["groups"] = groups
# 画像のgroupsからも削除
for meta in self._data["images"].values():
if name in meta.get("groups", []):
meta["groups"] = [g for g in meta["groups"] if g != name]
return self._save_to_disk()
def list_images_in_group(self, group_name: str) -> list[str]:
result = []
for key, meta in self._data["images"].items():
if group_name in meta.get("groups", []):
result.append(key)
return result
with self._lock:
result = []
for key, meta in self._data["images"].items():
if group_name in meta.get("groups", []):
result.append(key)
return result
def remove_stale_paths_from_group(self, group_name: str, stale_paths: list) -> int:
"""存在しないパスをグループから一括削除する(1回の保存で完結)"""
with self._lock:
stale_set = {self._normalize_path(p) for p in stale_paths}
count = 0
for key, meta in self._data["images"].items():
if key in stale_set and group_name in meta.get("groups", []):
meta["groups"] = [g for g in meta["groups"] if g != group_name]
count += 1
if count:
self._save_to_disk()
return count
def get_group_member_set(self, group_name: str) -> set:
"""グループメンバーのパスをsetで返す(高速フィルタ用)"""
return {
key for key, meta in self._data["images"].items()
if group_name in meta.get("groups", [])
}
with self._lock:
return {
key for key, meta in self._data["images"].items()
if group_name in meta.get("groups", [])
}
def clear_group(self, group_name: str) -> bool:
"""グループ内の全画像を除外する(グループ自体は残す)"""
with self._lock:
for meta in self._data["images"].values():
if group_name in meta.get("groups", []):
meta["groups"] = [g for g in meta["groups"] if g != group_name]
return self._save_to_disk()
def ensure_group(self, name: str) -> bool:
"""グループが存在しない場合のみ作成する"""
with self._lock:
if any(g["name"] == name for g in self._data.get("groups", [])):
return True
return self.create_group(name)
def delete(self, image_path: str) -> bool:
"""画像のメタデータエントリを削除する"""
key = self._normalize_path(image_path)
with self._lock:
if key in self._data["images"]:
del self._data["images"][key]
return self._save_to_disk()
return True
def rename_path(self, old_path: str, new_path: str) -> bool:
"""画像のパスキーを変更する(ファイル移動後のメタデータ引継ぎ)"""
old_key = self._normalize_path(old_path)
new_key = self._normalize_path(new_path)
with self._lock:
if old_key in self._data["images"]:
self._data["images"][new_key] = self._data["images"].pop(old_key)
return self._save_to_disk()
return True
def cleanup_stale_images(self, folder_path: str, existing_paths: set, recursive: bool = True) -> int:
"""folder_path 配下の存在しないファイルのメタデータを削除する。
existing_paths: そのフォルダの現在のファイルパス集合(_normalize_path 済み)
recursive: False の場合、folder_path 直下のファイルのみを対象にする。
呼び出し元(list_images)が非recursiveスキャン(フォルダ直下のみ列挙)の
結果を existing_paths として渡してくる場合、サブフォルダ内のファイルは
existing_paths に含まれない。それにもかかわらず対象範囲を「folder_path配下
全階層」のままにすると、サブフォルダ内画像のメタデータ(tags/memo等)を
"存在しない"と誤判定して全削除してしまう(実際に発生した不具合: サブフォルダ
に動画を保存する運用で、ルートフォルダを非recursiveで開くたびに
サブフォルダ内の全メタデータが失われていた)。
"""
folder_key = self._normalize_path(folder_path)
if not folder_key.endswith("/"):
folder_key += "/"
def _in_scope(key: str) -> bool:
if not key.startswith(folder_key):
return False
if recursive:
return True
return "/" not in key[len(folder_key):]
with self._lock:
stale = [
key for key in self._data["images"]
if _in_scope(key) and key not in existing_paths
]
if not stale:
return 0
for key in stale:
del self._data["images"][key]
self._save_to_disk()
logger.info("Cleaned up %d stale metadata entries from %s", len(stale), folder_path)
return len(stale)
File diff suppressed because it is too large Load Diff
+138
View File
@@ -0,0 +1,138 @@
"""Lab tab plan file management service (JSON plan + optional PNG index thumbnail)."""
import base64
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
logger = logging.getLogger(__name__)
class LabPlanService:
def __init__(self, plan_dir: Path):
self.plan_dir = plan_dir
self.plan_dir.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# Path safety
# ------------------------------------------------------------------
def _safe_path(self, filename: str, ext: str = ".json") -> Path | None:
if not filename or not filename.strip():
return None
name = filename.strip()
if not name.endswith(ext):
name = name + ext
if "/" in name or "\\" in name or name in (".", "..") or "\x00" in name:
return None
resolved = (self.plan_dir / name).resolve()
plan_dir_resolved = self.plan_dir.resolve()
if resolved != plan_dir_resolved and not str(resolved).startswith(str(plan_dir_resolved) + "\\") and not str(resolved).startswith(str(plan_dir_resolved) + "/"):
return None
return resolved
def _now_iso(self) -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
# ------------------------------------------------------------------
# CRUD
# ------------------------------------------------------------------
def list_plans(self) -> list[dict]:
if not self.plan_dir.is_dir():
return []
result = []
for path in sorted(self.plan_dir.glob("*.json")):
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
logger.warning("Skipping unreadable lab plan %s: %s", path.name, e)
continue
stem = path.stem
thumbnail = None
thumb_path = self.plan_dir / f"{stem}.png"
if thumb_path.is_file():
thumbnail = f"/wfm_data/lab_plan/{stem}.png"
result.append({
"filename": path.name,
"name": data.get("name", stem),
"note": data.get("note", ""),
"batch_count": data.get("batch_count", 1),
"updated_at": data.get("updated_at", ""),
"thumbnail": thumbnail,
})
result.sort(key=lambda p: p.get("updated_at", ""), reverse=True)
return result
def get_plan(self, filename: str) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if not path.is_file():
raise FileNotFoundError(f"Plan not found: {filename}")
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def save_plan(self, filename: str, data: dict, index_image_base64: str | None = None) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
data = dict(data)
data["updated_at"] = self._now_iso()
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
if index_image_base64:
self.save_index_image(filename, index_image_base64)
return {"filename": path.name, "updated_at": data["updated_at"]}
def save_index_image(self, filename: str, image_base64: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
stem = path.stem
thumb_path = self.plan_dir / f"{stem}.png"
# Accept both raw base64 and data: URL forms
b64 = image_base64
if "," in b64 and b64.strip().lower().startswith("data:"):
b64 = b64.split(",", 1)[1]
image_bytes = base64.b64decode(b64)
with open(thumb_path, "wb") as f:
f.write(image_bytes)
def save_index_image_to_output(self, image_base64: str, filename_prefix: str = "Lab_index") -> dict:
"""Saves the contact-sheet index image into ComfyUI's own output folder,
alongside the images generated during the run (unlike save_index_image,
which saves it next to the plan file in plan_dir)."""
b64 = image_base64
if "," in b64 and b64.strip().lower().startswith("data:"):
b64 = b64.split(",", 1)[1]
image_bytes = base64.b64decode(b64)
import folder_paths # type: ignore
output_dir = folder_paths.get_output_directory()
full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
save_name = f"{filename}_{counter:05}_.png"
save_path = Path(full_output_folder) / save_name
save_path.write_bytes(image_bytes)
return {"filename": save_name, "subfolder": subfolder}
def delete_plan(self, filename: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if path.is_file():
path.unlink()
thumb_path = self.plan_dir / f"{path.stem}.png"
if thumb_path.is_file():
thumb_path.unlink()
+374 -7
View File
@@ -2,6 +2,8 @@
import json
import logging
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -9,10 +11,23 @@ from ..config import MODEL_METADATA_FILE
logger = logging.getLogger(__name__)
_SCAN_CACHE_TTL = 30 # seconds — reuse scan result within this window
# Preview image extensions to search for (in priority order)
_PREVIEW_EXTENSIONS = [".preview.png", ".preview.jpg", ".preview.jpeg", ".preview.webp",
".png", ".jpg", ".jpeg", ".webp"]
# All sidecar extensions to delete when a model is deleted
_SIDECAR_EXTENSIONS = [
".preview.png", ".preview.jpg", ".preview.jpeg", ".preview.webp",
".png", ".jpg", ".jpeg", ".webp",
".metadata.json", ".cm-info.json", ".json", ".civitai.info", ".info",
]
_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",
@@ -59,6 +74,7 @@ class ModelsService:
def __init__(self):
self.metadata_file = MODEL_METADATA_FILE
self._scan_cache: dict = {} # model_type -> (timestamp, frozenset)
def _now_iso(self):
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
@@ -100,15 +116,180 @@ class ModelsService:
self._save_metadata(data)
return entry
def get_model_groups(self):
data = self._load_metadata()
return data.get("_groups", {})
def _scan_model_names(self, model_type: str) -> set:
"""モデルタイプの全ファイル名をスキャンして返す(相対パス、/区切り、.disabled除く)。
結果は30秒キャッシュされ、起動時の多重スキャンによる高負荷を防ぐ。"""
now = time.monotonic()
cached = self._scan_cache.get(model_type)
if cached is not None:
ts, names = cached
if now - ts < _SCAN_CACHE_TTL:
return names
def save_model_groups(self, groups):
dirs = _get_model_dirs(model_type)
names = set()
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if not f.is_file():
continue
try:
rel = str(f.relative_to(d)).replace("\\", "/")
if rel.endswith(_DISABLED_SUFFIX):
rel = rel[: -len(_DISABLED_SUFFIX)]
names.add(rel)
except ValueError:
pass
self._scan_cache[model_type] = (now, names)
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()
data["_groups"] = groups
raw = data.get("_groups", {})
# Migrate old flat format { "groupName": [...] } → per-type { "checkpoint": {...} }
if raw and not any(k in MODEL_TYPE_FOLDER_KEYS for k in raw):
logger.info("Migrating groups to per-type format (old data moved to _groups_legacy)")
data["_groups_legacy"] = raw
data["_groups"] = {}
self._save_metadata(data)
raw = {}
if model_type:
groups = raw.get(model_type, {})
# Guard: if no model directories are accessible (e.g. network drive disconnected),
# skip cleanup entirely to prevent mass-deletion of group members.
accessible_dirs = [d for d in _get_model_dirs(model_type) if d.is_dir()]
if not accessible_dirs:
configured_dirs = _get_model_dirs(model_type)
if configured_dirs:
logger.warning(
"No accessible directories for model_type=%s — skipping group cleanup "
"to avoid data loss (drives may be disconnected)", model_type
)
return {g: [m.replace("\\", "/") for m in members]
for g, members in groups.items()}
# No directories configured at all — return as-is (nothing to validate against)
return {g: [m.replace("\\", "/") for m in members] for g, members in groups.items()}
valid_names = self._scan_model_names(model_type)
cleaned = {}
dirty = False
for g_name, members in groups.items():
# Normalize backslashes (Windows ComfyUI paths) to forward slashes
normalized = [m.replace("\\", "/") for m in members]
filtered = [m for m in normalized if m in valid_names]
cleaned[g_name] = filtered
if len(filtered) != len(members) or normalized != list(members):
dirty = True
if dirty:
removed = sum(len(groups[g]) - len(cleaned[g]) for g in groups)
if removed > 0:
logger.info("Cleaned up %d stale group entries for model_type=%s", removed, model_type)
if not isinstance(data.get("_groups"), dict):
data["_groups"] = {}
data["_groups"][model_type] = cleaned
self._save_metadata(data)
return cleaned
return raw
def save_model_groups(self, groups, model_type):
# Normalize all member names to forward slashes (ComfyUI on Windows uses backslashes)
normalized = {g: [m.replace("\\", "/") for m in members] for g, members in groups.items()}
data = self._load_metadata()
if not isinstance(data.get("_groups"), dict):
data["_groups"] = {}
data["_groups"][model_type] = normalized
self._save_metadata(data)
return groups
# Also invalidate scan cache so next get_model_groups sees the fresh data
self._scan_cache.pop(model_type, None)
return normalized
def find_model_file(self, model_type, model_name):
"""Find a model file, checking both enabled and disabled states.
Returns (Path, is_enabled) or (None, None) if not found.
"""
dirs = _get_model_dirs(model_type)
for d in dirs:
enabled = d / model_name
if enabled.is_file():
return enabled, True
disabled = d / (model_name + _DISABLED_SUFFIX)
if disabled.is_file():
return disabled, False
return None, None
def enable_model(self, model_type, model_name):
"""Rename model.safetensors.disabled → model.safetensors."""
path, is_enabled = self.find_model_file(model_type, model_name)
if path is None:
raise FileNotFoundError(f"Model not found: {model_name}")
if is_enabled:
return
target = path.parent / path.name[: -len(_DISABLED_SUFFIX)]
path.rename(target)
logger.info("Enabled model: %s", model_name)
def disable_model(self, model_type, model_name):
"""Rename model.safetensors → model.safetensors.disabled."""
path, is_enabled = self.find_model_file(model_type, model_name)
if path is None:
raise FileNotFoundError(f"Model not found: {model_name}")
if not is_enabled:
return
target = path.parent / (path.name + _DISABLED_SUFFIX)
path.rename(target)
logger.info("Disabled model: %s", model_name)
def scan_disabled_models(self, model_type):
"""Scan directories for .disabled files.
Returns list of normalized model names (without .disabled suffix).
"""
dirs = _get_model_dirs(model_type)
disabled = []
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if f.is_file() and f.name.endswith(_DISABLED_SUFFIX):
try:
rel = str(f.relative_to(d))
if rel.endswith(_DISABLED_SUFFIX):
rel = rel[: -len(_DISABLED_SUFFIX)]
disabled.append(rel.replace("\\", "/"))
except ValueError:
pass
return disabled
def find_preview_image(self, model_type, model_name):
"""Find preview image for a model file.
@@ -138,7 +319,7 @@ class ModelsService:
for ext in _PREVIEW_EXTENSIONS:
preview = parent / (stem + ext)
if preview.is_file():
if preview.is_file() and preview.stat().st_size >= 100:
logger.debug("Preview found: %s", preview)
return preview
@@ -148,3 +329,189 @@ class ModelsService:
logger.debug("Preview: model file not found in any dir: %s", model_name)
return None
def delete_model(self, model_type, model_name):
"""Delete a model file and all associated preview/sidecar files.
Also removes the model's metadata entry.
Returns dict with deleted file paths.
"""
if ".." in model_name:
raise ValueError(f"Invalid model name: {model_name}")
path, _ = self.find_model_file(model_type, model_name)
if path is None:
raise FileNotFoundError(f"Model not found: {model_name}")
deleted = []
parent = path.parent
# Compute stem from the original (non-disabled) filename.
# path.name for a disabled file is e.g. "model.safetensors.disabled"
# so we strip the .disabled suffix first, then take Path.stem.
orig_name = path.name
if orig_name.endswith(_DISABLED_SUFFIX):
orig_name = orig_name[: -len(_DISABLED_SUFFIX)]
stem = Path(orig_name).stem # "model.safetensors" -> "model"
# Delete the model file itself
path.unlink()
deleted.append(str(path))
logger.info("Deleted model file: %s", path)
# Delete all sidecar files (previews, metadata, info)
for ext in _SIDECAR_EXTENSIONS:
sidecar = parent / (stem + ext)
if sidecar.is_file():
sidecar.unlink()
deleted.append(str(sidecar))
logger.info("Deleted sidecar: %s", sidecar)
# Remove metadata entry
data = self._load_metadata()
if model_name in data:
del data[model_name]
self._save_metadata(data)
return {"deleted": deleted}
def get_subdirs(self, model_type):
"""Return sorted list of root-level subdirectory names for a model type."""
dirs = _get_model_dirs(model_type)
subdirs = set()
for d in dirs:
if not d.is_dir():
continue
for item in d.iterdir():
if item.is_dir():
subdirs.add(item.name)
return sorted(subdirs)
def move_models(self, model_type, model_names, dest_subdir):
"""Move model files + sidecar files to dest_subdir (root-level subfolder name).
dest_subdir: "" = model root, "sdxl" = <root>/sdxl/
Creates the destination directory if it does not exist.
Updates metadata keys to reflect new paths.
Returns {"moved": [{"from": ..., "to": ...}], "errors": [...]}
"""
# Validate dest_subdir: must be a plain folder name (no separators, no "..", not absolute)
if dest_subdir:
if ".." in dest_subdir:
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: '..' not allowed"}]}
if "/" in dest_subdir or "\\" in dest_subdir:
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: must be a single folder name"}]}
if Path(dest_subdir).is_absolute():
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: absolute paths not allowed"}]}
moved = []
errors = []
model_dirs = _get_model_dirs(model_type)
meta_data = self._load_metadata()
meta_changed = False
renames = [] # [(old_name, new_name)]
for model_name in model_names:
if ".." in model_name:
errors.append({"model": model_name, "error": "Invalid model name"})
continue
path, _is_enabled = self.find_model_file(model_type, model_name)
if path is None:
errors.append({"model": model_name, "error": f"Model not found: {model_name}"})
continue
try:
# Determine which root dir this model lives in
root_dir = None
for d in model_dirs:
try:
path.relative_to(d)
root_dir = d
break
except ValueError:
pass
if root_dir is None:
errors.append({"model": model_name, "error": "Cannot determine root directory"})
continue
# Destination directory — verify it stays within root_dir after resolution
dest_dir = root_dir / dest_subdir if dest_subdir else root_dir
try:
dest_dir.resolve().relative_to(root_dir.resolve())
except ValueError:
errors.append({"model": model_name, "error": "Destination is outside model root"})
continue
dest_dir.mkdir(parents=True, exist_ok=True)
# Original filename without .disabled suffix
orig_name = path.name
if orig_name.endswith(_DISABLED_SUFFIX):
orig_name = orig_name[: -len(_DISABLED_SUFFIX)]
stem = Path(orig_name).stem
new_path = dest_dir / path.name
if new_path.resolve() == path.resolve():
errors.append({"model": model_name, "error": "Already in destination"})
continue
# Refuse to overwrite an existing file
if new_path.exists():
errors.append({"model": model_name, "error": f"Destination already exists: {path.name}"})
continue
# Move the model file
shutil.move(str(path), str(new_path))
logger.info("Moved model: %s → %s", path, new_path)
# Move all sidecar files (skip if destination already exists)
for ext in _SIDECAR_EXTENSIONS:
sidecar = path.parent / (stem + ext)
if sidecar.is_file():
sidecar_dest = dest_dir / (stem + ext)
if sidecar_dest.exists():
logger.warning("Sidecar destination exists, skipping: %s", sidecar_dest)
continue
try:
shutil.move(str(sidecar), str(sidecar_dest))
except Exception as se:
logger.warning("Could not move sidecar %s: %s", sidecar, se)
# Compute new logical model name (relative to root, forward slashes)
new_rel = str(new_path.relative_to(root_dir)).replace("\\", "/")
if new_rel.endswith(_DISABLED_SUFFIX):
new_rel = new_rel[: -len(_DISABLED_SUFFIX)]
# Update metadata key
if model_name in meta_data:
meta_data[new_rel] = meta_data.pop(model_name)
meta_changed = True
moved.append({"from": model_name, "to": new_rel})
renames.append((model_name, new_rel))
except Exception as e:
logger.error("Error moving model %s: %s", model_name, e)
errors.append({"model": model_name, "error": str(e)})
# Update group entries for renamed/moved models
if renames:
groups_for_type = meta_data.get("_groups", {}).get(model_type, {})
groups_dirty = False
for old_name, new_name in renames:
for members in groups_for_type.values():
for i, m in enumerate(members):
if m == old_name:
members[i] = new_name
groups_dirty = True
if groups_dirty:
if not isinstance(meta_data.get("_groups"), dict):
meta_data["_groups"] = {}
meta_data["_groups"][model_type] = groups_for_type
meta_changed = True
if meta_changed:
self._save_metadata(meta_data)
return {"moved": moved, "errors": errors}
+228
View File
@@ -0,0 +1,228 @@
"""AI skill (.md system prompt) file management service."""
import logging
import re
from pathlib import Path
logger = logging.getLogger(__name__)
ALLOWED_EXTS = {"md"}
DEFAULT_SKILL_FILENAME = "svg-icon.md"
DEFAULT_SKILL_CONTENT = """---
name: SVG Icon Generator
description: Produces clean, minimal, valid SVG icons and simple illustrations.
---
You are an expert SVG icon and illustration designer. When the user asks for an icon, logo, pictogram, diagram, character, animal, or any vector graphic, respond with valid, clean SVG markup.
## Composition process (do this before writing markup - skipping this step is the main cause of unrecognizable output)
- Break the subject down into 3-8 distinct parts that make it recognizable (e.g. a bird: body, head, beak, eye, wing, tail; a house: wall, roof, door, window). Drop parts that are not essential.
- Decide each part's approximate position, size, and draw order within the viewBox (elements listed later in the markup are drawn on top).
- Pick the simplest shape that captures each part's silhouette: `<circle>`/`<ellipse>` for round parts, `<rect>` for rectangular parts, `<polygon>` for angular parts (beaks, ears, leaves, roofs). For a rounded organic outline that no primitive can approximate well (a body silhouette, a wing, a leaf edge), use a short `<path>` with 2-4 smooth curve commands (`Q` or `C`) instead of a plain circle - a few deliberate curve points beat a distorted primitive.
- Never fall back to drawing an unrelated blob plus a few disconnected decorative lines when a subject is hard to render - always decompose it into the named parts above instead, even if each part is crude.
## Output rules
- Always wrap the SVG markup in a fenced code block labeled `svg`, e.g. ```svg ... ```.
- Keep any explanation brief and place it OUTSIDE the code block, never mixed inside the SVG.
- Output exactly one `<svg>...</svg>` element per code block.
## Structure rules
- Always include a `viewBox` attribute (e.g. `viewBox="0 0 24 24"`). Do not hardcode large pixel `width`/`height`; if you set them, make them match the viewBox aspect ratio.
- Use a small, round coordinate system (0-24 or 0-100).
- Round coordinate values to at most 2 decimal places.
- Keep every `<path>` short (at most about 6 commands) - long, intricate paths are where quality breaks down most often.
- Group related elements with `<g>` when it clarifies structure, but do not over-nest.
## Color rules
- For single-color icons, use `fill="currentColor"` (or `stroke="currentColor"` for line icons) so the icon inherits the surrounding text color.
- For multi-color illustrations, use explicit hex colors (e.g. `#4A90D9`) - never named CSS colors like `"blue"`.
- Avoid gradients, filters, and blend modes unless the user explicitly asks for a glossy/gradient style - they rarely render correctly from generated coordinates.
## Accessibility
- Include a `<title>` element as the first child of `<svg>` describing what the icon depicts.
## Security (mandatory - do not violate)
- Never include `<script>`, `<foreignObject>`, event handler attributes (`onload`, `onclick`, etc.), or `<a>`/`href` links to external URLs.
- Never reference external resources (no `xlink:href` to remote URLs, no `<image>` with external `src`).
## Example 1 - simple geometric icon (single color, primitives only)
Request: "Sun icon"
Parts: disc (circle), 8 rays (lines).
```svg
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Sun</title>
<circle cx="12" cy="12" r="5" fill="currentColor"/>
<g stroke="currentColor" stroke-width="2" stroke-linecap="round">
<line x1="12" y1="1" x2="12" y2="4"/>
<line x1="12" y1="20" x2="12" y2="23"/>
<line x1="4.22" y1="4.22" x2="6.34" y2="6.34"/>
<line x1="17.66" y1="17.66" x2="19.78" y2="19.78"/>
<line x1="1" y1="12" x2="4" y2="12"/>
<line x1="20" y1="12" x2="23" y2="12"/>
<line x1="4.22" y1="19.78" x2="6.34" y2="17.66"/>
<line x1="17.66" y1="6.34" x2="19.78" y2="4.22"/>
</g>
</svg>
```
## Example 2 - organic subject (multi-color, decomposed into parts)
Request: "Bird icon"
Parts: body (rounded outline via a short curved path), head (circle), beak (small triangle), eye (dot), wing (small curved path) - each drawn as its own element, layered head/beak/eye on top of the body.
```svg
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Bird</title>
<path d="M4 16 Q4 10 11 9 Q18 8 20 13 Q20 17 14 18 Q7 19 4 16 Z" fill="#4A90D9"/>
<path d="M8 14 Q5 12 3 14 Q6 16 9 16 Z" fill="#3576B8"/>
<circle cx="17" cy="10" r="3.2" fill="#4A90D9"/>
<polygon points="20,10 23,9.3 20,11.4" fill="#F2B807"/>
<circle cx="18" cy="9" r="0.6" fill="#1A1A1A"/>
</svg>
```
Follow this pattern for every request: list the parts first, represent each with the simplest adequate shape, then assemble - never skip straight to unstructured shapes.
"""
SKILL_CREATOR_FILENAME = "skill-creator.md"
SKILL_CREATOR_CONTENT = """---
name: Skill Creator
description: Interactively interviews you and drafts a new WFS chat skill (.md system prompt) ready to save.
---
You are a skill-design assistant embedded in ComfyUI Workflow Studio's AI TOOL Chat pane. Your job is to interactively help the user design a NEW "skill" - a markdown file with frontmatter (`name`, `description`) followed by system-prompt instructions. Once saved, a skill can be selected from a dropdown and is silently prepended to future chat messages as a system prompt.
## How to conduct the interview
- Ask ONE focused question at a time, never a bulleted list of questions. Wait for the user's answer before asking the next one.
- Cover, in this order, only what is not already clear from context:
1. What task or domain should the skill specialize in (what should the model do differently once this skill is active)?
2. What output format is expected - plain prose, a specific fenced code block language, a fixed structure, a length limit?
3. Any hard constraints or things to avoid (tone, forbidden content, security concerns, things past attempts got wrong)?
4. Would a short worked example help smaller/local models follow the pattern more reliably? If yes, ask what a good example input/output looks like, or offer to draft one.
- Keep it short - 3 to 5 questions is usually enough. If the user says "just generate it", "that's enough", or similar at any point, stop asking and produce the best skill you can from what you already have.
## Output format for the finished skill
- Once you have enough information, output the complete skill file in a single fenced code block labeled `skill` (```skill ... ```). Never mix prose inside that block - explanation goes outside it.
- The block must start with frontmatter exactly in this shape:
---
name: <short display name, shown in the skill dropdown>
description: <one sentence, shown as a tooltip in the dropdown>
---
- After the frontmatter, write clear, imperative system-prompt instructions for the target skill: what role the model should take, concrete output-format rules, hard constraints, and - if useful - one short worked example following a "request -> ideal output" shape.
- After the code block, tell the user in one line that they can click the "Save as new skill" button below the message to add it, or copy the block manually into a new skill.
"""
_FRONTMATTER_RE = re.compile(r"^---\r?\n(.*?)\r?\n---\r?\n?", re.DOTALL)
def _parse_frontmatter(content: str) -> dict:
"""Extract a shallow `key: value` frontmatter block, if present."""
m = _FRONTMATTER_RE.match(content)
if not m:
return {}
fields: dict = {}
for line in m.group(1).splitlines():
if ":" not in line:
continue
key, _, value = line.partition(":")
key = key.strip()
value = value.strip()
if key:
fields[key] = value
return fields
class SkillService:
def __init__(self, skills_dir: Path):
self.skills_dir = skills_dir
self.skills_dir.mkdir(parents=True, exist_ok=True)
self._seed_default_skill()
def _seed_default_skill(self) -> None:
"""Seed a starter skill file the first time the directory is empty."""
try:
has_any = any(
p.is_file() and p.suffix.lstrip(".").lower() in ALLOWED_EXTS
for p in self.skills_dir.iterdir()
)
except FileNotFoundError:
has_any = False
if not has_any:
(self.skills_dir / DEFAULT_SKILL_FILENAME).write_text(
DEFAULT_SKILL_CONTENT, encoding="utf-8"
)
(self.skills_dir / SKILL_CREATOR_FILENAME).write_text(
SKILL_CREATOR_CONTENT, encoding="utf-8"
)
# ------------------------------------------------------------------
# File CRUD
# ------------------------------------------------------------------
def list_skills(self) -> list[dict]:
"""Return sorted list of skill files with parsed frontmatter metadata."""
if not self.skills_dir.exists():
return []
files = []
for path in sorted(self.skills_dir.glob("*")):
if not (path.is_file() and path.suffix.lstrip(".").lower() in ALLOWED_EXTS):
continue
try:
content = path.read_text(encoding="utf-8")
except Exception:
content = ""
meta = _parse_frontmatter(content)
files.append({
"filename": path.name,
"name": meta.get("name") or path.stem,
"description": meta.get("description", ""),
"size": path.stat().st_size,
})
return files
def get_content(self, filename: str) -> str:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if not path.is_file():
raise FileNotFoundError(f"File not found: {filename}")
return path.read_text(encoding="utf-8")
def save_file(self, filename: str, content: str) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
path.write_text(content, encoding="utf-8")
meta = _parse_frontmatter(content)
return {
"filename": path.name,
"name": meta.get("name") or path.stem,
"description": meta.get("description", ""),
"size": path.stat().st_size,
}
def delete_file(self, filename: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if path.is_file():
path.unlink()
def _safe_path(self, filename: str) -> Path | None:
if not filename or not filename.strip():
return None
# Skills are a flat directory - reject any path separator (no subfolders).
name = filename.strip()
if "/" in name or "\\" in name or name in (".", ".."):
return None
ext = Path(name).suffix.lstrip(".").lower()
if ext not in ALLOWED_EXTS:
return None
return self.skills_dir / name
+123
View File
@@ -0,0 +1,123 @@
"""Tagger タグ DB サービス(SQLite)。"""
import csv
import io
import logging
import sqlite3
from pathlib import Path
from typing import List
logger = logging.getLogger(__name__)
class TaggerDbService:
def __init__(self, db_file: Path):
self.db_file = db_file
self._init_db()
def _conn(self) -> sqlite3.Connection:
return sqlite3.connect(str(self.db_file))
def _init_db(self):
self.db_file.parent.mkdir(parents=True, exist_ok=True)
with self._conn() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT,
interrogator_tags TEXT,
vlm_tags TEXT,
all_tags TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
for sql in [
"CREATE INDEX IF NOT EXISTS idx_all_tags ON images(all_tags)",
"CREATE INDEX IF NOT EXISTS idx_filename ON images(filename)",
"CREATE INDEX IF NOT EXISTS idx_created_at ON images(created_at DESC)",
]:
conn.execute(sql)
conn.commit()
def save(self, filename: str, interrogator_tags: str, vlm_tags: str) -> int:
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
with self._conn() as conn:
cur = conn.execute(
"INSERT INTO images (filename, interrogator_tags, vlm_tags, all_tags) VALUES (?, ?, ?, ?)",
(filename, interrogator_tags, vlm_tags, all_tags),
)
conn.commit()
return cur.lastrowid
def list(self, limit: int = 100, offset: int = 0) -> list:
with self._conn() as conn:
rows = conn.execute(
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at "
"FROM images ORDER BY id DESC LIMIT ? OFFSET ?",
(limit, offset),
).fetchall()
return [self._row(r) for r in rows]
def total(self) -> int:
with self._conn() as conn:
return conn.execute("SELECT COUNT(*) FROM images").fetchone()[0]
def search(self, q: str) -> list:
pattern = f"%{q}%"
with self._conn() as conn:
rows = conn.execute(
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at "
"FROM images WHERE all_tags LIKE ? OR filename LIKE ? ORDER BY id DESC LIMIT 200",
(pattern, pattern),
).fetchall()
return [self._row(r) for r in rows]
def update(self, row_id: int, interrogator_tags: str, vlm_tags: str):
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
with self._conn() as conn:
conn.execute(
"UPDATE images SET interrogator_tags=?, vlm_tags=?, all_tags=? WHERE id=?",
(interrogator_tags, vlm_tags, all_tags, row_id),
)
conn.commit()
def delete(self, row_id: int):
with self._conn() as conn:
conn.execute("DELETE FROM images WHERE id=?", (row_id,))
conn.commit()
def delete_bulk(self, row_ids: List[int]) -> int:
if not row_ids:
return 0
placeholders = ",".join("?" for _ in row_ids)
with self._conn() as conn:
cur = conn.execute(
f"DELETE FROM images WHERE id IN ({placeholders})",
row_ids,
)
conn.commit()
return cur.rowcount
def export_csv(self) -> str:
with self._conn() as conn:
rows = conn.execute(
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at FROM images ORDER BY id"
).fetchall()
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["id", "filename", "interrogator_tags", "vlm_tags", "all_tags", "created_at"])
writer.writerows(rows)
return buf.getvalue()
@staticmethod
def _row(r) -> dict:
return {
"id": r[0],
"filename": r[1] or "",
"interrogator_tags": r[2] or "",
"vlm_tags": r[3] or "",
"all_tags": r[4] or "",
"created_at": r[5] or "",
}
+488
View File
@@ -0,0 +1,488 @@
"""WD Tagger / DeepDanbooru / Ollama VLM 推論サービス。"""
import base64
import csv
import io
import json
import logging
import os
import re
import tempfile
import threading
import urllib.request
from pathlib import Path
from typing import Optional
import numpy as np
from PIL import Image, ImageOps, PngImagePlugin
logger = logging.getLogger(__name__)
_model_lock = threading.Lock()
class TaggerService:
def __init__(self, models_dir: Path, settings_file: Path):
self.models_dir = models_dir
self.settings_file = settings_file
self._cache: dict = {}
self._batch_state: dict = {
"running": False, "total": 0, "done": 0, "log": [], "stop": False,
}
# ── 設定 ──────────────────────────────────────────────────
def load_settings(self) -> dict:
if self.settings_file.exists():
try:
with open(self.settings_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {}
def save_settings(self, data: dict):
self.settings_file.parent.mkdir(parents=True, exist_ok=True)
with open(self.settings_file, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def _effective_models_dir(self) -> Path:
custom = self.load_settings().get("models_dir", "").strip()
if custom:
p = Path(custom)
if p.is_dir():
return p
return self.models_dir
# ── モデル一覧 ─────────────────────────────────────────────
def list_models(self) -> list:
mdir = self._effective_models_dir()
models = []
if not mdir.is_dir():
return models
for item in sorted(mdir.iterdir()):
if not item.is_dir():
continue
exts = {f.suffix.lower() for f in item.iterdir() if f.is_file()}
if ".onnx" in exts:
models.append({"name": item.name, "type": "onnx"})
elif ".h5" in exts:
models.append({"name": item.name, "type": "deepdanbooru"})
return models
# ── モデルロード ──────────────────────────────────────────
@staticmethod
def _validate_model_name(name: str) -> bool:
"""パストラバーサル防止: セパレータ・NUL・相対参照を拒否"""
return bool(name) and "/" not in name and "\\" not in name and "\x00" not in name and name not in (".", "..")
def _load_model(self, model_name: str) -> Optional[dict]:
if not self._validate_model_name(model_name):
logger.error("Invalid model name rejected: %r", model_name)
return None
if model_name in self._cache:
return self._cache[model_name]
with _model_lock:
if model_name in self._cache:
return self._cache[model_name]
mdir = self._effective_models_dir()
model_dir = mdir / model_name
if not model_dir.is_dir():
logger.error("Model dir not found: %s", model_dir)
return None
files = list(model_dir.iterdir())
onnx = next((f for f in files if f.suffix == ".onnx"), None)
h5 = next((f for f in files if f.suffix == ".h5"), None)
if onnx:
return self._load_onnx(model_name, onnx, model_dir)
if h5:
return self._load_deepdanbooru(model_name, h5, model_dir)
logger.error("No .onnx or .h5 in %s", model_dir)
return None
def _load_onnx(self, name: str, onnx_file: Path, model_dir: Path) -> Optional[dict]:
try:
import onnxruntime as ort
providers = []
try:
import torch
if torch.cuda.is_available():
providers.append("CUDAExecutionProvider")
except ImportError:
pass
providers.append("CPUExecutionProvider")
session = ort.InferenceSession(str(onnx_file), providers=providers)
labels = self._load_labels(model_dir)
data = {
"session": session,
"labels": labels,
"input_name": session.get_inputs()[0].name,
"input_shape": session.get_inputs()[0].shape,
"type": "onnx",
}
self._cache[name] = data
logger.info("ONNX loaded: %s (%d labels)", name, len(labels))
return data
except ImportError:
logger.error("onnxruntime not installed")
return None
except Exception as e:
logger.error("ONNX load error %s: %s", name, e)
return None
def _load_deepdanbooru(self, name: str, h5_file: Path, model_dir: Path) -> Optional[dict]:
try:
import tensorflow as tf
except ImportError:
logger.warning("TensorFlow not installed — DeepDanbooru unavailable")
return None
try:
model = tf.keras.models.load_model(str(h5_file))
labels = self._load_labels(model_dir)
data = {"session": model, "labels": labels, "type": "deepdanbooru"}
self._cache[name] = data
logger.info("DeepDanbooru loaded: %s (%d labels)", name, len(labels))
return data
except Exception as e:
logger.error("DeepDanbooru load error %s: %s", name, e)
return None
def _load_labels(self, model_dir: Path) -> list:
for fname in ("selected_tags.csv", "tags.csv", "tags.txt", "tags-general.txt"):
p = model_dir / fname
if not p.exists():
continue
try:
if p.suffix == ".csv":
with open(p, "r", encoding="utf-8-sig", newline="") as f:
reader = csv.reader(f)
next(reader, None)
return [row[1] for row in reader if len(row) > 1]
else:
with open(p, "r", encoding="utf-8") as f:
return [ln.strip() for ln in f if ln.strip()]
except Exception as e:
logger.warning("Label load failed %s: %s", p, e)
return []
# ── 推論(WD Tagger / DeepDanbooru) ────────────────────
def predict(self, image_b64: str, model_name: str, threshold: float = 0.35, char_threshold: float = 0.85) -> dict:
img = self._decode_b64(image_b64)
data = self._load_model(model_name)
if data is None:
return {"error": f"Model '{model_name}' could not be loaded"}
try:
if data["type"] == "deepdanbooru":
tags = self._predict_dd(img, data, threshold, char_threshold)
else:
tags = self._predict_onnx(img, data, threshold, char_threshold)
return {"tags": ", ".join(tags), "count": len(tags)}
except Exception as e:
logger.error("predict error: %s", e)
return {"error": str(e)}
def _predict_onnx(self, img: Image.Image, data: dict, thr: float, char_thr: float) -> list:
shape = data["input_shape"]
fmt = "NHWC"
size = 224
if len(shape) == 4:
if shape[1] == 3 and isinstance(shape[2], int) and shape[2] > 0:
fmt = "NCHW"
size = int(shape[2])
elif shape[3] == 3 and isinstance(shape[1], int) and shape[1] > 0:
fmt = "NHWC"
size = int(shape[1])
img = ImageOps.exif_transpose(img)
# WD Tagger系標準の前処理: 透過は白背景で合成 → アスペクト比を維持したまま
# 白背景で正方形にパディング → リサイズ → RGB→BGR → 0-255のfloat32のまま(NHWC)
if img.mode != "RGBA":
img = img.convert("RGBA")
canvas = Image.new("RGBA", img.size, (255, 255, 255))
canvas.paste(img, mask=img)
img = canvas.convert("RGB")
w, h = img.size
max_dim = max(w, h)
padded = Image.new("RGB", (max_dim, max_dim), (255, 255, 255))
padded.paste(img, ((max_dim - w) // 2, (max_dim - h) // 2))
if max_dim != size:
padded = padded.resize((size, size), Image.Resampling.BICUBIC)
arr = np.array(padded, dtype=np.float32)
arr = np.ascontiguousarray(arr[:, :, ::-1]) # RGB -> BGR
if fmt == "NCHW":
arr = arr.transpose((2, 0, 1))
arr = np.expand_dims(arr, 0)
preds = data["session"].run(None, {data["input_name"]: arr})[0][0]
return self._filter_tags(preds, data["labels"], thr, char_thr)
def _predict_dd(self, img: Image.Image, data: dict, thr: float, char_thr: float) -> list:
img = ImageOps.exif_transpose(img)
if img.mode != "RGB":
img = img.convert("RGB")
arr = np.array(img.resize((512, 512), Image.Resampling.LANCZOS), dtype=np.float32) / 255.0
arr = np.expand_dims(arr, 0)
preds = data["session"].predict(arr)[0]
return self._filter_tags(preds, data["labels"], thr, char_thr)
def _filter_tags(self, preds, labels: list, thr: float, char_thr: float) -> list:
tags = []
for i, score in enumerate(preds):
if i >= len(labels):
break
label = labels[i]
if float(score) >= (char_thr if label.startswith("character:") else thr):
tags.append(label.replace("character:", ""))
return tags
# ── VLM Tagging (Ollama / LM Studio / Lemonade / Unsloth) ──
@staticmethod
def _unsloth_api_key() -> Optional[str]:
"""UNSLOTH_API_KEY を環境変数(.env)から取得。Unslothはローカルでも常に必須。"""
return os.environ.get("UNSLOTH_API_KEY", "").strip() or None
@staticmethod
def _strip_thinking_tags(text: str) -> str:
text = re.sub(r"<think>[\s\S]*?</think>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<thinking>[\s\S]*?</thinking>", "", text, flags=re.IGNORECASE)
return text.strip()
def vlm_models(self, backend: str, api_url: str) -> list:
backend = (backend or "ollama").lower()
try:
if backend == "ollama":
req = urllib.request.Request(api_url.rstrip("/") + "/api/tags")
with urllib.request.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":
key = self._unsloth_api_key()
if not key:
logger.error("vlm_models: UNSLOTH_API_KEY is not set")
return []
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:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["id"] for m in data.get("data", []))
except Exception as e:
logger.error("vlm_models: %s", e)
return []
def vlm_predict(self, image_b64: str, backend: str, api_url: str, model: str, prompt: str, max_tags: int = 40,
thinking_mode: bool = False, max_tokens: int = 0) -> dict:
backend = (backend or "ollama").lower()
try:
if backend == "ollama":
body = {
"model": model,
"messages": [{"role": "user", "content": prompt, "images": [image_b64]}],
"stream": False,
"think": bool(thinking_mode),
"options": {"temperature": 0.7, "num_ctx": 4096},
}
if max_tokens > 0:
body["options"]["num_predict"] = max_tokens
payload = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
api_url.rstrip("/") + "/api/chat",
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.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":
key = self._unsloth_api_key()
if not key:
return {"error": "UNSLOTH_API_KEY is not set. Copy .env.example to .env in the "
"plugin folder, fill in the key, and restart ComfyUI."}
headers["Authorization"] = f"Bearer {key}"
body = {
"model": model,
"messages": [{"role": "user", "content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
]}],
"stream": False,
}
if max_tokens > 0:
body["max_tokens"] = max_tokens
payload = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
api_url.rstrip("/") + "/v1/chat/completions",
data=payload,
headers=headers,
method="POST",
)
with urllib.request.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", "")
# Unslothはreasoningを別フィールドで返すため<think>タグに畳んで統一的に扱う
reasoning = message.get("reasoning_content")
if reasoning:
content = f"<think>{reasoning}</think>{content}"
if not thinking_mode:
content = self._strip_thinking_tags(content)
tags = [t.strip() for t in content.split(",") if t.strip()][:max_tags]
return {"tags": ", ".join(tags), "count": len(tags)}
except Exception as e:
logger.error("vlm_predict: %s", e)
return {"error": str(e)}
# ── ファイルメタデータ書込 ────────────────────────────────
_ALLOWED_WRITE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
def write_meta_to_file(self, image_path: str, tags: str) -> dict:
path = Path(image_path).resolve()
if path.suffix.lower() not in self._ALLOWED_WRITE_EXTS:
return {"error": "Unsupported file type"}
if not path.is_file():
return {"error": f"File not found: {image_path}"}
try:
import piexif
except ImportError:
piexif = None
try:
with Image.open(path) as img:
img.load()
ext = path.suffix.lower()
if ext in (".jpg", ".jpeg") and piexif:
self._write_jpeg(img, path, tags, piexif)
elif ext == ".png":
self._write_png(img, path, tags)
else:
self._write_sidecar(path, tags)
return {"ok": True}
except Exception as e:
logger.error("write_meta: %s", e)
return {"error": str(e)}
def _write_jpeg(self, img: Image.Image, path: Path, tags: str, piexif):
exif_data = img.info.get("exif")
if exif_data:
try:
exif_dict = piexif.load(exif_data)
except Exception:
exif_dict = {"0th": {}, "Exif": {}, "1st": {}, "GPS": {}, "Interop": {}}
else:
exif_dict = {"0th": {}, "Exif": {}, "1st": {}, "GPS": {}, "Interop": {}}
exif_dict["0th"][piexif.ImageIFD.ImageDescription] = tags.encode("utf-8")
exif_bytes = piexif.dump(exif_dict)
with tempfile.NamedTemporaryFile(delete=False, suffix=path.suffix) as tmp:
tmp_path = Path(tmp.name)
img.save(str(tmp_path), "JPEG", quality=95, exif=exif_bytes)
tmp_path.replace(path)
def _write_png(self, img: Image.Image, path: Path, tags: str):
meta = PngImagePlugin.PngInfo()
for k, v in img.info.items():
if isinstance(k, str) and isinstance(v, str):
meta.add_text(k, v)
meta.add_text("Tags", tags)
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
tmp_path = Path(tmp.name)
img.save(str(tmp_path), "PNG", pnginfo=meta)
tmp_path.replace(path)
def _write_sidecar(self, path: Path, tags: str):
sidecar = path.with_suffix(".tags.json")
with open(sidecar, "w", encoding="utf-8") as f:
json.dump({"tags": tags}, f, ensure_ascii=False, indent=2)
# ── バッチ処理 ────────────────────────────────────────────
def batch_status(self) -> dict:
s = self._batch_state
return {
"running": s["running"],
"total": s["total"],
"done": s["done"],
"log": s["log"][-50:],
}
def batch_stop(self):
self._batch_state["stop"] = True
def batch_start(self, folder: str, model_name: str, threshold: float, char_threshold: float,
use_ollama: bool, vlm_backend: str, vlm_api_url: str, ollama_model: str, ollama_prompt: str,
ollama_max_tags: int, save_db: bool, write_file: bool, write_txt: bool, db_service,
thinking_mode: bool = False, max_tokens: int = 0) -> dict:
if self._batch_state["running"]:
return {"error": "Batch already running"}
folder_path = Path(folder)
if not folder_path.is_dir():
return {"error": f"Folder not found: {folder}"}
exts = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
files = sorted(f for f in folder_path.iterdir() if f.is_file() and f.suffix.lower() in exts)
if not files:
return {"error": "No image files found"}
self._batch_state = {
"running": True, "total": len(files), "done": 0, "log": [], "stop": False,
}
def _run():
for fpath in files:
if self._batch_state["stop"]:
self._batch_state["log"].append("Stopped.")
break
try:
with Image.open(fpath) as img:
img.load()
buf = io.BytesIO()
img.save(buf, format="PNG")
b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
interrogator_tags = ""
if model_name:
res = self.predict(b64, model_name, threshold, char_threshold)
interrogator_tags = res.get("tags", "")
vlm_tags = ""
if use_ollama and ollama_model:
res2 = self.vlm_predict(b64, vlm_backend, vlm_api_url, ollama_model, ollama_prompt, ollama_max_tags,
thinking_mode, max_tokens)
vlm_tags = res2.get("tags", "")
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
if save_db:
db_service.save(str(fpath), interrogator_tags, vlm_tags)
if write_file and all_tags:
self.write_meta_to_file(str(fpath), all_tags)
if write_txt and all_tags:
txt_path = fpath.with_suffix(".txt")
with open(txt_path, "w", encoding="utf-8") as f:
f.write(all_tags)
n = len([t for t in all_tags.split(",") if t.strip()])
self._batch_state["log"].append(f"✓ {fpath.name}: {n} tags")
except Exception as e:
self._batch_state["log"].append(f"✗ {fpath.name}: {e}")
self._batch_state["done"] += 1
self._batch_state["running"] = False
threading.Thread(target=_run, daemon=True).start()
return {"ok": True, "total": len(files)}
# ── ユーティリティ ────────────────────────────────────────
@staticmethod
def _decode_b64(b64: str) -> Image.Image:
return Image.open(io.BytesIO(base64.b64decode(b64)))
+143
View File
@@ -0,0 +1,143 @@
"""Video tab plan file management service (JSON plan + optional PNG index thumbnail).
Duplicated from LabPlanService rather than shared — the two plan formats are
unrelated (batch keyframe columns vs. sequential timeline blocks) and would
gain nothing from a forced common base beyond coincidental line-count savings.
"""
import base64
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
logger = logging.getLogger(__name__)
class VideoPlanService:
def __init__(self, plan_dir: Path):
self.plan_dir = plan_dir
self.plan_dir.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# Path safety
# ------------------------------------------------------------------
def _safe_path(self, filename: str, ext: str = ".json") -> Path | None:
if not filename or not filename.strip():
return None
name = filename.strip()
if not name.endswith(ext):
name = name + ext
if "/" in name or "\\" in name or name in (".", "..") or "\x00" in name:
return None
resolved = (self.plan_dir / name).resolve()
plan_dir_resolved = self.plan_dir.resolve()
if resolved != plan_dir_resolved and not str(resolved).startswith(str(plan_dir_resolved) + "\\") and not str(resolved).startswith(str(plan_dir_resolved) + "/"):
return None
return resolved
def _now_iso(self) -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
# ------------------------------------------------------------------
# CRUD
# ------------------------------------------------------------------
def list_plans(self) -> list[dict]:
if not self.plan_dir.is_dir():
return []
result = []
for path in sorted(self.plan_dir.glob("*.json")):
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
logger.warning("Skipping unreadable video plan %s: %s", path.name, e)
continue
stem = path.stem
thumbnail = None
thumb_path = self.plan_dir / f"{stem}.png"
if thumb_path.is_file():
thumbnail = f"/wfm_data/video_plan/{stem}.png"
result.append({
"filename": path.name,
"name": data.get("name", stem),
"note": data.get("note", ""),
"block_count": len(data.get("blocks", [])),
"updated_at": data.get("updated_at", ""),
"thumbnail": thumbnail,
})
result.sort(key=lambda p: p.get("updated_at", ""), reverse=True)
return result
def get_plan(self, filename: str) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if not path.is_file():
raise FileNotFoundError(f"Plan not found: {filename}")
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def save_plan(self, filename: str, data: dict, index_image_base64: str | None = None) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
data = dict(data)
data["updated_at"] = self._now_iso()
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
if index_image_base64:
self.save_index_image(filename, index_image_base64)
return {"filename": path.name, "updated_at": data["updated_at"]}
def save_index_image(self, filename: str, image_base64: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
stem = path.stem
thumb_path = self.plan_dir / f"{stem}.png"
# Accept both raw base64 and data: URL forms
b64 = image_base64
if "," in b64 and b64.strip().lower().startswith("data:"):
b64 = b64.split(",", 1)[1]
image_bytes = base64.b64decode(b64)
with open(thumb_path, "wb") as f:
f.write(image_bytes)
def save_index_image_to_output(self, image_base64: str, filename_prefix: str = "Video_index") -> dict:
"""Saves the contact-sheet index image into ComfyUI's own output folder,
alongside the videos generated during the run (unlike save_index_image,
which saves it next to the plan file in plan_dir)."""
b64 = image_base64
if "," in b64 and b64.strip().lower().startswith("data:"):
b64 = b64.split(",", 1)[1]
image_bytes = base64.b64decode(b64)
import folder_paths # type: ignore
output_dir = folder_paths.get_output_directory()
full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
save_name = f"{filename}_{counter:05}_.png"
save_path = Path(full_output_folder) / save_name
save_path.write_bytes(image_bytes)
return {"filename": save_name, "subfolder": subfolder}
def delete_plan(self, filename: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if path.is_file():
path.unlink()
thumb_path = self.plan_dir / f"{path.stem}.png"
if thumb_path.is_file():
thumb_path.unlink()
+127
View File
@@ -0,0 +1,127 @@
"""Video tab utilities: last-frame capture and animated GIF conversion.
Runs entirely on dependencies ComfyUI itself already requires — PyAV for
decoding (ComfyUI core already needs av>=17.0.0) and Pillow for GIF encoding
— so no ffmpeg binary and no new pip installs, unlike a typical ffmpeg-based
implementation (e.g. Eagle's video2gif/video-to-frame plugins).
"""
import base64
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
try:
from PIL import Image
_RESAMPLE = getattr(getattr(Image, "Resampling", Image), "LANCZOS")
except Exception: # pragma: no cover - Pillow is a hard ComfyUI dependency
_RESAMPLE = None
class VideoService:
def _resolve_media_path(self, filename: str, subfolder: str, type_: str) -> Path:
"""Resolves a ComfyUI-style {filename, subfolder, type} reference to an
absolute path, guarding against path traversal outside the matching
input/output/temp directory."""
import folder_paths # type: ignore
base_dir = folder_paths.get_directory_by_type(type_)
if not base_dir:
raise ValueError(f"Invalid type: {type_}")
base = Path(base_dir).resolve()
target = (base / (subfolder or "") / filename).resolve()
try:
target.relative_to(base)
except ValueError:
raise ValueError("Access denied: path outside allowed directory")
if not target.is_file():
raise FileNotFoundError(f"File not found: {filename}")
return target
def save_frame_to_output(self, image_base64: str, filename_prefix: str = "video/Frame") -> dict:
"""Saves a client-captured video frame (PNG data URL) into ComfyUI's own
output folder — same auto-numbered pattern as Lab's index-image save
(see LabPlanService.save_index_image_to_output)."""
import folder_paths # type: ignore
b64 = image_base64
if "," in b64 and b64.strip().lower().startswith("data:"):
b64 = b64.split(",", 1)[1]
image_bytes = base64.b64decode(b64)
output_dir = folder_paths.get_output_directory()
full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
save_name = f"{filename}_{counter:05}_.png"
save_path = Path(full_output_folder) / save_name
save_path.write_bytes(image_bytes)
return {"filename": save_name, "subfolder": subfolder}
def convert_to_gif(
self,
filename: str,
subfolder: str,
type_: str,
start_time: float = 0.0,
end_time=None,
fps: float = 10.0,
max_width=None,
filename_prefix: str = "video/GIF",
) -> dict:
"""Decodes the given video (PyAV), samples it down to `fps`, optionally
downscales to `max_width`, and encodes the result as an animated GIF
(Pillow) into ComfyUI's own output folder."""
import av # type: ignore
import folder_paths # type: ignore
if _RESAMPLE is None:
raise RuntimeError("Pillow is not available")
src_path = self._resolve_media_path(filename, subfolder, type_)
fps = max(0.1, float(fps))
container = av.open(str(src_path))
try:
stream = container.streams.video[0]
source_fps = float(stream.average_rate) if stream.average_rate else 24.0
step = max(1, round(source_fps / fps))
pil_frames = []
idx = 0
for frame in container.decode(stream):
t = float(frame.pts * stream.time_base) if frame.pts is not None else None
if t is not None:
if t < start_time:
idx += 1
continue
if end_time is not None and t > end_time:
break
if idx % step == 0:
im = frame.to_image()
if max_width and im.width > max_width:
ratio = max_width / im.width
im = im.resize((max_width, max(1, round(im.height * ratio))), _RESAMPLE)
pil_frames.append(im.convert("RGB"))
idx += 1
finally:
container.close()
if not pil_frames:
raise ValueError("No frames found in the specified range")
output_dir = folder_paths.get_output_directory()
full_output_folder, out_filename, counter, out_subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
save_name = f"{out_filename}_{counter:05}_.gif"
save_path = Path(full_output_folder) / save_name
duration_ms = max(20, round(1000 / fps))
pil_frames[0].save(
save_path,
format="GIF",
save_all=True,
append_images=pil_frames[1:],
duration=duration_ms,
loop=0,
optimize=True,
)
return {"filename": save_name, "subfolder": out_subfolder, "frame_count": len(pil_frames)}
+205
View File
@@ -0,0 +1,205 @@
"""Wildcard file management service."""
import logging
import os
import platform
import shutil
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
ALLOWED_EXTS = {"txt", "yaml", "yml"}
class WildcardService:
def __init__(self, wildcard_dir: Path):
self.wildcard_dir = wildcard_dir
# Only mkdir if it is a real directory (not a junction/symlink)
if not self.wildcard_dir.exists() and not self._is_junction(self.wildcard_dir):
self.wildcard_dir.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------------
# File CRUD
# ------------------------------------------------------------------
def list_wildcards(self) -> list[dict]:
"""Return sorted list of wildcard files recursively (follows junction/symlink)."""
if not self.wildcard_dir.exists():
return []
files = []
for path in sorted(self.wildcard_dir.rglob("*")):
if path.is_file() and path.suffix.lstrip(".").lower() in ALLOWED_EXTS:
rel = path.relative_to(self.wildcard_dir)
dir_posix = rel.parent.as_posix()
if dir_posix == ".":
dir_posix = ""
files.append({
"name": path.stem,
"filename": rel.as_posix(),
"ext": path.suffix.lstrip(".").lower(),
"size": path.stat().st_size,
"dir": dir_posix,
"wc_name": rel.with_suffix("").as_posix(),
})
return files
def get_content(self, filename: str) -> str:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if not path.is_file():
raise FileNotFoundError(f"File not found: {filename}")
return path.read_text(encoding="utf-8")
def save_file(self, filename: str, content: str) -> dict:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
rel = path.relative_to(self.wildcard_dir)
dir_posix = rel.parent.as_posix()
if dir_posix == ".":
dir_posix = ""
return {
"name": path.stem,
"filename": rel.as_posix(),
"ext": path.suffix.lstrip(".").lower(),
"size": path.stat().st_size,
"dir": dir_posix,
"wc_name": rel.with_suffix("").as_posix(),
}
def delete_file(self, filename: str) -> None:
path = self._safe_path(filename)
if path is None:
raise ValueError(f"Invalid filename: {filename}")
if path.is_file():
path.unlink()
def _safe_path(self, filename: str) -> Path | None:
if not filename or not filename.strip():
return None
# Normalize to forward slashes and strip leading/trailing slashes
filename = filename.replace("\\", "/").strip("/")
# Validate each path component — block traversal and empty parts
parts = filename.split("/")
for p in parts:
if not p or p == ".." or p == ".":
return None
ext = Path(parts[-1]).suffix.lstrip(".").lower()
if ext not in ALLOWED_EXTS:
return None
return self.wildcard_dir.joinpath(*parts)
# ------------------------------------------------------------------
# Impact Pack integration
# ------------------------------------------------------------------
@staticmethod
def find_impact_pack_wildcards(comfyui_root: Path) -> Path | None:
"""Return Impact Pack wildcards directory path, or None if not installed."""
custom_nodes = comfyui_root / "custom_nodes"
if not custom_nodes.is_dir():
return None
for d in custom_nodes.iterdir():
if d.is_dir() and "impact-pack" in d.name.lower():
wildcards = d / "wildcards"
if wildcards.is_dir():
return wildcards
return None
def get_link_status(self, comfyui_root: Path) -> dict:
"""Return current Impact Pack integration status."""
impact_dir = self.find_impact_pack_wildcards(comfyui_root)
is_linked = self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink()
resolved_target = None
if is_linked:
try:
resolved_target = str(self.wildcard_dir.resolve())
except Exception:
pass
return {
"impact_pack_installed": impact_dir is not None,
"impact_pack_wildcards_dir": str(impact_dir) if impact_dir else None,
"wfs_wildcard_dir": str(self.wildcard_dir),
"is_linked": is_linked,
"link_target": resolved_target,
}
def create_link(self, comfyui_root: Path) -> dict:
"""Replace WFS wildcard dir with a junction/symlink → Impact Pack wildcards."""
impact_dir = self.find_impact_pack_wildcards(comfyui_root)
if impact_dir is None:
raise RuntimeError("ComfyUI-Impact-Pack is not installed.")
if self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink():
raise RuntimeError("Link already exists.")
# Migrate existing WFS files to Impact Pack dir
migrated: list[str] = []
if self.wildcard_dir.is_dir():
for f in self.wildcard_dir.iterdir():
if f.is_file():
dest = impact_dir / f.name
if not dest.exists():
shutil.copy2(str(f), str(dest))
migrated.append(f.name)
shutil.rmtree(str(self.wildcard_dir))
# Create junction (Windows) or symlink (others)
self._create_junction_or_symlink(self.wildcard_dir, impact_dir)
logger.info("Wildcard link created: %s -> %s", self.wildcard_dir, impact_dir)
return {"migrated_files": migrated}
def remove_link(self) -> None:
"""Remove junction/symlink and restore WFS wildcard dir as a plain directory."""
if not (self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink()):
raise RuntimeError("No link to remove.")
self._remove_junction_or_symlink(self.wildcard_dir)
self.wildcard_dir.mkdir(parents=True, exist_ok=True)
logger.info("Wildcard link removed, restored plain dir: %s", self.wildcard_dir)
# ------------------------------------------------------------------
# Platform helpers
# ------------------------------------------------------------------
@staticmethod
def _is_junction(path: Path) -> bool:
"""Return True if path is a Windows directory junction."""
if platform.system() != "Windows":
return False
try:
import ctypes
FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
attrs = ctypes.windll.kernel32.GetFileAttributesW(str(path))
return attrs != 0xFFFFFFFF and bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
except Exception:
return False
@staticmethod
def _create_junction_or_symlink(link: Path, target: Path) -> None:
if platform.system() == "Windows":
result = subprocess.run(
["cmd", "/c", "mklink", "/J", str(link), str(target)],
capture_output=True, text=True,
)
if result.returncode != 0:
raise RuntimeError(f"mklink /J failed: {result.stderr.strip()}")
else:
os.symlink(target, link, target_is_directory=True)
@staticmethod
def _remove_junction_or_symlink(path: Path) -> None:
if platform.system() == "Windows":
result = subprocess.run(
["cmd", "/c", "rmdir", str(path)],
capture_output=True, text=True,
)
if result.returncode != 0:
raise RuntimeError(f"rmdir failed: {result.stderr.strip()}")
else:
os.unlink(str(path))
+122 -27
View File
@@ -3,6 +3,35 @@
import os
import re
# プロンプトを直接持つノードタイプ(CLIPTextEncode以外の複合ノード含む)
_PROMPT_NODE_TYPES = {
"CLIPTextEncode", "CLIPTextEncodeSDXL", "CLIPTextEncodeSDXLRefiner",
"CLIPTextEncodeEditPlus", "TextEncodeQwenImageEditPlus", "TextEncodeMageFlowEdit",
"SDXLPromptStyler", "SDXLPromptStylerAdvanced", "ImageMetadataPromptLoader",
"WFS_PromptText", "ImpactWildcardEncode", "ImpactWildcardProcessor",
}
# 画像を最終出力として保存するノードタイプ
_OUTPUT_IMAGE_NODE_TYPES = {"SaveImage", "SaveImageAdvanced"}
# CLIPLoader / DualCLIPLoader の type フィールド → モデル種別マッピング
_CLIP_TYPE_TO_MODEL = {
"flux": "Flux",
"flux2": "Flux2",
"newbie": "NewBie",
"ovis": "Ovis",
"qwen_image": "Qwen",
"sd3": "SD3",
"sd3.5": "SD3",
"hidream_i": "HiDream",
"hidream_e": "HiDream",
"hidream": "HiDream",
"wan": "Wan",
"cosmos": "Cosmos",
"lumina": "Lumina",
"lumina2": "Z-IMAGE",
}
def _model_name_from_ui_node(node):
"""Extract model filename from UI format node (lowercase)."""
@@ -11,16 +40,65 @@ def _model_name_from_ui_node(node):
return val.lower() if isinstance(val, str) else ""
def _clip_type_from_ui_node(node):
"""Extract CLIPLoader type string from widgets_values (lowercase)."""
ntype = node.get("type", "")
vals = node.get("widgets_values", [])
if ntype == "CLIPLoader" and len(vals) > 1:
return str(vals[1]).lower() if isinstance(vals[1], str) else ""
if ntype in ("DualCLIPLoader", "TripleCLIPLoader") and len(vals) > 2:
return str(vals[2]).lower() if isinstance(vals[2], str) else ""
return ""
def _model_name_from_api_node(node):
"""Extract model filename from API format node (lowercase)."""
inputs = node.get("inputs", {})
for key in ("ckpt_name", "unet_name", "model_name"):
for key in ("ckpt_name", "unet_name", "model_name", "clip_name1", "clip_name"):
val = inputs.get(key, "")
if isinstance(val, str) and val:
return val.lower()
return ""
def _collect_all_ui_nodes(workflow_data):
"""Yield all UI-format nodes including those inside definitions.subgraphs."""
for node in workflow_data.get("nodes", []):
yield node
defs = workflow_data.get("definitions", {})
if isinstance(defs, dict):
for sg in defs.get("subgraphs", []):
if isinstance(sg, dict):
for node in sg.get("nodes", []):
yield node
def _detect_model_type_from_name(mn_base, model_types):
"""Detect model type from a model filename (already lowercased basename)."""
if re.search(r"sd1[._-]?5|v1[._-]5", mn_base):
model_types.add("SD1.5")
elif re.search(r"sdxl|[._-]xl[._-]|[._-]xl$|xl[._-]", mn_base):
model_types.add("SDXL")
elif re.search(r"flux[-_.]?2", mn_base):
model_types.add("Flux2")
elif "flux" in mn_base:
model_types.add("Flux")
elif re.search(r"sd[._-]?3", mn_base):
model_types.add("SD3")
elif "qwen" in mn_base:
model_types.add("Qwen")
elif "zimage" in mn_base or "z-image" in mn_base or "zit" in mn_base:
model_types.add("Z-IMAGE")
elif "newbie" in mn_base:
model_types.add("NewBie")
elif "ovis" in mn_base:
model_types.add("Ovis")
elif "hidream" in mn_base:
model_types.add("HiDream")
elif "wan" in mn_base and re.search(r"wan[-_.]?\d|wan[-_]video", mn_base):
model_types.add("Wan")
def analyze_workflow(workflow_data, filename=""):
"""Analyze workflow JSON and return model types, input/output node counts."""
model_types = set()
@@ -36,23 +114,33 @@ def analyze_workflow(workflow_data, filename=""):
model_types.add("Qwen")
if "zimage" in fn or "z-image" in fn or "zit" in fn:
model_types.add("Z-IMAGE")
if "flux2" in fn:
if re.search(r"flux[-_.]?2", fn):
model_types.add("Flux2")
elif "flux" in fn:
model_types.add("Flux")
if "sd3" in fn:
model_types.add("SD3")
if "newbie" in fn:
model_types.add("NewBie")
if "ovis" in fn:
model_types.add("Ovis")
if "hidream" in fn:
model_types.add("HiDream")
if "wan" in fn and re.search(r"wan[-_.]?\d|wan[-_]video", fn):
model_types.add("Wan")
# Support both UI format (nodes array) and API format (node ID object)
raw_nodes = workflow_data.get("nodes", None)
if raw_nodes is not None:
# UI / app format: collect all nodes including subgraph definitions
node_iter = [
(
node.get("type", ""),
node.get("title", "").lower(),
_model_name_from_ui_node(node),
_clip_type_from_ui_node(node),
)
for node in raw_nodes
for node in _collect_all_ui_nodes(workflow_data)
]
else:
node_iter = []
@@ -62,33 +150,32 @@ def analyze_workflow(workflow_data, filename=""):
ntype = node.get("class_type", "")
title = node.get("_meta", {}).get("title", "").lower()
mn = _model_name_from_api_node(node)
node_iter.append((ntype, title, mn))
node_iter.append((ntype, title, mn, ""))
for ntype, title, mn in node_iter:
for ntype, title, mn, clip_type in node_iter:
if (
"CheckpointLoader" in ntype
or "UNETLoader" in ntype
or "UnetLoader" in ntype # UnetLoaderGGUF 等を含む
or "unet_name" in ntype
):
mn_base = os.path.basename(mn.replace("\\", "/"))
if re.search(r"sd1[._-]?5|v1[._-]5", mn_base):
model_types.add("SD1.5")
elif re.search(r"sdxl|[._-]xl[._-]|[._-]xl$|xl[._-]", mn_base):
model_types.add("SDXL")
elif "flux2" in mn_base:
model_types.add("Flux2")
elif "flux" in mn_base:
model_types.add("Flux")
elif re.search(r"sd[._-]?3", mn_base):
model_types.add("SD3")
elif "qwen" in mn_base:
model_types.add("Qwen")
elif "zimage" in mn_base or "z-image" in mn_base or "zit" in mn_base:
model_types.add("Z-IMAGE")
_detect_model_type_from_name(mn_base, model_types)
# CLIPLoader 系: type フィールドまたはファイル名からモデル種別を検出
# QuadrupleCLIPLoader 等、type フィールドを持たない新型ローダーにも対応
if "CLIPLoader" in ntype:
if clip_type:
detected = _CLIP_TYPE_TO_MODEL.get(clip_type)
if detected:
model_types.add(detected)
mn_base = os.path.basename(mn.replace("\\", "/"))
if mn_base:
_detect_model_type_from_name(mn_base, model_types)
if "sdxl" in title:
model_types.add("SDXL")
if "flux2" in title:
if re.search(r"flux[-_.]?2", title):
model_types.add("Flux2")
elif "flux" in title:
model_types.add("Flux")
@@ -98,26 +185,34 @@ def analyze_workflow(workflow_data, filename=""):
model_types.add("Qwen")
if "zimage" in title or "z-image" in title or "zit" in title:
model_types.add("Z-IMAGE")
if "newbie" in title:
model_types.add("NewBie")
if "ovis" in title:
model_types.add("Ovis")
if "hidream" in title:
model_types.add("HiDream")
if ntype == "CLIPTextEncode" or "prompt" in title:
if ntype in _PROMPT_NODE_TYPES or "prompt" in title:
inputs["prompts"] += 1
if ntype in ("LoadImage", "LoadImageMask"):
inputs["images"] += 1
if ntype == "LoadVideo" or "load video" in title:
inputs["videos"] += 1
if ntype == "SaveImage":
if ntype in _OUTPUT_IMAGE_NODE_TYPES:
outputs["images"] += 1
if ntype in ("SaveVideo", "VH_VideoCombine"):
outputs["videos"] += 1
# Detect workflow format
if raw_nodes is not None:
# App format: UI-based structure with definitions (subgraphs) or linearMode
# App format: simplified web-app-style UI (linearMode) or .app.json filename.
# A workflow that merely *contains* subgraphs (definitions.subgraphs) is still a
# normal node graph (comfyui-workflow.js's convertUiToApi flattens subgraphs before
# conversion), so it's treated as "ui" here too — must match detectFormat() in
# static/js/comfyui-workflow.js or the App/UI badge shown to the user disagrees
# with what GenerateUI actually does with the file.
extra = workflow_data.get("extra", {})
if (
"definitions" in workflow_data
or extra.get("linearMode") is True
):
if extra.get("linearMode") is True:
wf_format = "app"
elif filename and filename.lower().endswith(".app.json"):
wf_format = "app"
+47 -2
View File
@@ -4,7 +4,7 @@ import jinja2
from aiohttp import web
from pathlib import Path
from .config import TEMPLATES_DIR, STATIC_DIR, DATA_DIR, WORKFLOWS_DIR
from .config import TEMPLATES_DIR, STATIC_DIR, DATA_DIR, WORKFLOWS_DIR, LAB_PLAN_DIR, VIDEO_PLAN_DIR
logger = logging.getLogger(__name__)
@@ -41,6 +41,38 @@ async def serve_workflow_file(request: web.Request) -> web.Response:
})
async def serve_lab_plan_file(request: web.Request) -> web.Response:
"""Serve files (index thumbnails) from the Lab plan directory."""
filename = request.match_info.get("filename", "")
if not filename or ".." in filename or "/" in filename or "\\" in filename:
return web.Response(status=404)
file_path = LAB_PLAN_DIR / filename
if not file_path.is_file():
return web.Response(status=404)
content_type, _ = mimetypes.guess_type(str(file_path))
return web.FileResponse(file_path, headers={
"Content-Type": content_type or "application/octet-stream",
})
async def serve_video_plan_file(request: web.Request) -> web.Response:
"""Serve files (index thumbnails) from the Video plan directory."""
filename = request.match_info.get("filename", "")
if not filename or ".." in filename or "/" in filename or "\\" in filename:
return web.Response(status=404)
file_path = VIDEO_PLAN_DIR / filename
if not file_path.is_file():
return web.Response(status=404)
content_type, _ = mimetypes.guess_type(str(file_path))
return web.FileResponse(file_path, headers={
"Content-Type": content_type or "application/octet-stream",
})
class WorkflowStudio:
"""Main entry point for Workflow Studio plugin."""
@@ -57,19 +89,32 @@ class WorkflowStudio:
# Dynamic workflow file serving (thumbnails etc.)
app.router.add_get("/wfm_data/workflows/{filename}", serve_workflow_file)
# Dynamic Lab plan file serving (index thumbnails)
app.router.add_get("/wfm_data/lab_plan/{filename}", serve_lab_plan_file)
# Dynamic Video plan file serving (index thumbnails)
app.router.add_get("/wfm_data/video_plan/{filename}", serve_video_plan_file)
# Main page
app.router.add_get("/wfm", serve_index_page)
# API routes
from .routes import workflow_routes, settings_routes, ollama_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes
from .routes import workflow_routes, settings_routes, ollama_routes, unsloth_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes, wildcard_routes, tagger_routes, gmic_routes, skill_routes, lab_routes, video_routes
workflow_routes.setup_routes(app)
settings_routes.setup_routes(app)
ollama_routes.setup_routes(app)
unsloth_routes.setup_routes(app)
eagle_routes.setup_routes(app)
nodes_routes.setup_routes(app)
prompts_routes.setup_routes(app)
models_routes.setup_routes(app)
gallery_routes.setup_routes(app)
wildcard_routes.setup_routes(app)
tagger_routes.setup_routes(app)
gmic_routes.setup_routes(app)
skill_routes.setup_routes(app)
lab_routes.setup_routes(app)
video_routes.setup_routes(app)
logger.info("Workflow Studio: Routes registered successfully")
+5 -5
View File
@@ -1,8 +1,8 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow management and generation UI plugin for ComfyUI. Browse, organize, and execute workflows from a dedicated studio interface."
version = "0.2.7"
license = "MIT"
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.6.2"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
@@ -10,7 +10,7 @@ dependencies = ["jinja2"]
Repository = "https://github.com/ketle-man/ComfyUI-Workflow-Studio"
[tool.comfy]
PublisherId = "ketle-man"
PublisherId = "statsu"
DisplayName = "Workflow Studio"
Icon = "https://raw.githubusercontent.com/ketle-man/ComfyUI-Workflow-Studio/main/assets/icon.svg"
Icon = "https://raw.githubusercontent.com/ketle-man/ComfyUI-Workflow-Studio/main/docs/thumb.png"
Banner = "https://raw.githubusercontent.com/ketle-man/ComfyUI-Workflow-Studio/main/assets/banner.svg"
+35
View File
@@ -0,0 +1,35 @@
# ComfyUI-Workflow-Studio - Tagger tab dependencies
#
# numpy and Pillow are already bundled with ComfyUI and do not need to be installed.
# torch is managed by ComfyUI and must NOT be pinned here.
#
# Install into ComfyUI's embedded Python:
# python_embeded\python.exe -m pip install -r requirements.txt
#
# For GPU-accelerated ONNX inference, install onnxruntime-gpu instead of onnxruntime:
# python_embeded\python.exe -m pip install onnxruntime-gpu
# -- Required for WD Tagger / SwinV2 ONNX inference --
onnxruntime>=1.16
# -- Required for JPEG EXIF tag writing --
piexif>=1.1.3
# -- Optional: DeepDanbooru (.h5 model) support --
# Omit if you do not use DeepDanbooru models.
# TensorFlow is large (~600MB) and conflicts with some CUDA setups.
# tensorflow>=2.10
# -- Required to load UNSLOTH_API_KEY from a local .env file (Unsloth backend, AI TOOL tab) --
python-dotenv>=1.0,<2.0
# -- Multi-layer PSD export (Gallery tab bulk action) --
# Pure-Python, ships prebuilt wheels (no C compiler required on Windows).
psd-tools>=1.10
# -- MP4 thumbnail generation (Gallery tab) --
# Uses PyAV (av) to decode the first frame. ComfyUI core already requires av>=17.0.0,
# so it is normally pre-installed in python_embeded and no action is needed here.
# If missing, mp4 thumbnail generation simply fails and falls back to a placeholder
# (Gallery itself keeps working). Not pinned here on purpose — see torch note above.
# av>=17.0.0
+392 -1
View File
@@ -2,11 +2,45 @@
Gallery Tab Styles
============================================================ */
/* ── サブタブ (Output / Style-Prompt) ──────────────────────── */
.wfm-gallery-subtab-nav {
display: flex;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
}
.wfm-gallery-subtab-btn {
padding: 6px 16px;
font-size: 12px;
background: transparent;
border: none;
color: var(--wfm-text-secondary);
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
transition: color 0.15s;
}
.wfm-gallery-subtab-btn:hover { color: var(--wfm-text-primary); }
.wfm-gallery-subtab-btn.active { color: var(--wfm-primary); border-bottom-color: var(--wfm-primary); }
.wfm-gallery-panel {
display: none;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.wfm-gallery-panel.active { display: flex; }
/* ── 3カラムレイアウト ──────────────────────────────────────── */
.wfm-gallery-layout {
display: flex;
height: calc(100vh - var(--wfm-header-height, 96px));
flex: 1;
min-height: 0;
overflow: hidden;
gap: 0;
}
@@ -27,10 +61,12 @@
.wfm-gallery-tree-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 8px;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
background: var(--wfm-bg-primary, #16213e);
gap: 4px;
}
.wfm-gallery-tree-title {
@@ -39,6 +75,13 @@
color: var(--wfm-text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
flex: 1;
}
.wfm-gallery-tree-actions {
display: flex;
gap: 4px;
flex-shrink: 0;
}
@@ -210,6 +253,61 @@
color: #fbbf24;
}
/* Feederグループボタン(サムネイルカード左上) */
.wfm-gallery-thumb-feeder-btn {
position: absolute;
top: 4px;
left: 4px;
background: rgba(0,0,0,0.5);
border: none;
border-radius: 50%;
width: 24px;
height: 24px;
font-size: 11px;
font-weight: bold;
line-height: 1;
padding: 0;
cursor: pointer;
color: rgba(255,255,255,0.6);
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.15s, color 0.15s;
}
.wfm-gallery-thumb-card:hover .wfm-gallery-thumb-feeder-btn {
opacity: 1;
}
.wfm-gallery-thumb-feeder-btn.active {
color: #38bdf8;
opacity: 1;
}
.wfm-gallery-thumb-feeder-btn:hover {
background: rgba(0,0,0,0.75);
color: #38bdf8;
}
/* 動画ファイル(mp4)の再生アイコンバッジ(サムネイル中央) */
.wfm-gallery-thumb-video-badge {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 36px;
height: 36px;
border-radius: 50%;
background: rgba(0,0,0,0.55);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
pointer-events: none;
}
/* テーブルビューのお気に入りボタン */
.wfm-gallery-table-fav-btn {
background: none;
@@ -369,6 +467,15 @@
flex-shrink: 0;
}
.wfm-gallery-preview-wrapper {
position: relative;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.wfm-gallery-detail-img {
max-width: 100%;
max-height: 200px;
@@ -407,6 +514,20 @@
white-space: nowrap;
}
.wfm-gallery-image-prompt-text {
font-size: 12px;
color: var(--wfm-text-primary);
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
background: var(--wfm-bg-primary, #16213e);
border: 1px solid var(--wfm-border);
border-radius: 4px;
padding: 6px 8px;
max-height: 160px;
overflow-y: auto;
}
.wfm-gallery-tags-display {
display: flex;
flex-wrap: wrap;
@@ -592,3 +713,273 @@
.wfm-gallery-lightbox-close:hover {
background: rgba(255,255,255,0.2);
}
/* ── 画像比較ライトボックス ──────────────────────────────────── */
.wfm-lightbox-compare .wfm-lightbox-compare-inner {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
max-width: 96vw;
max-height: 92vh;
overflow: auto;
}
.wfm-lightbox-compare-grid {
display: grid;
grid-template-columns: repeat(var(--compare-cols, 2), 1fr);
gap: 12px;
padding: 16px;
}
.wfm-lightbox-compare-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
}
.wfm-lightbox-compare-img {
max-width: calc(92vw / var(--compare-cols, 2) - 12px);
max-height: 78vh;
object-fit: contain;
border-radius: 4px;
cursor: default;
}
.wfm-lightbox-compare-label {
color: rgba(255,255,255,0.75);
font-size: 12px;
text-align: center;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-lightbox-compare-close {
position: fixed;
top: 16px;
right: 16px;
z-index: 10001;
}
/* ── 詳細パネル アクションボタン行 ───────────────────────────── */
.wfm-gallery-detail-action-row {
display: flex;
gap: 6px;
padding: 4px 8px;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
flex-wrap: wrap;
}
/* ── 詳細パネル アクションボタン ─────────────────────────────── */
.wfm-gallery-action-btn {
padding: 4px 10px;
border-radius: 4px;
border: 1px solid;
cursor: pointer;
font-size: 12px;
white-space: nowrap;
align-self: center;
margin: 2px 3px;
color: #fff;
}
.wfm-gallery-action-btn-green {
background: var(--wfm-success, #22c55e);
border-color: var(--wfm-success, #22c55e);
}
.wfm-gallery-action-btn-green:hover {
background: #16a34a;
border-color: #16a34a;
}
.wfm-gallery-action-btn-primary {
background: var(--wfm-primary);
border-color: var(--wfm-primary);
}
.wfm-gallery-action-btn-primary:hover {
background: var(--wfm-primary-hover);
border-color: var(--wfm-primary-hover);
}
.wfm-gallery-action-btn-tagger {
background: var(--wfm-accent, #7c5cfc);
border-color: var(--wfm-accent, #7c5cfc);
}
.wfm-gallery-action-btn-tagger:hover {
background: #6a4de0;
border-color: #6a4de0;
}
.wfm-gallery-action-btn-orange {
background: #f59e0b;
border-color: #f59e0b;
color: #1a1a2e;
}
.wfm-gallery-action-btn-orange:hover {
background: #d97f06;
border-color: #d97f06;
}
/* ── ファイル操作ボタン (詳細パネル) ─────────────────────────── */
.wfm-gallery-file-actions {
display: flex;
gap: 6px;
padding-top: 4px;
}
.wfm-gallery-file-actions .wfm-btn {
flex: 1;
}
/* ── 移動先選択モーダル ──────────────────────────────────────── */
.wfm-gallery-move-modal {
background: var(--wfm-bg-primary, #16213e);
border: 1px solid var(--wfm-border);
border-radius: 8px;
padding: 20px;
min-width: 320px;
max-width: 480px;
width: 90%;
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
display: flex;
flex-direction: column;
gap: 12px;
}
.wfm-gallery-move-modal-title {
font-size: 14px;
font-weight: 600;
color: var(--wfm-text-primary);
}
.wfm-gallery-move-dest-sel {
width: 100%;
padding: 6px 8px;
font-size: 13px;
}
.wfm-gallery-move-modal-footer {
display: flex;
gap: 8px;
justify-content: flex-end;
}
/* ============================================================
ImagePrompt / Style_Catalog ギャラリー (右ペイン)
============================================================ */
.wfm-imageprompt-detail-panel {
width: 520px;
min-width: 520px;
max-width: 520px;
flex-direction: row;
overflow: hidden;
}
.wfm-imageprompt-detail-col {
display: flex;
flex-direction: column;
min-width: 0;
}
.wfm-imageprompt-detail-col-left {
width: 280px;
min-width: 280px;
max-width: 280px;
overflow-y: auto;
border-right: 1px solid var(--wfm-border);
padding-bottom: 8px;
}
.wfm-imageprompt-detail-col-right {
flex: 1;
min-width: 0;
padding: 8px 10px;
}
.wfm-imageprompt-section {
padding: 8px 10px;
}
.wfm-imageprompt-prompt-box {
width: 100%;
resize: vertical;
font-size: 12px;
padding: 6px 8px;
background: var(--wfm-bg-primary, #16213e);
border: 1px solid var(--wfm-border);
border-radius: 4px;
color: var(--wfm-text-primary);
box-sizing: border-box;
}
.wfm-imageprompt-btn-row {
display: flex;
gap: 6px;
margin-top: 6px;
}
.wfm-imageprompt-btn-row .wfm-btn {
flex: 1;
}
.wfm-imageprompt-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 6px;
min-height: 24px;
}
.wfm-imageprompt-chip {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
background: rgba(79,142,247,0.15);
color: var(--wfm-accent, #4f8ef7);
border: 1px solid rgba(79,142,247,0.3);
border-radius: 10px;
padding: 2px 4px 2px 8px;
font-size: 11px;
}
.wfm-imageprompt-chip-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 220px;
}
.wfm-imageprompt-chip-remove {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 0 2px;
font-size: 13px;
line-height: 1;
opacity: 0.7;
}
.wfm-imageprompt-chip-remove:hover { opacity: 1; }
.wfm-imageprompt-final-section {
height: 100%;
}
.wfm-imageprompt-final-textarea {
margin-top: 4px;
flex: 1;
min-height: 0;
resize: none;
}
+468
View File
@@ -0,0 +1,468 @@
/* =============================================
Image Edit Tab
============================================= */
#wfm-tab-image-edit {
padding: 0;
overflow: hidden;
}
.ie-editor {
display: flex;
height: 100%;
overflow: hidden;
background: var(--wfm-bg);
}
/* =============================================
Left Toolbar
============================================= */
.ie-toolbar {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 8px 5px;
background: var(--wfm-surface);
border-right: 1px solid var(--wfm-border);
width: 46px;
flex-shrink: 0;
}
.ie-tool-btn {
width: 34px;
height: 34px;
border: 1px solid transparent;
background: transparent;
border-radius: 6px;
cursor: pointer;
font-size: 15px;
font-weight: 600;
color: var(--wfm-text);
display: flex;
align-items: center;
justify-content: center;
transition: background 0.12s, border-color 0.12s;
user-select: none;
position: relative;
}
.ie-tool-btn:hover {
background: var(--wfm-surface-hover);
border-color: var(--wfm-border);
}
.ie-tool-btn.active {
background: var(--wfm-primary);
border-color: var(--wfm-primary);
color: #fff;
}
.ie-tool-placeholder {
opacity: 0.38;
}
.ie-tool-placeholder::after {
content: "";
position: absolute;
bottom: 3px;
right: 3px;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--wfm-text-secondary);
opacity: 0.5;
}
/* =============================================
Center column
============================================= */
.ie-center {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
min-width: 0;
}
/* Action bar */
.ie-action-bar {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border-bottom: 1px solid var(--wfm-border);
background: var(--wfm-surface);
flex-shrink: 0;
flex-wrap: wrap;
}
/* Tool options bar */
.ie-tool-options {
display: flex;
align-items: center;
gap: 14px;
padding: 5px 10px;
border-bottom: 1px solid var(--wfm-border);
background: var(--wfm-surface);
flex-shrink: 0;
flex-wrap: wrap;
min-height: 36px;
font-size: 12px;
}
.ie-opt-group {
display: flex;
align-items: center;
gap: 5px;
}
.ie-opt-group label {
color: var(--wfm-text-secondary);
white-space: nowrap;
}
.ie-opt-select {
font-size: 12px;
padding: 2px 5px;
background: var(--wfm-surface);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
cursor: pointer;
}
.ie-opt-input {
font-size: 12px;
padding: 2px 5px;
background: var(--wfm-surface);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
}
.ie-opt-active {
background: var(--wfm-primary) !important;
color: #fff !important;
border-color: var(--wfm-primary) !important;
}
/* Canvas wrap */
.ie-canvas-wrap {
flex: 1;
overflow: hidden;
position: relative;
background: #1a1a1a;
background-image:
linear-gradient(45deg, #222 25%, transparent 25%),
linear-gradient(-45deg, #222 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #222 75%),
linear-gradient(-45deg, transparent 75%, #222 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, -10px 0;
}
.ie-canvas-container {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
line-height: 0;
box-shadow: 0 2px 20px rgba(0,0,0,0.6);
}
.ie-canvas-container canvas {
position: absolute;
top: 0;
left: 0;
display: block;
}
#ie-canvas-bg {
z-index: 1;
}
#ie-canvas-draw {
z-index: 2;
cursor: crosshair;
}
#ie-canvas-overlay {
z-index: 3;
cursor: default;
pointer-events: none; /* SelectTool.activate()でautoに変更 */
}
.ie-placeholder {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--wfm-text-secondary);
font-size: 14px;
pointer-events: none;
gap: 8px;
}
.ie-placeholder-icon {
font-size: 40px;
opacity: 0.3;
}
/* Zoom bar */
.ie-zoom-bar {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-top: 1px solid var(--wfm-border);
background: var(--wfm-surface);
font-size: 12px;
flex-shrink: 0;
color: var(--wfm-text-secondary);
}
#ie-zoom-label {
min-width: 38px;
text-align: right;
color: var(--wfm-text);
}
/* =============================================
Properties Pane (left of Layers panel)
============================================= */
.ie-props-pane {
width: 160px;
flex-shrink: 0;
display: flex;
flex-direction: column;
border-left: 1px solid var(--wfm-border);
background: var(--wfm-surface);
overflow: hidden;
}
.ie-props-header {
display: flex;
align-items: center;
padding: 5px 8px;
border-bottom: 1px solid var(--wfm-border);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.4px;
color: var(--wfm-text-secondary);
flex-shrink: 0;
}
.ie-props-body {
flex: 1;
overflow-y: auto;
padding: 8px 6px;
display: flex;
flex-direction: column;
gap: 10px;
}
.ie-props-row {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 11px;
}
.ie-props-row label {
color: var(--wfm-text-secondary);
white-space: nowrap;
}
.ie-props-row input[type="range"] {
width: 100%;
}
.ie-props-row span {
font-size: 11px;
color: var(--wfm-text);
text-align: right;
}
/* Mask layer item highlight */
.ie-layer-item[data-type="mask"] .ie-layer-type-icon {
color: #e25252;
}
/* =============================================
Right Panel (Layers)
============================================= */
.ie-right-panel {
width: 220px;
flex-shrink: 0;
display: flex;
flex-direction: column;
border-left: 1px solid var(--wfm-border);
background: var(--wfm-surface);
overflow: hidden;
}
.ie-layers-header {
display: flex;
flex-direction: column;
gap: 4px;
padding: 5px 6px;
border-bottom: 1px solid var(--wfm-border);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.4px;
color: var(--wfm-text-secondary);
flex-shrink: 0;
}
.ie-layers-header-row {
display: flex;
align-items: center;
gap: 2px;
}
.ie-layers-header-row > span {
flex: 1;
}
.ie-layer-list {
flex: 1;
overflow-y: auto;
padding: 4px;
}
.ie-layer-item {
display: flex;
align-items: center;
gap: 5px;
padding: 4px 5px;
border-radius: 5px;
cursor: pointer;
font-size: 12px;
user-select: none;
transition: background 0.1s;
}
.ie-layer-item:hover {
background: var(--wfm-surface-hover);
}
.ie-layer-item.active {
background: rgba(90, 110, 220, 0.22);
outline: 1px solid rgba(90, 110, 220, 0.4);
}
.ie-layer-thumb {
width: 30px;
height: 30px;
border: 1px solid var(--wfm-border);
border-radius: 3px;
flex-shrink: 0;
object-fit: cover;
background:
repeating-conic-gradient(#888 0% 25%, transparent 0% 50%)
0 0 / 8px 8px;
}
.ie-layer-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ie-layer-vis-btn {
background: none;
border: none;
cursor: pointer;
font-size: 13px;
padding: 0;
line-height: 1;
color: var(--wfm-text);
opacity: 0.85;
flex-shrink: 0;
transition: opacity 0.1s;
}
.ie-layer-vis-btn:hover {
opacity: 1;
}
.ie-opacity-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-top: 1px solid var(--wfm-border);
font-size: 12px;
flex-shrink: 0;
color: var(--wfm-text-secondary);
}
.ie-opacity-row input[type="range"] {
flex: 1;
}
#ie-layer-opacity-label {
min-width: 32px;
text-align: right;
color: var(--wfm-text);
}
/* =============================================
Text Tool Overlay
============================================= */
.ie-text-overlay {
position: absolute;
z-index: 100;
background: var(--wfm-surface);
border: 1px solid var(--wfm-border);
border-radius: 6px;
padding: 8px;
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
display: flex;
flex-direction: column;
gap: 6px;
min-width: 180px;
}
.ie-text-textarea {
width: 200px;
resize: vertical;
background: var(--wfm-bg);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
padding: 6px;
font-size: 13px;
font-family: inherit;
min-height: 60px;
}
.ie-text-btn-row {
display: flex;
gap: 6px;
justify-content: flex-end;
}
/* =============================================
Scrollbar
============================================= */
.ie-layer-list::-webkit-scrollbar {
width: 4px;
}
.ie-layer-list::-webkit-scrollbar-thumb {
background: var(--wfm-border);
border-radius: 2px;
}
+413
View File
@@ -0,0 +1,413 @@
/* Lab tab — experimental I2I batch generation with per-column keyframes */
/* .wfm-gen-subtab-content.active defaults to flex-direction:row (main.css);
Lab needs its Setting/Results nav stacked above the panel body. */
#wfm-gen-subtab-lab.active {
flex-direction: column;
}
.wfm-lab-subtab-nav {
display: flex;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
}
.wfm-lab-subtab-btn {
padding: 6px 16px;
font-size: 12px;
background: transparent;
border: none;
color: var(--wfm-text-secondary);
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
transition: color 0.15s;
}
.wfm-lab-subtab-btn:hover { color: var(--wfm-text-primary); }
.wfm-lab-subtab-btn.active { color: var(--wfm-primary); border-bottom-color: var(--wfm-primary); }
.wfm-lab-panel {
display: none;
flex-direction: column;
flex: 1;
overflow: hidden;
height: calc(100% - 33px);
}
.wfm-lab-panel.active { display: flex; }
.wfm-lab-planjson-toolbar {
display: flex;
gap: 8px;
padding: 8px 10px;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
}
.wfm-lab-pane-header {
font-size: 11px;
font-weight: 600;
color: var(--wfm-text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
padding: 4px 0 6px;
flex-shrink: 0;
}
/* ---------------- Setting layout: left | center (4 columns) | right ---------------- */
.wfm-lab-setting-layout {
display: flex;
height: 100%;
overflow: hidden;
gap: 0;
}
.wfm-lab-pane {
display: flex;
flex-direction: column;
overflow: hidden;
min-width: 0;
border-right: 1px solid var(--wfm-border);
padding: 10px;
}
.wfm-lab-pane:last-child { border-right: none; }
.wfm-lab-left { width: 220px; flex-shrink: 0; }
.wfm-lab-center { flex: 1; padding: 0; }
.wfm-lab-right { width: 260px; flex-shrink: 0; overflow-y: auto; }
.wfm-lab-side-btns {
display: flex;
flex-direction: column;
gap: 6px;
margin-top: 12px;
}
.wfm-lab-plan-workflow-row {
display: flex;
align-items: center;
gap: 6px;
margin-top: 8px;
padding: 6px 8px;
background: var(--wfm-bg-secondary);
border: 1px solid var(--wfm-border);
border-radius: 4px;
}
.wfm-lab-plan-workflow-name {
flex: 1;
min-width: 0;
font-size: 11px;
color: var(--wfm-text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-lab-field-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
}
.wfm-lab-field-row label {
font-size: 12px;
color: var(--wfm-text-secondary);
white-space: nowrap;
}
.wfm-lab-field-row input {
flex: 1;
min-width: 0;
}
.wfm-lab-note {
width: 100%;
resize: vertical;
font-size: 12px;
}
.wfm-lab-checkbox-label {
display: flex;
align-items: center;
gap: 6px;
margin-top: 8px;
font-size: 12px;
color: var(--wfm-text-secondary);
cursor: pointer;
}
/* ---------------- Keyframe columns ---------------- */
.wfm-lab-columns {
display: flex;
height: 100%;
overflow: hidden;
}
.wfm-lab-column {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
border-right: 1px solid var(--wfm-border);
overflow: hidden;
}
.wfm-lab-column:last-child { border-right: none; }
.wfm-lab-col-header {
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-between;
gap: 4px;
row-gap: 4px;
padding: 6px 8px;
font-size: 11px;
font-weight: 600;
color: var(--wfm-text-secondary);
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
}
.wfm-lab-col-btns { display: flex; gap: 2px; }
.wfm-lab-col-header-left {
display: flex;
align-items: center;
gap: 6px;
}
/* Model column header: C/L/V toggle that switches which single field its cells
summarize (see _modelViewMode in lab-tab.js) — not part of the Plan data. */
.wfm-lab-model-view-toggle { display: flex; gap: 2px; }
.wfm-lab-model-view-btn {
width: 20px;
height: 20px;
padding: 0;
font-size: 10px;
font-weight: 700;
line-height: 1;
background: var(--wfm-bg-tertiary);
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius-sm);
color: var(--wfm-text-secondary);
cursor: pointer;
transition: color 0.15s, border-color 0.15s, background 0.15s;
}
.wfm-lab-model-view-btn:hover { color: var(--wfm-text-primary); border-color: var(--wfm-primary); }
.wfm-lab-model-view-btn.active {
color: #fff;
background: var(--wfm-primary);
border-color: var(--wfm-primary);
}
.wfm-lab-col-cells {
flex: 1;
overflow-y: auto;
padding: 6px;
display: flex;
flex-direction: column;
gap: 6px;
}
.wfm-lab-cell {
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius-sm);
padding: 6px 8px;
font-size: 11px;
cursor: pointer;
background: var(--wfm-bg-tertiary);
transition: border-color 0.15s;
}
.wfm-lab-cell:hover { border-color: var(--wfm-primary); }
.wfm-lab-cell-index {
font-weight: 600;
color: var(--wfm-primary);
margin-right: 4px;
}
.wfm-lab-cell-value {
color: var(--wfm-text-primary);
word-break: break-all;
}
.wfm-lab-cell.wfm-lab-cell-revert .wfm-lab-cell-value {
color: var(--wfm-text-secondary);
font-style: italic;
}
/* Setting 1, not yet explicitly overridden: showing the live GenerateUI value instead of
its own stored one (see _isLiveDisplay in lab-tab.js). Dashed border distinguishes it
from a saved override (solid border) at a glance. */
.wfm-lab-cell.wfm-lab-cell-live {
border-style: dashed;
}
.wfm-lab-cell.wfm-lab-cell-live .wfm-lab-cell-value {
color: var(--wfm-text-secondary);
}
/* This keyframe row is skipped entirely (see _resolveKeyframe's bypassed handling) —
amber to read as "temporarily disabled", distinct from the neutral gray used for
revert/live. Takes priority over both of those in _cellHtml. */
.wfm-lab-cell.wfm-lab-cell-bypassed {
border-color: var(--wfm-warning);
opacity: 0.6;
}
.wfm-lab-cell.wfm-lab-cell-bypassed .wfm-lab-cell-value {
color: var(--wfm-warning);
}
/* LoRA node-bypass (strength forced to 0 at apply-time) — red to distinguish from the
amber row-level bypassed above; the row itself still applies, only the LoRA doesn't. */
.wfm-lab-cell.wfm-lab-cell-node-bypassed {
border-color: var(--wfm-danger);
}
.wfm-lab-cell.wfm-lab-cell-node-bypassed .wfm-lab-cell-value {
color: var(--wfm-danger);
}
/* Single-click selection target for the column header's up/down reorder buttons —
layered as a box-shadow (not border-color) so it never conflicts with the
revert/live/bypassed/node-bypassed border-color signaling above. */
.wfm-lab-cell.wfm-lab-cell-selected {
box-shadow: 0 0 0 2px var(--wfm-primary);
}
.wfm-lab-cell-applied {
margin-top: 3px;
padding-top: 3px;
border-top: 1px dashed var(--wfm-border);
font-size: 10px;
color: var(--wfm-text-secondary);
}
/* Shown instead of a keyframe list when the loaded workflow has no node this Model
sub-column (checkpoint/lora/vae) could override — see _hasNodeForColumn in lab-tab.js. */
.wfm-lab-cell-empty {
padding: 6px 8px;
font-size: 11px;
font-style: italic;
color: var(--wfm-text-secondary);
cursor: default;
}
.wfm-lab-cell-prompt-line {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
/* ---------------- Modal form (checkpoint/vae/prompt/ksampler edit) ---------------- */
.wfm-lab-modal-row {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 10px;
}
.wfm-lab-modal-row label {
font-size: 12px;
color: var(--wfm-text-secondary);
}
.wfm-lab-modal-inline {
display: flex;
gap: 8px;
}
.wfm-lab-modal-btnrow {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 10px;
}
.wfm-lab-modal-hint {
font-size: 11px;
color: var(--wfm-text-secondary);
font-style: italic;
margin: 0 0 10px;
}
.wfm-lab-modal-inline > div {
flex: 1;
min-width: 0;
}
.wfm-lab-modal-checkbox {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
margin-top: 4px;
}
/* ---------------- Results layout ---------------- */
.wfm-lab-results-layout {
display: flex;
height: 100%;
overflow: hidden;
}
.wfm-lab-results-left {
width: 260px;
flex-shrink: 0;
border-right: 1px solid var(--wfm-border);
padding: 10px;
}
.wfm-lab-results-center {
flex: 1;
min-width: 0;
padding: 10px;
overflow-y: auto;
}
.wfm-lab-results-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.wfm-lab-result-thumb {
width: 100%;
aspect-ratio: 1 / 1;
object-fit: cover;
border-radius: var(--wfm-radius-sm);
border: 1px solid var(--wfm-border);
cursor: pointer;
transition: border-color 0.15s;
}
.wfm-lab-result-thumb:hover { border-color: var(--wfm-primary); }
.wfm-lab-result-item { position: relative; }
.wfm-lab-result-index {
position: absolute;
top: 2px;
left: 2px;
background: rgba(0, 0, 0, 0.6);
color: #fff;
font-size: 10px;
padding: 1px 5px;
border-radius: var(--wfm-radius-sm);
}
+2917 -71
View File
File diff suppressed because it is too large Load Diff
+302
View File
@@ -0,0 +1,302 @@
/* ============================================================
Tagger Tab Styles
============================================================ */
/* ── サブタブナビ ────────────────────────────────────────────── */
.wfm-tagger-subtab-nav {
display: flex;
gap: 0;
border-bottom: 1px solid var(--wfm-border);
background: var(--wfm-bg-secondary);
flex-shrink: 0;
}
.wfm-tagger-subtab-btn {
padding: 8px 20px;
font-size: 13px;
font-weight: 500;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
color: var(--wfm-text-secondary);
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
white-space: nowrap;
}
.wfm-tagger-subtab-btn:hover {
color: var(--wfm-text);
}
.wfm-tagger-subtab-btn.active {
color: var(--wfm-primary);
border-bottom-color: var(--wfm-primary);
}
/* ── サブタブ共通 ────────────────────────────────────────────── */
.wfm-tagger-subtab {
flex: 1;
overflow-y: auto;
padding: 12px;
}
/* ── セクション ─────────────────────────────────────────────── */
.wfm-tagger-section {
background: var(--wfm-surface);
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius);
padding: 10px 12px;
margin-bottom: 10px;
}
.wfm-tagger-section-header {
font-size: 12px;
font-weight: 600;
color: var(--wfm-text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 8px;
}
/* ── フォームレイアウト ─────────────────────────────────────── */
.wfm-tagger-form-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.wfm-tagger-form-row:last-child {
margin-bottom: 0;
}
.wfm-tagger-label {
font-size: 12px;
color: var(--wfm-text-secondary);
min-width: 80px;
white-space: nowrap;
}
.wfm-tagger-select {
flex: 1;
min-width: 0;
}
/* ── スライダー ─────────────────────────────────────────────── */
.wfm-tagger-slider {
flex: 1;
min-width: 0;
accent-color: var(--wfm-primary);
cursor: pointer;
}
.wfm-tagger-slider-val {
font-size: 12px;
color: var(--wfm-text-secondary);
min-width: 36px;
text-align: right;
}
/* ── Single サブタブ ─────────────────────────────────────────── */
.wfm-tagger-single-layout {
display: flex;
gap: 12px;
height: calc(100vh - var(--wfm-header-height, 96px) - 80px);
min-height: 0;
}
.wfm-tagger-image-pane {
width: 300px;
min-width: 240px;
display: flex;
flex-direction: column;
gap: 8px;
flex-shrink: 0;
}
.wfm-tagger-image-sources {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.wfm-tagger-preview-wrap {
flex: 1;
min-height: 0;
background: var(--wfm-surface);
border: 2px dashed var(--wfm-border);
border-radius: var(--wfm-radius);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
transition: border-color 0.15s, background 0.15s;
cursor: pointer;
}
.wfm-tagger-preview-wrap.drag-over {
border-color: var(--wfm-primary);
background: rgba(74, 158, 255, 0.08);
}
.wfm-tagger-image-name {
font-size: 11px;
color: var(--wfm-text-secondary);
text-align: center;
word-break: break-all;
min-height: 16px;
}
.wfm-tagger-controls-pane {
flex: 1;
min-width: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0;
}
.wfm-tagger-result-actions {
display: flex;
gap: 6px;
margin-top: 6px;
flex-wrap: wrap;
}
/* ── Batch サブタブ ──────────────────────────────────────────── */
.wfm-tagger-batch-layout {
max-width: 900px;
}
.wfm-tagger-batch-cols {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.wfm-tagger-progress-bar-wrap {
height: 6px;
background: var(--wfm-border);
border-radius: 3px;
overflow: hidden;
}
.wfm-tagger-progress-bar {
height: 100%;
background: var(--wfm-primary);
border-radius: 3px;
transition: width 0.3s ease;
}
/* ── DB サブタブ ─────────────────────────────────────────────── */
.wfm-tagger-db-layout {
display: flex;
flex-direction: column;
height: calc(100vh - var(--wfm-header-height, 96px) - 80px);
min-height: 0;
}
.wfm-tagger-db-toolbar {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 10px;
flex-shrink: 0;
}
.wfm-tagger-db-table-wrap {
flex: 1;
overflow: auto;
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius);
min-height: 0;
}
.wfm-tagger-db-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.wfm-tagger-db-table th,
.wfm-tagger-db-table td {
padding: 6px 10px;
text-align: left;
border-bottom: 1px solid var(--wfm-border);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 220px;
}
.wfm-tagger-db-table th {
background: var(--wfm-bg-secondary);
color: var(--wfm-text-secondary);
font-weight: 600;
text-transform: uppercase;
font-size: 11px;
letter-spacing: 0.04em;
position: sticky;
top: 0;
z-index: 1;
}
#wfm-tagger-db-th-select, td.wfm-tagger-db-select {
text-align: center;
}
#wfm-tagger-db-th-select input, .wfm-tagger-db-select input {
vertical-align: middle;
}
.wfm-tagger-db-table tbody tr {
cursor: pointer;
transition: background 0.1s;
}
.wfm-tagger-db-table tbody tr:hover {
background: var(--wfm-surface-hover);
}
.wfm-tagger-db-table tbody tr.selected {
background: rgba(74, 158, 255, 0.15);
}
.wfm-tagger-db-edit-panel {
flex-shrink: 0;
margin-top: 10px;
background: var(--wfm-surface);
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius);
padding: 10px 12px;
}
/* ── ユーティリティ ─────────────────────────────────────────── */
#wfm-tab-tagger {
display: none;
flex-direction: column;
height: calc(100vh - var(--wfm-header-height, 56px));
overflow: hidden;
}
#wfm-tab-tagger.active {
display: flex;
}
.wfm-placeholder {
color: var(--wfm-text-secondary);
font-size: 13px;
text-align: center;
padding: 20px;
pointer-events: none;
}
+535
View File
@@ -0,0 +1,535 @@
/* =============================================
Video Tab (MiniMax H3 / LTX-2.5 / Wan2.2対応・GenerateUIタブとは独立)
3ペイン構成: 左=Plan/Asset/Editサブタブ / 中央=プレビュー+Video Source / 右=プロパティ
中央・右ペインは左のサブタブ切替と無関係に常時表示される。
各ペインは独立したカラムとして高さ100%を占め、内部でスクロールする。
中央ペインのコンテンツ量(生成結果の有無・動画の縦横比)が変わっても
左右のペインの位置が動かないよう、意図的に高さを共有させない構造にしている。
============================================= */
#wfm-tab-video {
padding: 0;
overflow: hidden;
}
.wfm-video-layout {
display: flex;
flex-direction: row;
height: 100%;
overflow: hidden;
}
/* ── 左ペイン: フォーム ── */
.wfm-video-form-panel {
width: 380px;
flex: none;
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px;
overflow-y: auto;
border-right: 1px solid var(--wfm-border);
}
.wfm-video-form-panel label {
display: block;
font-size: 12px;
color: var(--wfm-text-secondary);
margin-bottom: 4px;
}
.wfm-video-wf-name {
color: var(--wfm-text-secondary);
font-size: 13px;
}
/* ── Plan/Asset/Edit サブタブナビ(Lab/Galleryと同型) ── */
.wfm-video-subtab-nav {
display: flex;
border-bottom: 1px solid var(--wfm-border);
flex-shrink: 0;
margin: -16px -16px 12px;
padding: 0 16px;
}
.wfm-video-subtab-btn {
padding: 6px 16px;
font-size: 12px;
background: transparent;
border: none;
color: var(--wfm-text-secondary);
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
transition: color 0.15s;
}
.wfm-video-subtab-btn:hover { color: var(--wfm-text-primary); }
.wfm-video-subtab-btn.active { color: var(--wfm-primary); border-bottom-color: var(--wfm-primary); }
/* 中央ペイン用のタブナビ: プレビュー行の"下"に来るため、サイドバー版と違って
上マージンは潰さない(プレビュー行と重ならないようにする)。左右のみ潰して
center-panelのpadding分フルブリードにする。 */
.wfm-video-center-subtab-nav {
margin: 0 -16px 12px;
}
.wfm-video-subtab-panel {
display: flex;
flex-direction: column;
gap: 10px;
}
/* ── Plan: タイムライン(各ブロックのdurationに応じてflex-growで幅配分) ── */
.wfm-video-timeline-wrap {
display: flex;
flex-direction: column;
gap: 6px;
}
.wfm-video-timeline-track {
display: flex;
height: 40px;
border-radius: 4px;
overflow: hidden;
border: 1px solid var(--wfm-border);
}
.wfm-video-timeline-block {
flex-basis: 0;
min-width: 24px;
cursor: pointer;
border-right: 1px solid rgba(0, 0, 0, 0.3);
transition: outline 0.1s;
}
.wfm-video-timeline-block:last-child { border-right: none; }
.wfm-video-timeline-block.selected { outline: 2px solid var(--wfm-primary); outline-offset: -2px; }
.wfm-video-timeline-toolbar {
display: flex;
gap: 6px;
}
/* ── Plan: 中央下部に配置されるコンテンツ全体(Planサブタブ選択時のみ表示) ── */
.wfm-video-plan-topbar {
display: flex;
flex-direction: column;
gap: 8px;
}
/* 現在ロード中のワークフロー名 + Planに記録されたワークフローのOpen Workflow行を
同じ1行にまとめる(以前は縦に2行だった)。 */
.wfm-video-wf-row {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.wfm-video-wf-row .wfm-lab-plan-workflow-row { margin-top: 0; }
.wfm-video-plan-basesettings {
display: grid;
grid-template-columns: repeat(5, 150px);
gap: 10px;
}
/* ── Plan: 2行目の追加設定(Width/Height/Turbo Mode/Strength/Steps/Prompt Enhance)。
basesettingsと同じ見た目だが、ワークフローによって対応する項目が変わる可変集合の
ため別クラスに分けている ── */
.wfm-video-plan-extrasettings {
display: grid;
grid-template-columns: repeat(6, 130px);
gap: 10px;
}
.wfm-video-plan-basesettings label,
.wfm-video-plan-extrasettings label {
display: block;
font-size: 12px;
color: var(--wfm-text-secondary);
margin-bottom: 4px;
}
/* Noise Seed欄: 数値入力とRandomizeチェックボックスを1セル内で横並びにする */
.wfm-video-seed-inline {
display: flex;
gap: 6px;
align-items: center;
}
.wfm-video-seed-inline .wfm-input { flex: 1; min-width: 0; }
.wfm-video-seed-randomize-inline {
display: flex;
align-items: center;
gap: 3px;
font-size: 11px;
white-space: nowrap;
margin-bottom: 0;
}
/* Turbo Mode / Prompt Enhance欄: ラベル行の下にチェックボックスを1つだけ置く
(他のnumber/select欄と縦位置を揃えるため、input要素の高さを合わせる) */
.wfm-video-checkbox-inline {
display: flex;
align-items: center;
gap: 4px;
height: 30px;
font-size: 12px;
margin-bottom: 0;
}
/* タイムラインの下: ブロックエディタ(左、横並びの3カラム) + Run/Planタブ(右) */
.wfm-video-plan-main-row {
display: flex;
gap: 16px;
align-items: flex-start;
}
/* ── Plan: ブロックエディタ(選択中ブロックのFirst/Last Image・Prompt。Durationはtopbarの
basesettings行に移動済み。中央の広いエリアに配置されるため横並びの3カラムで表示する) ── */
.wfm-video-block-editor {
flex: 1;
min-width: 0;
display: flex;
gap: 16px;
}
.wfm-video-block-col label {
display: block;
font-size: 12px;
color: var(--wfm-text-secondary);
margin-bottom: 4px;
}
.wfm-video-block-first-col,
.wfm-video-block-last-col {
width: 190px;
flex: none;
display: flex;
flex-direction: column;
}
.wfm-video-block-prompt-col {
flex: 1;
min-width: 220px;
display: flex;
flex-direction: column;
}
.wfm-video-block-prompt-col textarea {
flex: 1;
resize: none;
}
.wfm-video-block-color-row {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
color: var(--wfm-text-secondary);
margin-bottom: 6px;
}
.wfm-video-color-swatch {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 3px;
border: 1px solid var(--wfm-border);
}
/* ── Plan: Run/Planタブ(実行系・プラン管理系を切替表示するコンパクトなウィジェット) ── */
.wfm-video-runplan-panel {
width: 260px;
flex: none;
}
.wfm-video-runplan-tabnav {
display: flex;
gap: 4px;
margin-bottom: 10px;
border-bottom: 1px solid var(--wfm-border);
}
.wfm-video-runplan-tab {
flex: 1;
background: none;
border: none;
padding: 6px 4px;
cursor: pointer;
color: var(--wfm-text-secondary);
border-bottom: 2px solid transparent;
font-size: 13px;
}
.wfm-video-runplan-tab.active {
color: var(--wfm-text);
border-bottom-color: var(--wfm-primary);
}
.wfm-video-runplan-content {
display: flex;
flex-direction: column;
}
/* ── Asset: 素材グリッド・詳細パネル ── */
.wfm-video-asset-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
max-height: 320px;
overflow-y: auto;
}
.wfm-video-asset-card {
cursor: pointer;
border: 1px solid var(--wfm-border);
border-radius: 4px;
overflow: hidden;
transition: outline 0.1s;
}
.wfm-video-asset-card.selected { outline: 2px solid var(--wfm-primary); outline-offset: -2px; }
.wfm-video-asset-card-img {
width: 100%;
aspect-ratio: 1;
object-fit: cover;
display: block;
background: var(--wfm-bg-hover, #111);
}
.wfm-video-asset-card-name {
font-size: 10px;
padding: 2px 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--wfm-text-secondary);
}
.wfm-video-asset-detail {
display: flex;
flex-direction: column;
gap: 6px;
border-top: 1px solid var(--wfm-border);
padding-top: 10px;
}
.wfm-video-asset-detail label {
font-size: 12px;
color: var(--wfm-text-secondary);
}
.wfm-video-asset-name {
font-size: 12px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-video-asset-tags {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.wfm-video-asset-tag {
display: inline-flex;
align-items: center;
gap: 2px;
background: var(--wfm-bg-secondary);
border: 1px solid var(--wfm-border);
border-radius: 10px;
padding: 1px 8px;
font-size: 11px;
}
.wfm-video-asset-tag button {
background: none;
border: none;
color: var(--wfm-text-secondary);
cursor: pointer;
padding: 0;
font-size: 11px;
}
/* ── 中央ペイン: プレビュー + 編集 ── */
.wfm-video-center-panel {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
overflow-y: auto;
padding: 16px;
gap: 16px;
border-right: 1px solid var(--wfm-border);
}
/* 3カラム構成: 左=Video Source選択UI(固定幅) / 中央=Asset選択・Sourceドロップ兼用
プレビュー / 右=生成結果専用プレビュー。.wfm-video-preview-frameは共通クラスなので
両プレビュー枠とも自動的にflex:1で均等幅になる。 */
.wfm-video-preview-row {
flex: none;
display: flex;
flex-direction: row;
gap: 16px;
}
.wfm-video-preview-frame {
flex: 1;
min-width: 0;
min-height: 260px;
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed var(--wfm-border);
border-radius: 6px;
background: var(--wfm-bg-hover, #111);
text-align: center;
}
.wfm-video-preview-el {
max-width: 100%;
max-height: 60vh;
border-radius: 6px;
}
.wfm-video-source-panel {
width: 220px;
flex: none;
display: flex;
flex-direction: column;
}
.wfm-video-pane-header {
font-weight: 600;
margin-bottom: 4px;
}
.wfm-video-prop-hint {
font-size: 12px;
color: var(--wfm-text-secondary);
margin: 0 0 8px 0;
}
/* 将来の動画編集機能(トリミング等)用のプレースホルダー領域 */
.wfm-video-edit-panel {
flex: 1;
min-height: 160px;
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed var(--wfm-border);
border-radius: 6px;
color: var(--wfm-text-secondary);
font-size: 13px;
}
/* ── 右ペイン: プロパティ (Frame抽出 / GIF変換タブ) ── */
.wfm-video-properties-panel {
width: 240px;
flex: none;
padding: 16px;
overflow-y: auto;
}
.wfm-video-prop-tabnav {
display: flex;
gap: 4px;
margin-bottom: 12px;
border-bottom: 1px solid var(--wfm-border);
}
.wfm-video-prop-tab {
flex: 1;
background: none;
border: none;
padding: 6px 4px;
cursor: pointer;
color: var(--wfm-text-secondary);
border-bottom: 2px solid transparent;
font-size: 13px;
}
.wfm-video-prop-tab.active {
color: var(--wfm-text);
border-bottom-color: var(--wfm-primary);
}
.wfm-video-prop-content {
display: flex;
flex-direction: column;
gap: 6px;
}
/* ── 左ペイン Project サブタブ: 保存済みPlan一覧 ── */
.wfm-video-project-list {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 60vh;
overflow-y: auto;
}
.wfm-video-project-item {
display: flex;
gap: 8px;
align-items: center;
border: 1px solid var(--wfm-border);
border-radius: 4px;
padding: 6px;
cursor: pointer;
}
.wfm-video-project-item:hover { border-color: var(--wfm-primary); }
.wfm-video-project-item.active { outline: 2px solid var(--wfm-primary); outline-offset: -2px; }
.wfm-video-project-item-thumb {
width: 40px;
height: 40px;
flex: none;
object-fit: cover;
border-radius: 3px;
background: var(--wfm-bg-hover, #111);
}
.wfm-video-project-item-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.wfm-video-project-item-name {
font-size: 12px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-video-project-item-meta {
font-size: 10px;
color: var(--wfm-text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-video-project-item-delete {
flex: none;
background: none;
border: none;
color: var(--wfm-text-secondary);
cursor: pointer;
font-size: 14px;
padding: 2px 6px;
}
.wfm-video-project-item-delete:hover { color: var(--wfm-danger); }
+205
View File
@@ -0,0 +1,205 @@
/**
* Shared AI backend settings modal (Backend / Connection / Model / Generation / Unload / Save).
* Used by the Prompt tab and Tagger tab, each with its own localStorage key so their
* settings stay independent — mirrors the AI TOOL tab's own settings pane (ai-tab.js).
*/
import { openModal, closeModal, showToast } from "./app.js";
import { t } from "./i18n.js";
import { readJsonStorage, getAiBackendDefaultUrl, unslothProxy, unloadAiModel } from "./util.js";
function loadCfg(storageKey) {
return readJsonStorage(storageKey);
}
function saveCfg(storageKey, patch) {
const data = { ...loadCfg(storageKey), ...patch };
localStorage.setItem(storageKey, JSON.stringify(data));
return data;
}
// 保存済み設定を {backend, url, model, thinkingMode, maxTokens} の形で返す
export function getAiBackendConfig(storageKey) {
const s = loadCfg(storageKey);
const backend = s.backend || "ollama";
const url = (s.backendUrl || getAiBackendDefaultUrl(backend)).replace(/\/$/, "");
return {
backend,
url,
model: s.model || "",
thinkingMode: !!s.thinkingMode,
maxTokens: Math.max(0, parseInt(s.maxTokens, 10) || 0),
};
}
function isValidBackendUrl(url) {
try {
const u = new URL(url);
return u.protocol === "http:" || u.protocol === "https:";
} catch {
return false;
}
}
async function fetchBackendModels(url, backend) {
if (backend === "ollama") {
const res = await fetch(`${url}/api/tags`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).models?.map(m => m.name) || [];
} else if (backend === "unsloth") {
const data = await unslothProxy(url, "/v1/models", "GET");
return (data.data || []).map(m => m.id);
} else {
const res = await fetch(`${url}/v1/models`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return ((await res.json()).data || []).map(m => m.id);
}
}
/**
* @param {string} storageKey localStorage key holding {backend, backendUrl, model, thinkingMode, maxTokens}
* @param {string} title modal title
* @param {() => void} [onSaved] called after Save persists the config (e.g. to refresh a status label)
*/
export function openAiBackendSettingsModal(storageKey, title, onSaved) {
const saved = loadCfg(storageKey);
const backend = saved.backend || "ollama";
const html = `
<div class="wfm-ai-settings-container">
<div class="wfm-ai-settings-section">
<div class="wfm-ai-settings-title">${t("aiSettingsBackend")}</div>
<div class="wfm-ai-backend-row">
${[["ollama", "Ollama"], ["lmstudio", "LM Studio"], ["lemonade", "Lemonade"], ["unsloth", "Unsloth"]].map(([v, label]) => `
<label class="wfm-ai-radio-label">
<input type="radio" name="wfm-aism-backend" value="${v}" ${v === backend ? "checked" : ""}> ${label}
</label>`).join("")}
</div>
</div>
<div class="wfm-ai-settings-section">
<div class="wfm-ai-settings-title">${t("aiSettingsConnection")}</div>
<div class="wfm-ai-settings-row">
<label class="wfm-ai-label">URL</label>
<input type="text" id="wfm-aism-url" class="wfm-input wfm-ai-url-input" value="${saved.backendUrl || getAiBackendDefaultUrl(backend)}">
</div>
<div class="wfm-ai-settings-row">
<button id="wfm-aism-test-btn" class="wfm-btn">${t("aiSettingsTestBtn")}</button>
<button id="wfm-aism-unload-btn" class="wfm-btn">${t("aiUnloadModel")}</button>
</div>
<div class="wfm-ai-settings-row">
<span id="wfm-aism-test-result" class="wfm-ai-test-result"></span>
</div>
</div>
<div class="wfm-ai-settings-section">
<div class="wfm-ai-settings-title">${t("aiSettingsModelSection")}</div>
<div class="wfm-ai-settings-row">
<select id="wfm-aism-model" class="wfm-select wfm-ai-model-select">
<option value="">${t("selectModel")}</option>
</select>
<button id="wfm-aism-refresh-btn" class="wfm-btn">${t("aiSettingsRefreshBtn")}</button>
</div>
</div>
<div class="wfm-ai-settings-section">
<div class="wfm-ai-settings-title">${t("aiSettingsGenerationTitle")}</div>
<div class="wfm-ai-settings-row">
<label class="wfm-ai-label" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-aism-thinking"> ${t("aiSettingsThinkingMode")}
</label>
</div>
<div class="wfm-ai-settings-row">
<label class="wfm-ai-label">${t("aiSettingsMaxTokens")}</label>
<input type="number" id="wfm-aism-max-tokens" class="wfm-input" min="0" step="1" placeholder="${t("aiSettingsMaxTokensPlaceholder")}">
</div>
</div>
<div class="wfm-ai-settings-section">
<button id="wfm-aism-save-btn" class="wfm-btn wfm-btn-primary">${t("aiSettingsSaveBtn")}</button>
</div>
</div>`;
openModal(title, html);
const urlInput = document.getElementById("wfm-aism-url");
const modelSelect = document.getElementById("wfm-aism-model");
const thinkingCheckbox = document.getElementById("wfm-aism-thinking");
const maxTokensInput = document.getElementById("wfm-aism-max-tokens");
const testResultEl = document.getElementById("wfm-aism-test-result");
thinkingCheckbox.checked = !!saved.thinkingMode;
if (saved.maxTokens) maxTokensInput.value = saved.maxTokens;
function currentBackend() {
return document.querySelector("input[name='wfm-aism-backend']:checked")?.value || "ollama";
}
async function populateModels(selectedModel) {
const url = urlInput.value.trim();
try {
const models = await fetchBackendModels(url, currentBackend());
modelSelect.innerHTML = models.length
? models.map(name => `<option value="${name}" ${name === selectedModel ? "selected" : ""}>${name}</option>`).join("")
: `<option value="">${t("noModelsFound")}</option>`;
} catch {
modelSelect.innerHTML = `<option value="">${t("noModelsFound")}</option>`;
}
}
populateModels(saved.model || "");
document.querySelectorAll("input[name='wfm-aism-backend']").forEach(r => {
r.addEventListener("change", () => {
urlInput.value = getAiBackendDefaultUrl(r.value);
testResultEl.textContent = "";
});
});
document.getElementById("wfm-aism-refresh-btn")?.addEventListener("click", () => populateModels(modelSelect.value));
document.getElementById("wfm-aism-test-btn")?.addEventListener("click", async () => {
const url = urlInput.value.trim();
if (!isValidBackendUrl(url)) {
testResultEl.textContent = t("aiToastInvalidUrlInput");
testResultEl.className = "wfm-ai-test-result wfm-ai-status-error";
return;
}
testResultEl.textContent = t("aiStatusConnecting");
testResultEl.className = "wfm-ai-test-result wfm-ai-status-working";
try {
const models = await fetchBackendModels(url, currentBackend());
testResultEl.textContent = `${t("aiStatusConnectOk")} (${models.length} ${t("aiModels")})`;
testResultEl.className = "wfm-ai-test-result wfm-ai-status-ok";
await populateModels(modelSelect.value);
} catch (err) {
testResultEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
testResultEl.className = "wfm-ai-test-result wfm-ai-status-error";
}
});
document.getElementById("wfm-aism-unload-btn")?.addEventListener("click", async () => {
const url = urlInput.value.trim();
const model = modelSelect.value;
if (!model) { showToast(t("aiUnloadNoModel"), "error"); return; }
try {
await unloadAiModel(url, currentBackend(), model);
showToast(t("aiUnloadDone"), "success");
} catch (err) {
showToast(err.message === "UNSUPPORTED" ? t("aiUnloadUnsupported") : t("aiUnloadFailed") + err.message, "error");
}
});
document.getElementById("wfm-aism-save-btn")?.addEventListener("click", () => {
const url = urlInput.value.trim();
if (url && !isValidBackendUrl(url)) {
showToast(t("aiToastInvalidUrl"), "error");
return;
}
saveCfg(storageKey, {
backend: currentBackend(),
backendUrl: url,
model: modelSelect.value,
thinkingMode: !!thinkingCheckbox.checked,
maxTokens: Math.max(0, parseInt(maxTokensInput.value, 10) || 0),
});
showToast(t("aiToastSettingsSaved"), "success");
closeModal();
if (onSaved) onSaved();
});
}
+1309
View File
File diff suppressed because it is too large Load Diff
+533 -10
View File
@@ -4,6 +4,7 @@
*/
import { initI18n, t } from "./i18n.js";
import { getSettings } from "./util.js";
// Initialize i18n before anything else
initI18n();
@@ -41,11 +42,32 @@ export function showToast(message, type = "info", duration = 3000) {
export function openModal(title, contentHtml) {
const overlay = document.getElementById("wfm-modal-overlay");
const titleEl = document.getElementById("wfm-modal-title");
let titleEl = document.getElementById("wfm-modal-title");
const bodyEl = document.getElementById("wfm-modal-body");
const titleInput = document.getElementById("wfm-modal-title-input");
if (!overlay || !titleEl || !bodyEl) return;
// This modal shell is shared by every caller (Workflow/Models/Nodes detail
// modals, Lab's keyframe editor, etc.). Some callers (e.g. workflow-tab.js's
// openDetailModal) inject extra header chrome after calling openModal() — a
// favorite star button, and a click-to-rename listener + tooltip/cursor on the
// title — but nothing ever tore that down again. The next caller to reuse this
// same DOM inherited it as stale leftovers: a Lab cell modal could show a
// favorite star wired to the PREVIOUS caller's workflow object, and clicking it
// silently toggled that unrelated workflow's favorite state. Clean slate every
// time, before any caller-specific chrome is added back on top.
titleEl.parentElement?.querySelectorAll(".wfm-fav-btn").forEach((el) => el.remove());
const freshTitleEl = titleEl.cloneNode(false); // drops any addEventListener from a prior caller
freshTitleEl.removeAttribute("title");
freshTitleEl.removeAttribute("style"); // also clears any leftover display:none from an interrupted rename
titleEl.replaceWith(freshTitleEl);
titleEl = freshTitleEl;
if (titleInput) {
titleInput.style.display = "none";
titleInput.value = "";
}
titleEl.textContent = title;
bodyEl.innerHTML = contentHtml;
overlay.style.display = "flex";
@@ -90,7 +112,7 @@ function initTabs() {
function applyI18nToHtml() {
// Tab labels
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp" };
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", gallery: "tabGallery", "image-edit": "tabImageEdit", video: "tabVideo", settings: "tabSettings", help: "tabHelp", ai: "tabAi", tagger: "tabTagger" };
document.querySelectorAll(".wfm-tab").forEach((tab) => {
const key = tabMap[tab.dataset.tab];
if (key) tab.textContent = t(key);
@@ -112,9 +134,15 @@ function applyI18nToHtml() {
if (listLoadBtn.disabled) listLoadBtn.title = t("selectCardFirst");
}
const listLoadVideoBtn = document.getElementById("wfm-list-load-video-btn");
if (listLoadVideoBtn) {
listLoadVideoBtn.textContent = t("loadInVideo");
if (listLoadVideoBtn.disabled) listLoadVideoBtn.title = t("selectCardFirst");
}
const listOpenComfyBtn = document.getElementById("wfm-list-open-comfyui-btn");
if (listOpenComfyBtn) {
listOpenComfyBtn.textContent = t("openInComfyUI");
listOpenComfyBtn.textContent = t("sendToCanvas");
if (listOpenComfyBtn.disabled) listOpenComfyBtn.title = t("selectCardFirst");
}
@@ -194,17 +222,109 @@ function applyI18nToHtml() {
if (btn.dataset.detailTab === "info") btn.textContent = t("modelsSideInfo");
if (btn.dataset.detailTab === "meta") btn.textContent = t("gallerySideMetadata");
if (btn.dataset.detailTab === "group") btn.textContent = t("modelsSideGroup");
if (btn.dataset.detailTab === "prompt") btn.textContent = t("gallerySidePrompt");
});
const galleryBulkDeselect = document.getElementById("wfm-gallery-bulk-deselect");
if (galleryBulkDeselect) galleryBulkDeselect.textContent = t("galleryBulkDeselectAll");
const galleryBulkSelectAll = document.getElementById("wfm-gallery-bulk-select-all");
if (galleryBulkSelectAll) galleryBulkSelectAll.textContent = t("galleryBulkSelectAll");
const galleryBulkGroupSelect = document.getElementById("wfm-gallery-bulk-group-select");
if (galleryBulkGroupSelect) {
const opt = galleryBulkGroupSelect.querySelector("option[value='']");
if (opt) opt.textContent = t("galleryBulkAddToGroup");
}
const galleryBulkGroupAdd = document.getElementById("wfm-gallery-bulk-group-add");
if (galleryBulkGroupAdd) galleryBulkGroupAdd.textContent = t("galleryBulkAdd");
const galleryBulkGroupRemove = document.getElementById("wfm-gallery-bulk-group-remove");
if (galleryBulkGroupRemove) galleryBulkGroupRemove.textContent = t("galleryBulkGroupRemove");
const galleryBulkFav = document.getElementById("wfm-gallery-bulk-fav");
if (galleryBulkFav) galleryBulkFav.textContent = t("galleryBulkFavAll");
const galleryBulkUnfav = document.getElementById("wfm-gallery-bulk-unfav");
if (galleryBulkUnfav) galleryBulkUnfav.textContent = t("galleryBulkUnfavAll");
const galleryBulkMove = document.getElementById("wfm-gallery-bulk-move");
if (galleryBulkMove) galleryBulkMove.textContent = t("galleryBulkMoveTo");
const galleryBulkExport = document.getElementById("wfm-gallery-bulk-export");
if (galleryBulkExport) galleryBulkExport.textContent = t("galleryBulkExport");
const galleryBulkPsd = document.getElementById("wfm-gallery-bulk-psd");
if (galleryBulkPsd) galleryBulkPsd.textContent = t("galleryBulkPsd");
const galleryBulkEditLayers = document.getElementById("wfm-gallery-bulk-edit-layers");
if (galleryBulkEditLayers) galleryBulkEditLayers.textContent = t("galleryBulkEditLayers");
const galleryBulkDelete = document.getElementById("wfm-gallery-bulk-delete");
if (galleryBulkDelete) galleryBulkDelete.textContent = t("galleryBulkDelete");
const galleryOpenTaggerBtn = document.getElementById("wfm-gallery-open-tagger-btn");
if (galleryOpenTaggerBtn) galleryOpenTaggerBtn.textContent = t("tabTagger");
// Gallery サブタブ (Output / ImagePrompt / Style_Catalog)
const galleryOutputSubtab = document.getElementById("wfm-gallery-subtab-output");
if (galleryOutputSubtab) galleryOutputSubtab.textContent = t("galleryTabOutput");
const galleryImagePromptSubtab = document.getElementById("wfm-gallery-subtab-imageprompt");
if (galleryImagePromptSubtab) galleryImagePromptSubtab.textContent = t("galleryTabImagePrompt");
const galleryStyleCatalogSubtab = document.getElementById("wfm-gallery-subtab-styleCatalog");
if (galleryStyleCatalogSubtab) galleryStyleCatalogSubtab.textContent = t("galleryTabStyleCatalog");
const galleryMetadataSubtab = document.getElementById("wfm-gallery-subtab-metadata");
if (galleryMetadataSubtab) galleryMetadataSubtab.textContent = t("galleryTabMetadata");
// ImagePrompt ギャラリーパネル
const imagePromptSearch = document.getElementById("wfm-imageprompt-search");
if (imagePromptSearch) imagePromptSearch.placeholder = t("gallerySearchPlaceholder");
const imagePromptRefreshBtn = document.getElementById("wfm-imageprompt-refresh-btn");
if (imagePromptRefreshBtn) imagePromptRefreshBtn.textContent = t("refresh");
const imagePromptTreeTitle = document.getElementById("wfm-imageprompt-tree-title");
if (imagePromptTreeTitle) imagePromptTreeTitle.textContent = t("galleryFolders");
const imagePromptListPlaceholder = document.getElementById("wfm-imageprompt-list-placeholder");
if (imagePromptListPlaceholder) imagePromptListPlaceholder.textContent = t("gallerySelectFolder");
const imagePromptNoSelection = document.getElementById("wfm-imageprompt-no-selection");
if (imagePromptNoSelection) imagePromptNoSelection.textContent = t("galleryNoSelection");
const imagePromptSelectedPromptTitle = document.getElementById("wfm-imageprompt-selected-prompt-title");
if (imagePromptSelectedPromptTitle) imagePromptSelectedPromptTitle.textContent = t("imagePromptSelectedPrompt");
const imagePromptSelectedPrompt = document.getElementById("wfm-imageprompt-selected-prompt");
if (imagePromptSelectedPrompt) imagePromptSelectedPrompt.placeholder = t("imagePromptNoPrompt");
const imagePromptSavePromptBtn = document.getElementById("wfm-imageprompt-save-prompt-btn");
if (imagePromptSavePromptBtn) imagePromptSavePromptBtn.textContent = t("save");
const imagePromptAddBtn = document.getElementById("wfm-imageprompt-add-btn");
if (imagePromptAddBtn) imagePromptAddBtn.textContent = t("imagePromptAddBtn");
const imagePromptChipsTitle = document.getElementById("wfm-imageprompt-chips-title");
if (imagePromptChipsTitle) imagePromptChipsTitle.textContent = t("imagePromptChipsTitle");
const imagePromptClearBtn = document.getElementById("wfm-imageprompt-clear-btn");
if (imagePromptClearBtn) imagePromptClearBtn.textContent = t("imagePromptClearBtn");
const imagePromptFinalPromptTitle = document.getElementById("wfm-imageprompt-final-prompt-title");
if (imagePromptFinalPromptTitle) imagePromptFinalPromptTitle.textContent = t("imagePromptFinalPromptTitle");
const imagePromptCopyBtn = document.getElementById("wfm-imageprompt-copy-btn");
if (imagePromptCopyBtn) imagePromptCopyBtn.textContent = t("copy");
// Style_Catalog ギャラリーパネル
const scSearch = document.getElementById("wfm-stylecatalog-search");
if (scSearch) scSearch.placeholder = t("stylecatalogSearchPlaceholder");
const scRefreshBtn = document.getElementById("wfm-stylecatalog-refresh-btn");
if (scRefreshBtn) scRefreshBtn.textContent = t("refresh");
const scTreeTitle = document.getElementById("wfm-stylecatalog-tree-title");
if (scTreeTitle) scTreeTitle.textContent = t("galleryFolders");
const scListPlaceholder = document.getElementById("wfm-stylecatalog-list-placeholder");
if (scListPlaceholder) scListPlaceholder.textContent = t("gallerySelectFolder");
const scNoSelection = document.getElementById("wfm-stylecatalog-no-selection");
if (scNoSelection) scNoSelection.textContent = t("galleryNoSelection");
const scPositiveTitle = document.getElementById("wfm-stylecatalog-positive-title");
if (scPositiveTitle) scPositiveTitle.textContent = t("stylecatalogPositive");
const scCopyPositiveBtn = document.getElementById("wfm-stylecatalog-copy-positive-btn");
if (scCopyPositiveBtn) scCopyPositiveBtn.textContent = t("copy");
const scNegativeTitle = document.getElementById("wfm-stylecatalog-negative-title");
if (scNegativeTitle) scNegativeTitle.textContent = t("stylecatalogNegative");
const scCopyNegativeBtn = document.getElementById("wfm-stylecatalog-copy-negative-btn");
if (scCopyNegativeBtn) scCopyNegativeBtn.textContent = t("copy");
const scSelectStyleBtn = document.getElementById("wfm-stylecatalog-select-style-btn");
if (scSelectStyleBtn) scSelectStyleBtn.textContent = t("stylecatalogSelectStyleBtn");
const scLoadGenuiBtn = document.getElementById("wfm-stylecatalog-load-genui-btn");
if (scLoadGenuiBtn) scLoadGenuiBtn.textContent = t("stylecatalogLoadGenuiBtn");
const scOpenMetadataBtn = document.getElementById("wfm-stylecatalog-open-metadata-btn");
if (scOpenMetadataBtn) scOpenMetadataBtn.textContent = t("stylecatalogOpenMetadataBtn");
// Prompt tab
const assistantHeader = document.querySelector(".wfm-prompt-split-left .wfm-prompt-split-header");
if (assistantHeader) assistantHeader.textContent = t("assistantSubtab");
const presetsHeader = document.querySelector(".wfm-prompt-split-right .wfm-prompt-split-header");
if (presetsHeader) presetsHeader.textContent = t("presetsSubtab");
const ollamaRefreshBtn = document.getElementById("wfm-ollama-refresh-btn");
if (ollamaRefreshBtn) ollamaRefreshBtn.textContent = t("refresh");
const ollamaTestBtn = document.getElementById("wfm-ollama-test-btn");
if (ollamaTestBtn) ollamaTestBtn.textContent = t("test");
const ollamaSettingsBtn = document.getElementById("wfm-ollama-settings-btn");
if (ollamaSettingsBtn) ollamaSettingsBtn.title = t("settings");
const ollamaAttachBtn = document.getElementById("wfm-ollama-attach-btn");
if (ollamaAttachBtn) ollamaAttachBtn.textContent = t("attachImage");
const ollamaClearBtn = document.getElementById("wfm-ollama-clear-btn");
@@ -224,6 +344,98 @@ function applyI18nToHtml() {
const presetCopyNegBtn = document.getElementById("wfm-preset-copy-neg-btn");
if (presetCopyNegBtn) presetCopyNegBtn.textContent = t("copyNegativePrompt");
// AI tab
document.querySelectorAll(".wfm-ai-subtab-btn").forEach(btn => {
if (btn.dataset.aiSubtab === "translate") btn.textContent = t("aiSubTabTranslate");
if (btn.dataset.aiSubtab === "vlm") btn.textContent = t("aiSubTabVlm");
if (btn.dataset.aiSubtab === "ai-settings") btn.textContent = t("aiSubTabSettings");
});
const aiLangMap = { ja: "aiLangJa", en: "aiLangEn", zh: "aiLangZh", free: "aiLangFree" };
[document.getElementById("wfm-ai-src-lang"), document.getElementById("wfm-ai-dst-lang")].forEach(sel => {
if (!sel) return;
sel.querySelectorAll("option").forEach(opt => {
const key = aiLangMap[opt.value];
if (key) opt.textContent = t(key);
});
});
const aiTransInput = document.getElementById("wfm-ai-trans-input");
if (aiTransInput) aiTransInput.placeholder = t("aiTransInputPlaceholder");
const aiTransOutput = document.getElementById("wfm-ai-trans-output");
if (aiTransOutput) aiTransOutput.placeholder = t("aiTransOutputPlaceholder");
const aiTransBtn = document.getElementById("wfm-ai-trans-btn");
if (aiTransBtn) aiTransBtn.textContent = t("aiTranslateBtn");
const aiTransCopyBtn = document.getElementById("wfm-ai-trans-copy-btn");
if (aiTransCopyBtn) aiTransCopyBtn.textContent = t("aiCopyBtn");
const aiVlmLabel = document.getElementById("wfm-ai-vlm-label");
if (aiVlmLabel) aiVlmLabel.textContent = t("aiVlmDropLabel");
const aiVlmTask = document.getElementById("wfm-ai-vlm-task");
if (aiVlmTask) {
aiVlmTask.querySelectorAll("option").forEach(opt => {
if (opt.value === "describe") opt.textContent = t("aiVlmDescribe");
if (opt.value === "prompt") opt.textContent = t("aiVlmPromptCreate");
});
}
const aiVlmRunBtn = document.getElementById("wfm-ai-vlm-run");
if (aiVlmRunBtn) aiVlmRunBtn.textContent = t("aiVlmRunBtn");
const aiVlmResult = document.getElementById("wfm-ai-vlm-result");
if (aiVlmResult) aiVlmResult.placeholder = t("aiVlmResultPlaceholder");
const aiVlmCopyBtn = document.getElementById("wfm-ai-vlm-copy");
if (aiVlmCopyBtn) aiVlmCopyBtn.textContent = t("aiCopyBtn");
const aiBackendTitle = document.getElementById("wfm-ai-settings-backend-title");
if (aiBackendTitle) aiBackendTitle.textContent = t("aiSettingsBackend");
const aiConnTitle = document.getElementById("wfm-ai-settings-conn-title");
if (aiConnTitle) aiConnTitle.textContent = t("aiSettingsConnection");
const aiTestBtn = document.getElementById("wfm-ai-test-btn");
if (aiTestBtn) aiTestBtn.textContent = t("aiSettingsTestBtn");
const aiModelTitle = document.getElementById("wfm-ai-settings-model-title");
if (aiModelTitle) aiModelTitle.textContent = t("aiSettingsModelSection");
const aiModelSel = document.getElementById("wfm-ai-model-select");
if (aiModelSel) {
const firstOpt = aiModelSel.querySelector("option[value='']");
if (firstOpt) firstOpt.textContent = t("aiSettingsModelPlaceholder");
}
const aiModelRefreshBtn = document.getElementById("wfm-ai-model-refresh-btn");
if (aiModelRefreshBtn) aiModelRefreshBtn.textContent = t("aiSettingsRefreshBtn");
const aiGenerationTitle = document.getElementById("wfm-ai-settings-generation-title");
if (aiGenerationTitle) aiGenerationTitle.textContent = t("aiSettingsGenerationTitle");
const aiThinkingModeLabel = document.getElementById("wfm-ai-thinking-mode-label");
if (aiThinkingModeLabel) aiThinkingModeLabel.textContent = t("aiSettingsThinkingMode");
const aiMaxTokensLabel = document.getElementById("wfm-ai-max-tokens-label");
if (aiMaxTokensLabel) aiMaxTokensLabel.textContent = t("aiSettingsMaxTokens");
const aiMaxTokensInput = document.getElementById("wfm-ai-max-tokens");
if (aiMaxTokensInput) aiMaxTokensInput.placeholder = t("aiSettingsMaxTokensPlaceholder");
const aiFreeLangTitle = document.getElementById("wfm-ai-settings-freelang-title");
if (aiFreeLangTitle) aiFreeLangTitle.textContent = t("aiSettingsFreeLang");
const aiFreeSrcLabel = document.getElementById("wfm-ai-free-src-label");
if (aiFreeSrcLabel) aiFreeSrcLabel.textContent = t("aiSettingsInputLang");
const aiFreeDstLabel = document.getElementById("wfm-ai-free-dst-label");
if (aiFreeDstLabel) aiFreeDstLabel.textContent = t("aiSettingsOutputLang");
const aiSaveBtn = document.getElementById("wfm-ai-settings-save-btn");
if (aiSaveBtn) aiSaveBtn.textContent = t("aiSettingsSaveBtn");
const aiChatImgGenLabel = document.getElementById("wfm-ai-chat-imggen-label-text");
if (aiChatImgGenLabel) aiChatImgGenLabel.textContent = t("aiChatImgGenToggle");
const aiChatGenTitle = document.getElementById("wfm-ai-settings-chatgen-title");
if (aiChatGenTitle) aiChatGenTitle.textContent = t("aiSettingsChatGenTitle");
const aiChatGenDedicatedLabel = document.getElementById("wfm-ai-chatgen-dedicated-label");
if (aiChatGenDedicatedLabel) aiChatGenDedicatedLabel.textContent = t("aiSettingsChatGenDedicated");
const aiChatGenI2ITitle = document.getElementById("wfm-ai-settings-chatgen-i2i-title");
if (aiChatGenI2ITitle) aiChatGenI2ITitle.textContent = t("aiSettingsChatI2IGenTitle");
const aiChatGenI2IDedicatedLabel = document.getElementById("wfm-ai-chatgen-i2i-dedicated-label");
if (aiChatGenI2IDedicatedLabel) aiChatGenI2IDedicatedLabel.textContent = t("aiSettingsChatGenDedicated");
const aiSkillSel = document.getElementById("wfm-ai-chat-skill-select");
if (aiSkillSel) {
const firstOpt = aiSkillSel.querySelector("option[value='']");
if (firstOpt) firstOpt.textContent = `-- ${t("aiSkillNone")} --`;
}
const aiSkillManageBtn = document.getElementById("wfm-ai-chat-skill-manage-btn");
if (aiSkillManageBtn) aiSkillManageBtn.title = t("aiSkillManageBtnTitle");
const aiSkillPanelTitle = document.querySelector(".wfm-ai-skill-panel-title");
if (aiSkillPanelTitle) aiSkillPanelTitle.textContent = t("aiSkillPanelTitle");
const aiSkillNewBtn = document.getElementById("wfm-ai-skill-new-btn");
if (aiSkillNewBtn) aiSkillNewBtn.textContent = t("aiSkillNewBtn");
const aiSkillContentTA = document.getElementById("wfm-ai-skill-editor-content");
if (aiSkillContentTA) aiSkillContentTA.placeholder = t("aiSkillContentPlaceholder");
// Group panel labels
const propTitle = document.querySelector("#wfm-side-tab-group .wfm-group-section-title");
if (propTitle) propTitle.textContent = t("properties");
@@ -265,28 +477,117 @@ function applyI18nToHtml() {
"wfm-help-gen-3": "helpGen3", "wfm-help-gen-4": "helpGen4",
"wfm-help-gen-5": "helpGen5", "wfm-help-gen-6": "helpGen6", "wfm-help-gen-7": "helpGen7",
"wfm-help-gen-8": "helpGen8", "wfm-help-gen-9": "helpGen9", "wfm-help-gen-10": "helpGen10",
"wfm-help-gen-11": "helpGen11", "wfm-help-gen-12": "helpGen12",
"wfm-help-gen-13": "helpGen13", "wfm-help-gen-14": "helpGen14",
"wfm-help-gen-15": "helpGen15", "wfm-help-gen-16": "helpGen16",
"wfm-help-gen-17": "helpGen17", "wfm-help-gen-18": "helpGen18",
"wfm-help-gen-19": "helpGen19",
"wfm-help-gen-20": "helpGen20", "wfm-help-gen-21": "helpGen21",
"wfm-help-gen-22": "helpGen22", "wfm-help-gen-23": "helpGen23",
"wfm-help-gen-24": "helpGen24", "wfm-help-gen-25": "helpGen25",
"wfm-help-gen-26": "helpGen26", "wfm-help-gen-27": "helpGen27",
"wfm-help-gen-28": "helpGen28",
"wfm-help-gen-29": "helpGen29",
"wfm-help-gen-30": "helpGen30",
"wfm-help-gen-31": "helpGen31",
"wfm-help-feeder-title": "helpFeederTitle",
"wfm-help-feeder-desc": "helpFeederDesc",
"wfm-help-feeder-imgloop-title": "helpFeederImgloopTitle",
"wfm-help-feeder-imgloop-desc": "helpFeederImgloopDesc",
"wfm-help-feeder-1": "helpFeeder1", "wfm-help-feeder-2": "helpFeeder2",
"wfm-help-feeder-3": "helpFeeder3", "wfm-help-feeder-4": "helpFeeder4",
"wfm-help-feeder-5": "helpFeeder5", "wfm-help-feeder-6": "helpFeeder6",
"wfm-help-feeder-7": "helpFeeder7", "wfm-help-feeder-8": "helpFeeder8",
"wfm-help-feeder-9": "helpFeeder9",
"wfm-help-feeder-gal-title": "helpFeederGalTitle",
"wfm-help-feeder-gal-desc": "helpFeederGalDesc",
"wfm-help-feeder-gal-1": "helpFeederGal1", "wfm-help-feeder-gal-2": "helpFeederGal2",
"wfm-help-feeder-gal-3": "helpFeederGal3", "wfm-help-feeder-gal-4": "helpFeederGal4",
"wfm-help-feeder-gal-5": "helpFeederGal5", "wfm-help-feeder-gal-6": "helpFeederGal6",
"wfm-help-lab-title": "helpLabTitle",
"wfm-help-lab-desc": "helpLabDesc",
"wfm-help-lab-card-columns-title": "helpLabCardColumnsTitle",
"wfm-help-lab-1": "helpLab1", "wfm-help-lab-2": "helpLab2",
"wfm-help-lab-3": "helpLab3", "wfm-help-lab-4": "helpLab4",
"wfm-help-lab-5": "helpLab5", "wfm-help-lab-6": "helpLab6",
"wfm-help-lab-7": "helpLab7", "wfm-help-lab-8": "helpLab8",
"wfm-help-lab-9": "helpLab9", "wfm-help-lab-10": "helpLab10",
"wfm-help-lab-11": "helpLab11", "wfm-help-lab-12": "helpLab12",
"wfm-help-lab-13": "helpLab13", "wfm-help-lab-14": "helpLab14",
"wfm-help-lab-15": "helpLab15",
"wfm-help-lab-16": "helpLab16", "wfm-help-lab-17": "helpLab17",
"wfm-help-lab-18": "helpLab18", "wfm-help-lab-19": "helpLab19",
"wfm-help-lab-card-plan-title": "helpLabCardPlanTitle",
"wfm-help-lab-plan-1": "helpLabPlan1", "wfm-help-lab-plan-2": "helpLabPlan2",
"wfm-help-lab-plan-3": "helpLabPlan3", "wfm-help-lab-plan-4": "helpLabPlan4",
"wfm-help-lab-plan-5": "helpLabPlan5", "wfm-help-lab-plan-6": "helpLabPlan6",
"wfm-help-lab-plan-7": "helpLabPlan7", "wfm-help-lab-plan-8": "helpLabPlan8",
"wfm-help-lab-plan-9": "helpLabPlan9", "wfm-help-lab-plan-10": "helpLabPlan10",
"wfm-help-lab-plan-11": "helpLabPlan11",
"wfm-help-lab-card-results-title": "helpLabCardResultsTitle",
"wfm-help-lab-results-1": "helpLabResults1", "wfm-help-lab-results-2": "helpLabResults2",
"wfm-help-lab-results-3": "helpLabResults3",
"wfm-help-prompt-1": "helpPrompt1", "wfm-help-prompt-2": "helpPrompt2",
"wfm-help-prompt-3": "helpPrompt3", "wfm-help-prompt-4": "helpPrompt4",
"wfm-help-prompt-5": "helpPrompt5", "wfm-help-prompt-6": "helpPrompt6",
"wfm-help-prompt-7": "helpPrompt7",
"wfm-help-prompt-7": "helpPrompt7", "wfm-help-prompt-8": "helpPrompt8",
"wfm-help-prompt-9": "helpPrompt9",
"wfm-help-prompt-card-style-title": "helpPromptCardStyleTitle",
"wfm-help-prompt-10": "helpPrompt10", "wfm-help-prompt-11": "helpPrompt11",
"wfm-help-prompt-12": "helpPrompt12", "wfm-help-prompt-13": "helpPrompt13",
"wfm-help-prompt-14": "helpPrompt14",
"wfm-help-prompt-card-toplevel-title": "helpPromptCardToplevel",
"wfm-help-prompt-15": "helpPrompt15",
"wfm-help-prompt-card-table-title": "helpPromptCardTable",
"wfm-help-prompt-16": "helpPrompt16", "wfm-help-prompt-17": "helpPrompt17",
"wfm-help-prompt-18": "helpPrompt18", "wfm-help-prompt-19": "helpPrompt19",
"wfm-help-prompt-20": "helpPrompt20", "wfm-help-prompt-21": "helpPrompt21",
"wfm-help-prompt-22": "helpPrompt22", "wfm-help-prompt-23": "helpPrompt23",
"wfm-help-prompt-24": "helpPrompt24", "wfm-help-prompt-25": "helpPrompt25",
"wfm-help-prompt-26": "helpPrompt26",
"wfm-help-settings-1": "helpSettings1", "wfm-help-settings-2": "helpSettings2",
"wfm-help-settings-3": "helpSettings3", "wfm-help-settings-4": "helpSettings4",
"wfm-help-settings-5": "helpSettings5", "wfm-help-settings-6": "helpSettings6",
"wfm-help-settings-7": "helpSettings7", "wfm-help-settings-8": "helpSettings8",
"wfm-help-settings-9": "helpSettings9", "wfm-help-settings-10": "helpSettings10",
"wfm-help-settings-11": "helpSettings11", "wfm-help-settings-12": "helpSettings12",
"wfm-help-settings-13": "helpSettings13", "wfm-help-settings-14": "helpSettings14",
"wfm-help-settings-15": "helpSettings15", "wfm-help-settings-16": "helpSettings16",
"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",
"wfm-help-nodes-7": "helpNodes7",
"wfm-help-models-1": "helpModels1", "wfm-help-models-2": "helpModels2",
"wfm-help-models-3": "helpModels3", "wfm-help-models-4": "helpModels4",
"wfm-help-models-5": "helpModels5", "wfm-help-models-6": "helpModels6",
"wfm-help-models-7": "helpModels7", "wfm-help-models-8": "helpModels8",
"wfm-help-models-9": "helpModels9",
"wfm-help-models-9": "helpModels9", "wfm-help-models-10": "helpModels10",
"wfm-help-models-11": "helpModels11", "wfm-help-models-12": "helpModels12",
"wfm-help-gallery-title": "helpGalleryTitle",
"wfm-help-gallery-1": "helpGallery1", "wfm-help-gallery-2": "helpGallery2",
"wfm-help-gallery-3": "helpGallery3", "wfm-help-gallery-4": "helpGallery4",
"wfm-help-gallery-5": "helpGallery5", "wfm-help-gallery-6": "helpGallery6",
"wfm-help-gallery-7": "helpGallery7", "wfm-help-gallery-8": "helpGallery8",
"wfm-help-gallery-9": "helpGallery9", "wfm-help-gallery-10": "helpGallery10",
"wfm-help-gallery-11": "helpGallery11", "wfm-help-gallery-12": "helpGallery12",
"wfm-help-gallery-13": "helpGallery13", "wfm-help-gallery-14": "helpGallery14",
"wfm-help-gallery-15": "helpGallery15", "wfm-help-gallery-16": "helpGallery16",
"wfm-help-gallery-17": "helpGallery17", "wfm-help-gallery-27": "helpGallery27",
"wfm-help-gallery-18": "helpGallery18", "wfm-help-gallery-19": "helpGallery19",
"wfm-help-gallery-20": "helpGallery20", "wfm-help-gallery-21": "helpGallery21",
"wfm-help-gallery-22": "helpGallery22", "wfm-help-gallery-23": "helpGallery23",
"wfm-help-gallery-24": "helpGallery24", "wfm-help-gallery-25": "helpGallery25",
"wfm-help-gallery-26": "helpGallery26",
"wfm-help-gallery-28": "helpGallery28", "wfm-help-gallery-29": "helpGallery29",
"wfm-help-gallery-30": "helpGallery30",
"wfm-help-gallery-card-styleprompt-title": "helpGalleryCardStyleprompt",
"wfm-help-gallery-card-stylecatalog-title": "helpGalleryCardStylecatalog",
"wfm-help-tagger-title": "helpTaggerTitle",
"wfm-help-tagger-1": "helpTagger1", "wfm-help-tagger-2": "helpTagger2",
"wfm-help-tagger-3": "helpTagger3", "wfm-help-tagger-4": "helpTagger4",
"wfm-help-tagger-5": "helpTagger5", "wfm-help-tagger-6": "helpTagger6",
"wfm-help-tagger-7": "helpTagger7", "wfm-help-tagger-8": "helpTagger8",
"wfm-help-tagger-9": "helpTagger9",
"wfm-help-sidepanel-title": "helpSidepanelTitle",
"wfm-help-sidepanel-1": "helpSidepanel1", "wfm-help-sidepanel-2": "helpSidepanel2",
"wfm-help-sidepanel-3": "helpSidepanel3", "wfm-help-sidepanel-4": "helpSidepanel4",
@@ -294,22 +595,201 @@ function applyI18nToHtml() {
"wfm-help-sidepanel-7": "helpSidepanel7", "wfm-help-sidepanel-8": "helpSidepanel8",
"wfm-help-sidepanel-9": "helpSidepanel9", "wfm-help-sidepanel-10": "helpSidepanel10",
"wfm-help-sidepanel-11": "helpSidepanel11", "wfm-help-sidepanel-12": "helpSidepanel12",
"wfm-help-sidepanel-13": "helpSidepanel13",
"wfm-help-sidepanel-14": "helpSidepanel14", "wfm-help-sidepanel-15": "helpSidepanel15",
"wfm-help-sidepanel-16": "helpSidepanel16",
"wfm-help-sidepanel-17": "helpSidepanel17",
"wfm-help-ai-title": "helpAiTitle",
"wfm-help-ai-1": "helpAi1", "wfm-help-ai-2": "helpAi2", "wfm-help-ai-3": "helpAi3",
"wfm-help-ai-4": "helpAi4", "wfm-help-ai-6": "helpAi6",
"wfm-help-ai-7": "helpAi7",
"wfm-help-ai-8": "helpAi8",
"wfm-help-ai-9": "helpAi9",
"wfm-help-ai-card-layout-title": "helpAiCardLayout",
"wfm-help-ai-card-translate-title": "helpAiCardTranslate",
"wfm-help-ai-card-chat-title": "helpAiCardChat",
"wfm-help-ai-card-svg-title": "helpAiCardSvg",
"wfm-help-ai-card-skills-title": "helpAiCardSkills",
"wfm-help-ai-card-skilltips-title": "helpAiCardSkillTips",
"wfm-help-ai-card-tools-title": "helpAiCardTools",
"wfm-help-ai-card-settings-title": "helpAiCardSettings",
"wfm-help-imageedit-title": "helpImageEditTitle",
"wfm-help-imageedit-tools-title": "helpImageEditToolsTitle",
"wfm-help-imageedit-layer-title": "helpImageEditLayerTitle",
"wfm-help-imageedit-text-title": "helpImageEditTextTitle",
"wfm-help-imageedit-export-title": "helpImageEditExportTitle",
"wfm-help-imageedit-kbd-title": "helpImageEditKbdTitle",
"wfm-help-imageedit-1": "helpImageEdit1", "wfm-help-imageedit-2": "helpImageEdit2", "wfm-help-imageedit-3": "helpImageEdit3",
"wfm-help-imageedit-4": "helpImageEdit4", "wfm-help-imageedit-5": "helpImageEdit5",
"wfm-help-imageedit-6": "helpImageEdit6", "wfm-help-imageedit-7": "helpImageEdit7",
"wfm-help-imageedit-8": "helpImageEdit8", "wfm-help-imageedit-9": "helpImageEdit9",
"wfm-help-imageedit-10": "helpImageEdit10", "wfm-help-imageedit-11": "helpImageEdit11",
"wfm-help-imageedit-12": "helpImageEdit12", "wfm-help-imageedit-13": "helpImageEdit13",
"wfm-help-imageedit-14": "helpImageEdit14", "wfm-help-imageedit-15": "helpImageEdit15",
"wfm-help-imageedit-16": "helpImageEdit16", "wfm-help-imageedit-17": "helpImageEdit17",
"wfm-help-imageedit-18": "helpImageEdit18",
"wfm-help-imageedit-19b": "helpImageEdit19b",
"wfm-help-imageedit-20": "helpImageEdit20", "wfm-help-imageedit-21": "helpImageEdit21",
"wfm-help-imageedit-22": "helpImageEdit22", "wfm-help-imageedit-23": "helpImageEdit23",
"wfm-help-imageedit-24": "helpImageEdit24", "wfm-help-imageedit-25": "helpImageEdit25",
"wfm-help-imageedit-26": "helpImageEdit26", "wfm-help-imageedit-27": "helpImageEdit27",
"wfm-help-imageedit-28": "helpImageEdit28", "wfm-help-imageedit-29": "helpImageEdit29",
"wfm-help-imageedit-30": "helpImageEdit30",
"wfm-help-imageedit-31": "helpImageEdit31", "wfm-help-imageedit-32": "helpImageEdit32",
"wfm-help-imageedit-33": "helpImageEdit33", "wfm-help-imageedit-34": "helpImageEdit34",
"wfm-help-imageedit-7b": "helpImageEdit7b", "wfm-help-imageedit-7c": "helpImageEdit7c",
"wfm-help-imageedit-7d": "helpImageEdit7d", "wfm-help-imageedit-7e": "helpImageEdit7e",
"wfm-help-imageedit-8b": "helpImageEdit8b",
"wfm-help-imageedit-blur-title": "helpImageEditBlurTitle",
"wfm-help-imageedit-blur-1": "helpImageEditBlur1", "wfm-help-imageedit-blur-2": "helpImageEditBlur2",
"wfm-help-imageedit-blur-3": "helpImageEditBlur3", "wfm-help-imageedit-blur-4": "helpImageEditBlur4",
"wfm-help-imageedit-blur-5": "helpImageEditBlur5", "wfm-help-imageedit-blur-6": "helpImageEditBlur6",
"wfm-help-imageedit-bgremove-title": "helpImageEditBgRemoveTitle",
"wfm-help-imageedit-bgremove-1": "helpImageEditBgRemove1", "wfm-help-imageedit-bgremove-2": "helpImageEditBgRemove2",
"wfm-help-imageedit-bgremove-3": "helpImageEditBgRemove3", "wfm-help-imageedit-bgremove-4": "helpImageEditBgRemove4",
"wfm-help-imageedit-bgremove-5": "helpImageEditBgRemove5",
"wfm-help-imageedit-mask-title": "helpImageEditMaskTitle",
"wfm-help-imageedit-mask-1": "helpImageEditMask1", "wfm-help-imageedit-mask-2": "helpImageEditMask2",
"wfm-help-imageedit-mask-3": "helpImageEditMask3", "wfm-help-imageedit-mask-4": "helpImageEditMask4",
"wfm-help-imageedit-mask-5": "helpImageEditMask5", "wfm-help-imageedit-mask-6": "helpImageEditMask6",
"wfm-help-imageedit-mask-7": "helpImageEditMask7", "wfm-help-imageedit-mask-8": "helpImageEditMask8",
"wfm-help-imageedit-mask-9": "helpImageEditMask9", "wfm-help-imageedit-mask-10": "helpImageEditMask10",
"wfm-help-imageedit-mask-11": "helpImageEditMask11", "wfm-help-imageedit-mask-12": "helpImageEditMask12",
"wfm-help-imageedit-mask-13": "helpImageEditMask13",
"wfm-help-imageedit-mask-14": "helpImageEditMask14",
"wfm-help-imageedit-gmic-title": "helpImageEditGmicTitle",
"wfm-help-imageedit-gmic-1": "helpImageEditGmic1", "wfm-help-imageedit-gmic-2": "helpImageEditGmic2",
"wfm-help-imageedit-gmic-3": "helpImageEditGmic3", "wfm-help-imageedit-gmic-4": "helpImageEditGmic4",
"wfm-help-imageedit-gmic-install-title": "helpImageEditGmicInstallTitle",
"wfm-help-imageedit-gmic-install-1": "helpImageEditGmicInstall1",
"wfm-help-imageedit-gmic-install-2": "helpImageEditGmicInstall2",
"wfm-help-imageedit-gmic-install-3": "helpImageEditGmicInstall3",
"wfm-help-imageedit-tabkbd-title": "helpImageEditTabKbdTitle",
"wfm-help-imageedit-tabkbd-1": "helpImageEdit22", "wfm-help-imageedit-tabkbd-2": "helpImageEdit23",
"wfm-help-imageedit-tabkbd-3": "helpImageEdit24", "wfm-help-imageedit-tabkbd-4": "helpImageEdit25",
"wfm-help-imageedit-tabkbd-5": "helpImageEdit26", "wfm-help-imageedit-tabkbd-6": "helpImageEdit27",
"wfm-help-imageedit-tabkbd-7": "helpImageEdit28", "wfm-help-imageedit-tabkbd-8": "helpImageEdit29",
"wfm-help-shortcuts-title": "helpShortcutsTitle",
"wfm-help-shortcuts-1": "helpShortcuts1", "wfm-help-shortcuts-2": "helpShortcuts2",
"wfm-help-shortcuts-3": "helpShortcuts3", "wfm-help-shortcuts-4": "helpShortcuts4",
"wfm-help-trouble-title": "helpTroubleTitle",
"wfm-help-trouble-1": "helpTrouble1", "wfm-help-trouble-2": "helpTrouble2",
"wfm-help-trouble-3": "helpTrouble3", "wfm-help-trouble-4": "helpTrouble4",
"wfm-help-trouble-5": "helpTrouble5", "wfm-help-trouble-6": "helpTrouble6",
"wfm-help-trouble-7": "helpTrouble7", "wfm-help-trouble-8": "helpTrouble8",
"wfm-help-trouble-9": "helpTrouble9",
"wfm-help-support-title": "helpSupportTitle",
"wfm-help-support-desc": "helpSupportDesc",
"wfm-help-github-desc": "helpGithubDesc",
"wfm-help-kofi-desc": "helpKofiDesc",
"wfm-help-thanks": "helpThanks",
// -- Help card headings (card-based redesign) --
"wfm-help-about-card-getting-started-title": "helpAboutCardGettingStarted",
"wfm-help-wf-title": "helpWfTitle",
"wfm-help-wf-card-browse-title": "helpWfCardBrowse",
"wfm-help-wf-card-groups-title": "helpWfCardGroups",
"wfm-help-wf-card-panel-title": "helpWfCardPanel",
"wfm-help-gen-title": "helpGenTitle",
"wfm-help-gen-card-connect-title": "helpGenCardConnect",
"wfm-help-gen-card-tabs-title": "helpGenCardTabs",
"wfm-help-gen-card-seed-title": "helpGenCardSeed",
"wfm-help-gen-card-batchsetup-title": "helpGenCardBatchSetup",
"wfm-help-gen-card-batchtypes-title": "helpGenCardBatchTypes",
"wfm-help-gen-card-lora-title": "helpGenCardLora",
"wfm-help-prompt-title": "helpPromptTitle",
"wfm-help-prompt-card-ai-title": "helpPromptCardAi",
"wfm-help-prompt-card-presets-title": "helpPromptCardPresets",
"wfm-help-prompt-card-wildcards-title": "helpPromptCardWildcards",
"wfm-help-metadata-card-overview-title": "helpMetadataCardOverview",
"wfm-help-metadata-card-extracted-title": "helpMetadataCardExtracted",
"wfm-help-metadata-card-formats-title": "helpMetadataCardFormats",
"wfm-help-settings-title": "helpSettingsTitle",
"wfm-help-settings-card-general-title": "helpSettingsCardGeneral",
"wfm-help-settings-card-connections-title": "helpSettingsCardConnections",
"wfm-help-settings-card-workflow-title": "helpSettingsCardWorkflow",
"wfm-help-settings-card-editor-title": "helpSettingsCardEditor",
"wfm-help-settings-card-misc-title": "helpSettingsCardMisc",
"wfm-help-nodes-title": "helpNodesTitle",
"wfm-help-nodes-card-browse-title": "helpNodesCardBrowse",
"wfm-help-nodes-card-groups-title": "helpNodesCardGroups",
"wfm-help-nodes-card-panel-title": "helpNodesCardPanel",
"wfm-help-gallery-card-browse-title": "helpGalleryCardBrowse",
"wfm-help-gallery-card-folder-title": "helpGalleryCardFolder",
"wfm-help-gallery-card-detail-title": "helpGalleryCardDetail",
"wfm-help-gallery-card-actions-title": "helpGalleryCardActions",
"wfm-help-gallery-card-formats-title": "helpGalleryCardFormats",
"wfm-help-models-title": "helpModelsTitle",
"wfm-help-models-card-browse-title": "helpModelsCardBrowse",
"wfm-help-models-card-civitai-title": "helpModelsCardCivitai",
"wfm-help-models-card-apply-title": "helpModelsCardApply",
"wfm-help-models-card-groups-title": "helpModelsCardGroups",
"wfm-help-models-card-bulk-title": "helpModelsCardBulk",
"wfm-help-sidepanel-card-tabs-title": "helpSidepanelCardTabs",
"wfm-help-sidepanel-card-dnd-title": "helpSidepanelCardDnd",
"wfm-help-sidepanel-card-info-title": "helpSidepanelCardInfo",
"wfm-help-sidepanel-card-ai-title": "helpSidepanelCardAi",
"wfm-help-sidepanel-card-nav-title": "helpSidepanelCardNav",
"wfm-help-tagger-card-overview-title": "helpTaggerCardOverview",
"wfm-help-tagger-card-single-title": "helpTaggerCardSingle",
"wfm-help-tagger-card-sending-title": "helpTaggerCardSending",
"wfm-help-tagger-card-batch-title": "helpTaggerCardBatch",
"wfm-help-imageedit-card-overview-title": "helpImageEditCardOverview",
"wfm-help-shortcuts-card-general-title": "helpShortcutsCardGeneral",
"wfm-help-trouble-card-connection-title": "helpTroubleCardConnection",
"wfm-help-trouble-card-workflow-title": "helpTroubleCardWorkflow",
"wfm-help-trouble-card-tagger-title": "helpTroubleCardTagger",
"wfm-help-video-title": "helpVideoTitle",
"wfm-help-video-desc": "helpVideoDesc",
"wfm-help-video-1": "helpVideo1", "wfm-help-video-2": "helpVideo2",
"wfm-help-video-3": "helpVideo3", "wfm-help-video-4": "helpVideo4",
"wfm-help-video-5": "helpVideo5", "wfm-help-video-6": "helpVideo6",
"wfm-help-video-7": "helpVideo7", "wfm-help-video-8": "helpVideo8",
"wfm-help-video-9": "helpVideo9", "wfm-help-video-10": "helpVideo10",
};
for (const [id, key] of Object.entries(helpIdMap)) {
const el = document.getElementById(id);
if (el) el.textContent = t(key);
}
// Search box placeholder
const helpSearch = document.getElementById("wfm-help-search");
if (helpSearch) {
helpSearch.placeholder = t("helpSearchPlaceholder");
helpSearch.addEventListener("input", _onHelpSearch);
}
// Jump-to-tab buttons
document.querySelectorAll(".wfm-help-jump-btn").forEach((btn) => {
btn.textContent = t("helpJumpToTab");
});
}
function _onHelpSearch(e) {
const q = e.target.value.trim().toLowerCase();
const navItems = document.querySelectorAll("[data-help-page]");
if (!q) {
navItems.forEach(btn => btn.classList.remove("search-hidden"));
return;
}
const matchedPages = new Set();
document.querySelectorAll(".wfm-help-page").forEach(page => {
const pageId = page.id.replace("wfm-help-page-", "");
if (page.textContent.toLowerCase().includes(q)) matchedPages.add(pageId);
});
let firstBtn = null;
navItems.forEach(btn => {
const pageId = btn.dataset.helpPage;
if (matchedPages.has(pageId)) {
btn.classList.remove("search-hidden");
if (!firstBtn) firstBtn = btn;
} else {
btn.classList.add("search-hidden");
}
});
if (firstBtn && !firstBtn.classList.contains("active")) firstBtn.click();
}
// ============================================
@@ -347,24 +827,67 @@ import { initWorkflowTab } from "./workflow-tab.js";
import { initNodesTab } from "./nodes-tab.js";
import { initGenerateTab } from "./generate-tab.js";
import { initPromptTab } from "./prompt-tab.js";
import { initSettingsTab, applyTheme, getSavedTheme } from "./settings-tab.js";
import { initPromptTableTab } from "./prompt-table.js";
import { initSettingsTab, applyTheme, getSavedTheme, applyTextareaFontSize, applyJsonColors, applyModelTabActiveColor } from "./settings-tab.js";
import { initModelsTab } from "./models-tab.js";
import { initGalleryTab } from "./gallery-tab.js";
import { initMetadataTab } from "./metadata-tab.js";
import { initAiTab } from "./ai-tab.js";
import { initTaggerTab } from "./tagger-tab.js";
import { imageEditTab } from "./image-edit-tab.js";
import { initVideoTab } from "./video-tab.js";
// Apply saved theme immediately to prevent flash of default theme
applyTheme(getSavedTheme());
// Apply saved textarea font size & JSON highlight colors
try {
const _s = getSettings();
if (_s.textareaFontSize) applyTextareaFontSize(_s.textareaFontSize);
applyJsonColors(_s.jsonColors);
applyModelTabActiveColor(_s.modelTabActiveColor);
} catch {}
function initHelpTab() {
document.querySelectorAll(".wfm-help-nav-item").forEach((btn) => {
btn.addEventListener("click", () => {
const page = btn.dataset.helpPage;
document.querySelectorAll(".wfm-help-nav-item").forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
document.querySelectorAll(".wfm-help-page").forEach((p) => p.classList.remove("active"));
document.getElementById(`wfm-help-page-${page}`)?.classList.add("active");
});
});
// Jump-to-tab buttons: switch to the real feature tab this help page documents
document.querySelectorAll(".wfm-help-jump-btn").forEach((btn) => {
btn.addEventListener("click", () => {
document.querySelector(`.wfm-tab[data-tab="${btn.dataset.jumpTab}"]`)?.click();
if (btn.dataset.jumpSubtab) {
document.querySelector(`.wfm-gallery-subtab-btn[data-gallery-subtab="${btn.dataset.jumpSubtab}"]`)?.click();
}
});
});
}
document.addEventListener("DOMContentLoaded", () => {
applyI18nToHtml();
initTabs();
initModal();
initHelpTab();
initSettingsTab(); // Settings first (applies saved URL)
initWorkflowTab();
initNodesTab();
initModelsTab();
initGenerateTab();
initPromptTab();
initPromptTableTab();
initMetadataTab();
initGalleryTab();
initAiTab();
initTaggerTab();
imageEditTab.init();
initVideoTab();
console.log("Workflow Studio: App initialized");
});
+103 -29
View File
@@ -18,8 +18,15 @@ export const comfyUI = {
connected: false,
generating: false,
currentPromptId: null,
// trackProgress() 実行中の Promise を promptId -> reject関数 で保持。
// WebSocket切断時に、待機中のPromiseを解決させずに放置してバッチループが
// 無言のまま停止する(例: カタログ作成バッチが特定件数で止まる)のを防ぐ。
_pendingTrackers: new Map(),
currentWorkflow: null,
currentAnalysis: null,
// ワークフロー読み込み時点のLora Loader (LoraManager)ノードの loras/text 状態。
// Stackグループチェックボックスのトグル時に、OFF側の「読み込み時の状態へ戻す」用に使う。
loraManagerSnapshots: {},
updateUrl(url) {
if (!url) {
@@ -66,10 +73,18 @@ export const comfyUI = {
this.socket = new WebSocket(url);
this.socket.onopen = () => resolve(true);
this.socket.onerror = () => resolve(false);
this.socket.onclose = () => { this.socket = null; };
this.socket.onclose = () => {
this.socket = null;
this._rejectPendingTrackers(new Error("WebSocket disconnected"));
};
});
},
_rejectPendingTrackers(err) {
for (const rejectFn of this._pendingTrackers.values()) rejectFn(err);
this._pendingTrackers.clear();
},
// Node info fetching
async fetchObjectInfo(nodeClass) {
const res = await fetch(`${this.baseUrl}/object_info/${nodeClass}`);
@@ -88,7 +103,18 @@ export const comfyUI = {
try {
const info = await this.fetchObjectInfo(cls);
if (info?.[cls]?.input?.required?.[inputKey]) {
return info[cls].input.required[inputKey][0] || [];
const inputDef = info[cls].input.required[inputKey];
const first = inputDef[0];
// V1: [["model1", "model2"], {}]
if (Array.isArray(first)) return first;
// 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 {}
}
@@ -121,17 +147,19 @@ export const comfyUI = {
},
async fetchDiffusionModels() {
return this._fetchModelList(
["UNETLoader", "UnetLoaderGGUF"],
"unet_name"
);
const [standard, gguf] = await Promise.all([
this._fetchModelList(["UNETLoader", "UnetLoaderGGUF"], "unet_name"),
this._fetchModelList(["LoaderGGUF", "LoaderGGUFAdvanced"], "gguf_name"),
]);
return [...new Set([...standard, ...gguf])];
},
async fetchTextEncoders() {
return this._fetchModelList(
["DualCLIPLoader", "CLIPLoader"],
"clip_name1"
);
const [dual, single] = await Promise.all([
this._fetchModelList(["DualCLIPLoader", "DualClipLoaderGGUF"], "clip_name1"),
this._fetchModelList(["CLIPLoader", "ClipLoaderGGUF"], "clip_name"),
]);
return [...new Set([...dual, ...single])];
},
async fetchHypernetworks() {
@@ -142,14 +170,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 [];
},
@@ -162,14 +193,16 @@ export const comfyUI = {
},
// Generation
async queuePrompt(workflow) {
async queuePrompt(workflow, extraData = null) {
const body = {
prompt: workflow,
client_id: this.clientId,
};
if (extraData) body.extra_data = extraData;
const res = await fetch(`${this.baseUrl}/prompt`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt: workflow,
client_id: this.clientId,
}),
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
@@ -178,12 +211,29 @@ export const comfyUI = {
return await res.json();
},
trackProgress(promptId, progressCallback) {
// timeoutMs: この時間内に完了/エラー/中断通知が来なければ強制的にreject。
// WebSocketの取りこぼしやexecution_interrupted未処理でPromiseが永久に
// ぶら下がり続け、バッチループが無言で停止するのを防ぐための安全弁。
trackProgress(promptId, progressCallback, timeoutMs = 10 * 60 * 1000) {
return new Promise((resolve, reject) => {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
reject(new Error("WebSocket not connected"));
return;
}
let settled = false;
const finish = (isResolve, value) => {
if (settled) return;
settled = true;
this.socket?.removeEventListener("message", handler);
clearTimeout(timer);
this._pendingTrackers.delete(promptId);
if (isResolve) resolve(value); else reject(value);
};
const timer = setTimeout(() => {
finish(false, new Error(`Generation timed out after ${Math.round(timeoutMs / 1000)}s (prompt_id=${promptId})`));
}, timeoutMs);
const handler = (event) => {
try {
const msg = JSON.parse(event.data);
@@ -193,17 +243,19 @@ export const comfyUI = {
}
if (msg.type === "executing" && msg.data?.prompt_id === promptId) {
if (msg.data.node === null) {
this.socket.removeEventListener("message", handler);
resolve();
finish(true);
}
}
if (msg.type === "execution_error" && msg.data?.prompt_id === promptId) {
this.socket.removeEventListener("message", handler);
reject(new Error(msg.data.exception_message || "Execution error"));
finish(false, new Error(msg.data.exception_message || "Execution error"));
}
if (msg.type === "execution_interrupted" && msg.data?.prompt_id === promptId) {
finish(false, new Error("Execution interrupted"));
}
} catch {}
};
this.socket.addEventListener("message", handler);
this._pendingTrackers.set(promptId, (err) => finish(false, err));
});
},
@@ -222,7 +274,13 @@ export const comfyUI = {
});
const res = await fetch(`${this.baseUrl}/view?${params}`);
if (!res.ok) throw new Error(`Failed to fetch image: HTTP ${res.status}`);
return await res.blob();
const blob = await res.blob();
// /view はSVGをセキュリティ上application/octet-streamで返すため、
// <img>で表示できるよう拡張子から正しいMIMEタイプへ付け替える
if (imageData.filename?.toLowerCase().endsWith(".svg") && blob.type !== "image/svg+xml") {
return blob.slice(0, blob.size, "image/svg+xml");
}
return blob;
},
async uploadImage(file, filename, overwrite = true) {
@@ -252,7 +310,7 @@ export const comfyUI = {
// High-level generate
async generate(workflow, options = {}) {
const { seedMode = "random", seedValue = -1, onProgress, onComplete, onError } = options;
const { seedMode = "random", seedValue = -1, onProgress, onComplete, onError, timeoutMs } = options;
this.generating = true;
try {
@@ -269,12 +327,12 @@ export const comfyUI = {
throw new Error("Failed to connect WebSocket");
}
// Queue prompt
const result = await this.queuePrompt(workflow);
// Queue prompt — pass workflow as extra_pnginfo so SaveImage embeds it in PNG metadata
const result = await this.queuePrompt(workflow, { extra_pnginfo: { workflow } });
this.currentPromptId = result.prompt_id;
// Track progress
await this.trackProgress(result.prompt_id, onProgress);
await this.trackProgress(result.prompt_id, onProgress, timeoutMs);
// Get history/results
const history = await this.getHistory(result.prompt_id);
@@ -282,6 +340,9 @@ export const comfyUI = {
// Extract images from SaveImage outputs only
const images = [];
// comfyui-tosvg の "Save SVG String" ノードは images ではなく
// saved_svg(ファイル名) / path(絶対パス) という独自キーで返す
const svgOutputs = [];
const outputs = history.outputs || {};
for (const nodeOutput of Object.values(outputs)) {
if (nodeOutput.images) {
@@ -289,10 +350,23 @@ export const comfyUI = {
images.push(img);
}
}
if (nodeOutput.saved_svg) {
// ComfyUI の実行エンジンは ui 出力の各値をイテラブルとして連結するため、
// ノード側が単一文字列で返すと 1 文字ずつ分解された配列になってしまう。
// (例: "a.svg" -> ["a",".","s","v","g"]) 文字配列を検出したら結合して復元する。
const joinIfCharArray = (v) =>
Array.isArray(v) && v.every((c) => typeof c === "string" && c.length === 1)
? v.join("")
: v;
svgOutputs.push({
filename: joinIfCharArray(nodeOutput.saved_svg),
path: joinIfCharArray(nodeOutput.path) || "",
});
}
}
onComplete?.(images, seed);
return { images, seed };
return { images, seed, svgOutputs };
} catch (err) {
onError?.(err);
throw err;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+859
View File
@@ -0,0 +1,859 @@
/**
* Feeder Tab - ImageFeeder node control (Image Loop mode)
* + WFS_GalleryFeeder node control (Gallery mode)
*/
import { comfyUI } from "./comfyui-client.js";
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { FEEDER_GROUP, ensureFeederGroup } from "./gallery-tab.js";
// ── Module State ──────────────────────────────────────────────────
const _s = {
dir: "", // current folder relative path (loop mode)
images: [], // filenames in current folder (loop mode)
selected: new Set(),// selected filenames (loop mode)
presets: {}, // {presetName: {directory, selected_files}}
running: false, // feeder run loop active
mode: localStorage.getItem("wfm_feeder_mode") || "loop", // "loop" | "gallery"
};
// Gallery mode state
const _gs = {
groups: [], // [{name}]
group: FEEDER_GROUP, // selected group name
images: [], // absolute paths in selected group
idx: 0, // current index
};
// ── Node helpers ──────────────────────────────────────────────────
function _feederNodes() {
const wf = comfyUI.currentWorkflow;
if (!wf) return [];
return Object.entries(wf)
.filter(([, n]) => n?.class_type === "ImageFeeder")
.map(([id, n]) => ({ id, title: n._meta?.title || `ImageFeeder` }));
}
function _galFeederNodes() {
const wf = comfyUI.currentWorkflow;
if (!wf) return [];
return Object.entries(wf)
.filter(([, n]) => n?.class_type === "WFS_GalleryFeeder")
.map(([id, n]) => ({ id, title: n._meta?.title || `GalleryFeeder` }));
}
export function refreshFeederNodeList() {
if (_s.mode === "gallery") {
_refreshGalNodeList();
} else {
const sel = document.getElementById("wfm-feeder-node-sel");
if (!sel) return;
const nodes = _feederNodes();
if (nodes.length === 0) {
sel.innerHTML = `<option value="">-- No ImageFeeder node --</option>`;
return;
}
const prevVal = sel.value;
sel.innerHTML = nodes.map(n =>
`<option value="${n.id}">${n.title} (ID:${n.id})</option>`
).join("");
if (prevVal && nodes.find(n => n.id === prevVal)) sel.value = prevVal;
_loadFromNode(sel.value || nodes[0].id);
}
}
function _refreshGalNodeList() {
const sel = document.getElementById("wfm-feeder-gal-node-sel");
if (!sel) return;
const nodes = _galFeederNodes();
if (nodes.length === 0) {
sel.innerHTML = `<option value="">-- No WFS_GalleryFeeder node --</option>`;
return;
}
const prevVal = sel.value;
sel.innerHTML = nodes.map(n =>
`<option value="${n.id}">${n.title} (ID:${n.id})</option>`
).join("");
if (prevVal && nodes.find(n => n.id === prevVal)) sel.value = prevVal;
_loadFromGalNode(sel.value || nodes[0].id);
}
function _loadFromNode(nodeId) {
const wf = comfyUI.currentWorkflow;
if (!wf?.[nodeId]) return;
const inp = wf[nodeId].inputs || {};
_setVal("wfm-feeder-dir-input", inp.directory || "");
_setVal("wfm-feeder-sort", inp.sort_mode || "ascending");
_setVal("wfm-feeder-index", inp.index ?? 0);
_setVal("wfm-feeder-start", inp.start_index ?? 0);
_setVal("wfm-feeder-end", inp.end_index ?? 0);
_setVal("wfm-feeder-batch", inp.batch_size ?? 1);
_setVal("wfm-feeder-seed", inp.seed ?? 0);
_setCheck("wfm-feeder-use-sel", inp.use_selection ?? true);
_s.selected.clear();
try {
const arr = JSON.parse(inp.selected_files || "[]");
if (Array.isArray(arr)) arr.forEach(f => _s.selected.add(f));
} catch {}
const dir = inp.directory || "";
if (_s.dir !== dir) {
_s.dir = dir;
_loadImages(dir);
_highlightTreeRow(dir);
} else {
_refreshGridCbs();
}
_updateStatus();
}
function _loadFromGalNode(nodeId) {
const wf = comfyUI.currentWorkflow;
if (!wf?.[nodeId]) return;
const inp = wf[nodeId].inputs || {};
const group = inp.group_name || FEEDER_GROUP;
_setVal("wfm-feeder-gal-sort", inp.sort_mode || "filename_asc");
_setVal("wfm-feeder-gal-index", inp.index ?? 0);
_setVal("wfm-feeder-gal-seed", inp.seed ?? 0);
_gs.idx = inp.index ?? 0;
if (_gs.group !== group) {
_gs.group = group;
_setGalGroupSelect(group);
_loadGalImages(group);
}
}
function _applyToWorkflow() {
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
const wf = comfyUI.currentWorkflow;
if (!nodeId || !wf?.[nodeId]) {
showToast(t("feederNoNode"), "error");
return;
}
_applyToNode(nodeId);
showToast(t("appliedToWorkflow"), "success");
}
function _applyGalToWorkflow() {
const nodeId = document.getElementById("wfm-feeder-gal-node-sel")?.value;
const wf = comfyUI.currentWorkflow;
if (!nodeId || !wf?.[nodeId]) {
showToast(t("feederGalNoNode"), "error");
return;
}
_applyToGalNode(nodeId);
showToast(t("appliedToWorkflow"), "success");
}
// ── Run Loop ──────────────────────────────────────────────────────
function _setRunUI(running) {
const runBtn = document.getElementById("wfm-feeder-run-btn");
const stopBtn = document.getElementById("wfm-feeder-stop-btn");
if (runBtn) runBtn.disabled = running;
if (stopBtn) stopBtn.disabled = !running;
}
function _setGalRunUI(running) {
const runBtn = document.getElementById("wfm-feeder-gal-run-btn");
const stopBtn = document.getElementById("wfm-feeder-gal-stop-btn");
if (runBtn) runBtn.disabled = running;
if (stopBtn) stopBtn.disabled = !running;
}
function _applyToNode(nodeId) {
const wf = comfyUI.currentWorkflow;
const inp = wf[nodeId].inputs;
inp.directory = _s.dir;
inp.sort_mode = document.getElementById("wfm-feeder-sort")?.value || "ascending";
inp.index = parseInt(document.getElementById("wfm-feeder-index")?.value) || 0;
inp.start_index = parseInt(document.getElementById("wfm-feeder-start")?.value) || 0;
inp.end_index = parseInt(document.getElementById("wfm-feeder-end")?.value) || 0;
inp.batch_size = parseInt(document.getElementById("wfm-feeder-batch")?.value) || 1;
inp.seed = parseInt(document.getElementById("wfm-feeder-seed")?.value) || 0;
inp.use_selection = document.getElementById("wfm-feeder-use-sel")?.checked ?? true;
inp.selected_files = JSON.stringify([..._s.selected]);
}
function _applyToGalNode(nodeId) {
const wf = comfyUI.currentWorkflow;
const inp = wf[nodeId].inputs;
inp.group_name = _gs.group;
inp.index = _gs.idx;
inp.sort_mode = document.getElementById("wfm-feeder-gal-sort")?.value || "filename_asc";
inp.seed = parseInt(document.getElementById("wfm-feeder-gal-seed")?.value) || 0;
}
async function _startRun() {
if (_s.running) return;
if (!comfyUI.currentWorkflow) { showToast(t("noWorkflowLoaded"), "error"); return; }
if (!comfyUI.connected) { showToast(t("notConnectedToComfyUI"), "error"); return; }
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
showToast(t("feederNoNode"), "error");
return;
}
const wsOk = await comfyUI.connectWebSocket();
if (!wsOk) { showToast(t("wsConnectionFailed"), "error"); return; }
_s.running = true;
_setRunUI(true);
const progressBar = document.getElementById("wfm-gen-progress-bar");
const progressText = document.getElementById("wfm-gen-progress-text");
const resultImg = document.getElementById("wfm-gen-result-img");
let _lastSync = null;
const _syncHandler = (ev) => {
try {
const msg = JSON.parse(ev.data);
if (msg.type === "image_loop_node_sync" && String(msg.data?.node_id) === String(nodeId)) {
_lastSync = msg.data;
if (msg.data.thumbnail_path) {
const p = msg.data.thumbnail_path;
_showPreview(p, p.split("/").pop());
}
}
} catch {}
};
comfyUI.socket.addEventListener("message", _syncHandler);
let count = 0;
try {
while (_s.running) {
_lastSync = null;
_applyToNode(nodeId);
const wf = comfyUI.currentWorkflow;
const inp = wf[nodeId].inputs;
if (progressBar) progressBar.style.width = "0%";
if (progressText) progressText.textContent = `#${++count} 0%`;
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
const { images, seed } = await comfyUI.generate(
{ ...wf },
{
seedMode,
seedValue,
onProgress: (pct) => {
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
if (progressText) progressText.textContent = `#${count} ${(pct * 100).toFixed(0)}%`;
},
}
);
const seedEl = document.getElementById("wfm-gen-seed-value");
if (seedEl) seedEl.value = seed;
if (progressBar) progressBar.style.width = "100%";
if (images.length > 0 && resultImg) {
const blob = await comfyUI.getImageBlob(images[0]);
resultImg.src = URL.createObjectURL(blob);
resultImg.style.display = "block";
}
if (!_s.running) break;
const control = document.getElementById("wfm-feeder-control-after")?.value || "loop";
if (control === "fixed") {
// index を変えない
} else if (_lastSync) {
const indexEl = document.getElementById("wfm-feeder-index");
if (indexEl) indexEl.value = _lastSync.next_index;
if (control === "increment" && !_lastSync.has_next) {
_s.running = false;
showToast(t("feederComplete", count), "success");
break;
}
}
}
} catch (err) {
if (_s.running) showToast(t("feederRunError", err.message), "error");
} finally {
comfyUI.socket?.removeEventListener("message", _syncHandler);
_s.running = false;
_setRunUI(false);
if (progressText) progressText.textContent = `Done (${count} generated)`;
}
}
async function _stopRun() {
_s.running = false;
try { await comfyUI.interrupt(); } catch {}
_setRunUI(false);
showToast(t("feederStopped"), "info");
}
// ── Gallery Mode Run Loop ─────────────────────────────────────────
async function _startGalRun() {
if (_s.running) return;
if (!comfyUI.currentWorkflow) { showToast(t("noWorkflowLoaded"), "error"); return; }
if (!comfyUI.connected) { showToast(t("notConnectedToComfyUI"), "error"); return; }
const nodeId = document.getElementById("wfm-feeder-gal-node-sel")?.value;
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
showToast(t("feederGalNoNode"), "error");
return;
}
if (_gs.images.length === 0) {
showToast(t("feederGalEmptyGroup"), "error");
return;
}
const wsOk = await comfyUI.connectWebSocket();
if (!wsOk) { showToast(t("wsConnectionFailed"), "error"); return; }
_s.running = true;
_setGalRunUI(true);
const progressBar = document.getElementById("wfm-gen-progress-bar");
const progressText = document.getElementById("wfm-gen-progress-text");
const resultImg = document.getElementById("wfm-gen-result-img");
const indexEl = document.getElementById("wfm-feeder-gal-index");
const total = _gs.images.length;
let count = 0;
try {
while (_s.running) {
_applyToGalNode(nodeId);
if (progressBar) progressBar.style.width = "0%";
if (progressText) progressText.textContent = `#${++count} [${_gs.idx + 1}/${total}] 0%`;
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
const { images, seed } = await comfyUI.generate(
{ ...comfyUI.currentWorkflow },
{
seedMode,
seedValue,
onProgress: (pct) => {
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
if (progressText) progressText.textContent = `#${count} [${_gs.idx + 1}/${total}] ${(pct * 100).toFixed(0)}%`;
},
}
);
const seedEl = document.getElementById("wfm-gen-seed-value");
if (seedEl) seedEl.value = seed;
if (progressBar) progressBar.style.width = "100%";
if (images.length > 0 && resultImg) {
const blob = await comfyUI.getImageBlob(images[0]);
resultImg.src = URL.createObjectURL(blob);
resultImg.style.display = "block";
}
if (!_s.running) break;
const control = document.getElementById("wfm-feeder-gal-control-after")?.value || "loop";
const nextIdx = (_gs.idx + 1) % total;
const isLast = _gs.idx === total - 1;
if (control === "fixed") {
// idx を変えない
} else if (control === "increment" && isLast) {
_s.running = false;
showToast(t("feederComplete", count), "success");
break;
} else {
_gs.idx = nextIdx;
if (indexEl) indexEl.value = _gs.idx;
_highlightGalCard(_gs.images[_gs.idx]);
}
}
} catch (err) {
if (_s.running) showToast(t("feederRunError", err.message), "error");
} finally {
_s.running = false;
_setGalRunUI(false);
if (progressText) progressText.textContent = `Done (${count} generated)`;
}
}
async function _stopGalRun() {
_s.running = false;
try { await comfyUI.interrupt(); } catch {}
_setGalRunUI(false);
showToast(t("feederStopped"), "info");
}
// ── Folder Tree (loop mode) ───────────────────────────────────────
async function _loadTree() {
const container = document.getElementById("wfm-feeder-tree");
if (!container) return;
container.innerHTML = `<div class="wfm-feeder-tree-msg">Loading...</div>`;
try {
const res = await fetch("/image_loop/tree");
if (!res.ok) throw new Error(res.status);
const data = await res.json();
_renderTree(data.tree || [], container);
} catch (err) {
container.innerHTML = `<div class="wfm-feeder-tree-msg">Cannot reach image-loop API</div>`;
console.warn("[Feeder] tree load failed:", err);
}
}
function _renderTree(items, container, depth = 0) {
if (depth === 0) {
container.innerHTML = "";
container.appendChild(_makeTreeRow("", "🏠 (root)", 0));
}
for (const item of items) {
const icon = item.children?.length > 0 ? "📂" : "📁";
container.appendChild(_makeTreeRow(item.path, `${icon} ${item.name}`, depth + 1));
if (item.children?.length > 0) _renderTree(item.children, container, depth + 1);
}
}
function _makeTreeRow(path, label, depth) {
const row = document.createElement("div");
row.className = "wfm-feeder-tree-row" + (_s.dir === path ? " active" : "");
row.style.paddingLeft = `${8 + depth * 12}px`;
row.dataset.path = path;
row.textContent = label;
row.title = path || "(root)";
row.addEventListener("click", () => _selectDir(path));
return row;
}
function _selectDir(path) {
if (_s.dir !== path) {
_s.selected.clear();
_s.dir = path;
_setVal("wfm-feeder-dir-input", path);
}
_highlightTreeRow(path);
_loadImages(path);
_updateStatus();
}
function _highlightTreeRow(path) {
document.querySelectorAll(".wfm-feeder-tree-row").forEach(el => {
el.classList.toggle("active", el.dataset.path === path);
});
}
// ── Image Grid (loop mode) ────────────────────────────────────────
async function _loadImages(dir) {
const grid = document.getElementById("wfm-feeder-grid");
if (!grid) return;
grid.innerHTML = `<div class="wfm-feeder-grid-msg">Loading...</div>`;
try {
const url = "/image_loop/images" + (dir ? `?dir=${encodeURIComponent(dir)}` : "");
const res = await fetch(url);
if (!res.ok) throw new Error(res.status);
const data = await res.json();
_s.images = data.images || [];
_renderGrid();
} catch (err) {
_s.images = [];
grid.innerHTML = `<div class="wfm-feeder-grid-msg" style="color:var(--wfm-danger)">Load failed: ${err.message}</div>`;
}
_updateStatus();
}
function _renderGrid() {
const grid = document.getElementById("wfm-feeder-grid");
if (!grid) return;
if (_s.images.length === 0) {
grid.innerHTML = `<div class="wfm-feeder-grid-msg">No images found</div>`;
return;
}
grid.innerHTML = "";
for (const fname of _s.images) grid.appendChild(_makeCard(fname));
}
function _makeCard(fname) {
const relPath = _s.dir ? `${_s.dir}/${fname}` : fname;
const checked = _s.selected.has(fname);
const card = document.createElement("div");
card.className = "wfm-feeder-card" + (checked ? " selected" : "");
card.dataset.name = fname;
const cb = document.createElement("input");
cb.type = "checkbox";
cb.className = "wfm-feeder-card-cb";
cb.checked = checked;
cb.addEventListener("change", e => {
e.stopPropagation();
if (cb.checked) _s.selected.add(fname);
else _s.selected.delete(fname);
card.classList.toggle("selected", cb.checked);
_updateStatus();
});
const img = document.createElement("img");
img.className = "wfm-feeder-card-img";
img.loading = "lazy";
img.src = `/image_loop/thumbnail?path=${encodeURIComponent(relPath)}`;
img.onerror = () => { img.style.display = "none"; card.style.minHeight = "110px"; };
const name = document.createElement("div");
name.className = "wfm-feeder-card-name";
name.textContent = fname;
name.title = fname;
card.append(cb, img, name);
card.addEventListener("click", e => {
if (e.target === cb) return;
_showPreview(relPath, fname);
});
return card;
}
function _refreshGridCbs() {
document.querySelectorAll(".wfm-feeder-card").forEach(card => {
const sel = _s.selected.has(card.dataset.name);
card.classList.toggle("selected", sel);
const cb = card.querySelector("input[type=checkbox]");
if (cb) cb.checked = sel;
});
}
function _selectAll() {
_s.images.forEach(f => _s.selected.add(f));
_refreshGridCbs();
_updateStatus();
}
function _deselectAll() {
_s.images.forEach(f => _s.selected.delete(f));
_refreshGridCbs();
_updateStatus();
}
function _updateStatus() {
const el = document.getElementById("wfm-feeder-status");
if (!el) return;
const inCurrent = _s.images.filter(f => _s.selected.has(f)).length;
el.textContent = `📂 ${_s.dir || "(root)"} | ${inCurrent} / ${_s.images.length} selected`;
}
// ── Gallery Mode: Group & Image Grid ─────────────────────────────
async function _loadGalGroups() {
try {
const res = await fetch("/wfm/gallery/groups");
if (!res.ok) throw new Error(res.status);
const data = await res.json();
_gs.groups = data.groups || [];
_renderGalGroupSelect();
} catch (err) {
console.warn("[Feeder] loadGalGroups failed:", err);
}
}
function _renderGalGroupSelect() {
const sel = document.getElementById("wfm-feeder-gal-group");
if (!sel) return;
sel.innerHTML = _gs.groups
.map(g => `<option value="${g.name}"${g.name === _gs.group ? " selected" : ""}>${g.name}</option>`)
.join("");
if (!_gs.groups.find(g => g.name === _gs.group) && _gs.groups.length > 0) {
_gs.group = _gs.groups[0].name;
}
}
function _setGalGroupSelect(group) {
const sel = document.getElementById("wfm-feeder-gal-group");
if (sel) sel.value = group;
}
async function _loadGalImages(group) {
const grid = document.getElementById("wfm-feeder-gal-grid");
const statusEl = document.getElementById("wfm-feeder-gal-status");
if (!grid) return;
grid.innerHTML = `<div class="wfm-feeder-grid-msg">Loading...</div>`;
try {
const res = await fetch(`/wfm/gallery/groups/${encodeURIComponent(group)}/images`);
if (!res.ok) throw new Error(res.status);
const data = await res.json();
_gs.images = data.images || [];
_gs.idx = 0;
const idxEl = document.getElementById("wfm-feeder-gal-index");
if (idxEl) idxEl.value = 0;
_renderGalGrid();
if (statusEl) statusEl.textContent = `${_gs.images.length} image(s) in "${group}"`;
} catch (err) {
_gs.images = [];
grid.innerHTML = `<div class="wfm-feeder-grid-msg" style="color:var(--wfm-danger)">Load failed: ${err.message}</div>`;
if (statusEl) statusEl.textContent = "";
}
}
function _renderGalGrid() {
const grid = document.getElementById("wfm-feeder-gal-grid");
if (!grid) return;
if (_gs.images.length === 0) {
grid.innerHTML = `<div class="wfm-feeder-grid-msg">No images in this group</div>`;
return;
}
grid.innerHTML = "";
_gs.images.forEach((absPath, i) => grid.appendChild(_makeGalCard(absPath, i)));
}
function _makeGalCard(absPath, idx) {
const fname = absPath.replace(/\\/g, "/").split("/").pop();
const card = document.createElement("div");
card.className = "wfm-feeder-card" + (idx === _gs.idx ? " selected" : "");
card.dataset.path = absPath;
card.dataset.idx = idx;
const img = document.createElement("img");
img.className = "wfm-feeder-card-img";
img.loading = "lazy";
img.src = `/wfm/gallery/image/serve?path=${encodeURIComponent(absPath)}`;
img.onerror = () => { img.style.display = "none"; card.style.minHeight = "110px"; };
const name = document.createElement("div");
name.className = "wfm-feeder-card-name";
name.textContent = fname;
name.title = fname;
card.append(img, name);
card.addEventListener("click", () => {
_gs.idx = idx;
const idxEl = document.getElementById("wfm-feeder-gal-index");
if (idxEl) idxEl.value = idx;
_highlightGalCard(absPath);
_showGalPreview(absPath, fname);
});
return card;
}
function _highlightGalCard(absPath) {
document.querySelectorAll("#wfm-feeder-gal-grid .wfm-feeder-card").forEach(c => {
c.classList.toggle("selected", c.dataset.path === absPath);
});
}
// ── Preview Panel ────────────────────────────────────────────────
async function _showPreview(relPath, fname) {
const imgEl = document.getElementById("wfm-feeder-preview-img");
const nameEl = document.getElementById("wfm-feeder-preview-name");
const infoEl = document.getElementById("wfm-feeder-preview-info");
if (imgEl) {
imgEl.src = `/image_loop/thumbnail?path=${encodeURIComponent(relPath)}`;
imgEl.style.display = "block";
}
if (nameEl) nameEl.textContent = fname;
if (infoEl) infoEl.textContent = "Loading...";
try {
const res = await fetch(`/image_loop/image_info?path=${encodeURIComponent(relPath)}`);
if (res.ok && infoEl) {
const d = await res.json();
const kb = d.size_bytes ? (d.size_bytes / 1024).toFixed(1) + " KB" : "";
infoEl.textContent = `${d.width ?? "?"}×${d.height ?? "?"} px\n${kb}`;
}
} catch { if (infoEl) infoEl.textContent = ""; }
}
async function _showGalPreview(absPath, fname) {
const imgEl = document.getElementById("wfm-feeder-preview-img");
const nameEl = document.getElementById("wfm-feeder-preview-name");
const infoEl = document.getElementById("wfm-feeder-preview-info");
if (imgEl) {
imgEl.src = `/wfm/gallery/image/serve?path=${encodeURIComponent(absPath)}`;
imgEl.style.display = "block";
}
if (nameEl) nameEl.textContent = fname;
if (infoEl) infoEl.textContent = "";
}
// ── Presets (loop mode) ───────────────────────────────────────────
async function _loadPresets() {
try {
const res = await fetch("/image_feeder/presets");
if (!res.ok) return;
_s.presets = await res.json();
} catch { _s.presets = {}; }
_renderPresets();
}
function _renderPresets() {
const sel = document.getElementById("wfm-feeder-preset-sel");
if (!sel) return;
const names = Object.keys(_s.presets).sort();
sel.innerHTML = `<option value="">-- Select preset --</option>` +
names.map(n => `<option value="${n}">${n}</option>`).join("");
}
async function _savePreset() {
const name = document.getElementById("wfm-feeder-preset-name")?.value.trim();
if (!name) { showToast(t("enterPresetName"), "error"); return; }
const sel = _s.images.filter(f => _s.selected.has(f));
try {
const res = await fetch("/image_feeder/presets", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, directory: _s.dir, selected_files: sel }),
});
if (res.ok) {
showToast(t("presetSavedName", name), "success");
const nameInput = document.getElementById("wfm-feeder-preset-name");
if (nameInput) nameInput.value = "";
await _loadPresets();
const selEl = document.getElementById("wfm-feeder-preset-sel");
if (selEl) selEl.value = name;
} else { showToast(t("saveFailed"), "error"); }
} catch (err) { showToast(t("saveFailed", err.message), "error"); }
}
async function _applyPreset() {
const selEl = document.getElementById("wfm-feeder-preset-sel");
const name = selEl?.value;
if (!name || !_s.presets[name]) { showToast(t("selectPresetFirst"), "error"); return; }
const preset = _s.presets[name];
const dir = preset.directory || "";
_s.selected.clear();
(preset.selected_files || []).forEach(f => _s.selected.add(f));
_setVal("wfm-feeder-dir-input", dir);
if (_s.dir !== dir) {
_s.dir = dir;
_highlightTreeRow(dir);
await _loadImages(dir);
}
_refreshGridCbs();
_updateStatus();
showToast(t("presetLoaded", name), "success");
}
async function _deletePreset() {
const name = document.getElementById("wfm-feeder-preset-sel")?.value;
if (!name) return;
try {
await fetch(`/image_feeder/presets/${encodeURIComponent(name)}`, { method: "DELETE" });
showToast(t("presetDeleted", name), "info");
await _loadPresets();
} catch (err) { showToast(t("deleteFailed"), "error"); }
}
// ── Mode Switch ───────────────────────────────────────────────────
function _setMode(mode) {
_s.mode = mode;
localStorage.setItem("wfm_feeder_mode", mode);
const loopBtn = document.getElementById("wfm-feeder-mode-loop");
const galBtn = document.getElementById("wfm-feeder-mode-gallery");
const loopSec = document.getElementById("wfm-feeder-loop-section");
const galSec = document.getElementById("wfm-feeder-gal-section");
const loopLib = document.getElementById("wfm-feeder-loop-library");
const galLib = document.getElementById("wfm-feeder-gal-library");
const isGallery = mode === "gallery";
if (loopBtn) loopBtn.classList.toggle("wfm-btn-primary", !isGallery);
if (galBtn) galBtn.classList.toggle("wfm-btn-primary", isGallery);
if (loopSec) loopSec.style.display = isGallery ? "none" : "";
if (galSec) galSec.style.display = isGallery ? "" : "none";
if (loopLib) loopLib.style.display = isGallery ? "none" : "";
if (galLib) galLib.style.display = isGallery ? "" : "none";
if (isGallery) {
_loadGalGroups().then(() => _loadGalImages(_gs.group));
_refreshGalNodeList();
}
}
// ── Helpers ───────────────────────────────────────────────────────
function _setVal(id, val) {
const el = document.getElementById(id);
if (el) el.value = val ?? "";
}
function _setCheck(id, val) {
const el = document.getElementById(id);
if (el) el.checked = !!val;
}
// ── Init ─────────────────────────────────────────────────────────
export async function initFeederTab() {
// Mode toggle
document.getElementById("wfm-feeder-mode-loop")?.addEventListener("click", () => _setMode("loop"));
document.getElementById("wfm-feeder-mode-gallery")?.addEventListener("click", () => _setMode("gallery"));
// ── Image Loop mode events ──
document.getElementById("wfm-feeder-node-sel")?.addEventListener("change", e => {
_loadFromNode(e.target.value);
});
document.getElementById("wfm-feeder-apply-btn")?.addEventListener("click", _applyToWorkflow);
document.getElementById("wfm-feeder-dir-input")?.addEventListener("change", e => {
const val = e.target.value.trim();
if (_s.dir !== val) {
_s.dir = val;
_highlightTreeRow(val);
_loadImages(val);
}
});
document.getElementById("wfm-feeder-reload-tree")?.addEventListener("click", _loadTree);
document.getElementById("wfm-feeder-sel-all")?.addEventListener("click", _selectAll);
document.getElementById("wfm-feeder-desel-all")?.addEventListener("click", _deselectAll);
document.getElementById("wfm-feeder-preset-save")?.addEventListener("click", _savePreset);
document.getElementById("wfm-feeder-preset-load")?.addEventListener("click", _applyPreset);
document.getElementById("wfm-feeder-preset-del")?.addEventListener("click", _deletePreset);
document.getElementById("wfm-feeder-run-btn")?.addEventListener("click", _startRun);
document.getElementById("wfm-feeder-stop-btn")?.addEventListener("click", _stopRun);
// ── Gallery mode events ──
document.getElementById("wfm-feeder-gal-node-sel")?.addEventListener("change", e => {
_loadFromGalNode(e.target.value);
});
document.getElementById("wfm-feeder-gal-apply-btn")?.addEventListener("click", _applyGalToWorkflow);
document.getElementById("wfm-feeder-gal-group")?.addEventListener("change", e => {
_gs.group = e.target.value;
_gs.idx = 0;
_loadGalImages(_gs.group);
});
document.getElementById("wfm-feeder-gal-index")?.addEventListener("change", e => {
_gs.idx = Math.max(0, parseInt(e.target.value) || 0);
if (_gs.images[_gs.idx]) _highlightGalCard(_gs.images[_gs.idx]);
});
document.getElementById("wfm-feeder-gal-run-btn")?.addEventListener("click", _startGalRun);
document.getElementById("wfm-feeder-gal-stop-btn")?.addEventListener("click", _stopGalRun);
// 初期化
await ensureFeederGroup();
_setMode(_s.mode);
if (_s.mode === "loop") {
await Promise.all([_loadTree(), _loadPresets()]);
_selectDir("");
}
}
+1420 -98
View File
File diff suppressed because it is too large Load Diff
+2208 -123
View File
File diff suppressed because it is too large Load Diff
+2820 -101
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+208
View File
@@ -0,0 +1,208 @@
/**
* Image Edit Tab - Background Removal
* Two backends: a lightweight in-browser model (@imgly/background-removal)
* and BiRefNet via the Mask Editor One server endpoints.
*/
import { showToast } from "../app.js";
export class BgRemove {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => void} callbacks.saveUndo
* @param {() => void} callbacks.updateCompositeView
* @param {() => void} callbacks.refreshLayerList
* @param {(newLayer: object) => void} callbacks.onLayerAdded
*/
constructor(callbacks) {
this._cb = callbacks;
this.birefnetAvailable = false;
}
async checkAvailability() {
try {
const resp = await fetch("/mask_editor/birefnet/status");
if (!resp.ok) return;
const json = await resp.json();
this.birefnetAvailable = json.loaded === true || json.model_found === true;
} catch {
this.birefnetAvailable = false;
}
}
renderPanel(el) {
const birefnetDisabled = this.birefnetAvailable ? "" : "disabled";
const birefnetLabel = this.birefnetAvailable
? "BiRefNet (Mask Editor One)"
: "BiRefNet (Mask Editor One required)";
el.innerHTML = `
<div class="ie-opt-group">
<label>Model</label>
<select id="ie-bgremove-model" class="ie-opt-select">
<option value="imgly">Lightweight (@imgly)</option>
<option value="birefnet" ${birefnetDisabled}>${birefnetLabel}</option>
</select>
</div>
<div class="ie-opt-group">
<label style="font-size:11px;cursor:pointer;">
<input type="checkbox" id="ie-bgremove-new-layer" checked> New Layer
</label>
</div>
<div class="ie-opt-group">
<button class="wfm-btn wfm-btn-sm" id="ie-bgremove-btn">Remove BG</button>
</div>
<span id="ie-bgremove-status" style="font-size:11px;color:var(--wfm-text-secondary);margin-left:4px;"></span>
`;
document.getElementById("ie-bgremove-btn")?.addEventListener("click", () => this.apply());
}
async apply() {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) { showToast("No image loaded", "error"); return; }
const layer = layerMgr.activeLayer;
if (!layer) { showToast("No active layer", "error"); return; }
const model = document.getElementById("ie-bgremove-model")?.value ?? "imgly";
const asNew = document.getElementById("ie-bgremove-new-layer")?.checked ?? true;
const statusEl = document.getElementById("ie-bgremove-status");
const btn = document.getElementById("ie-bgremove-btn");
const setStatus = msg => { if (statusEl) statusEl.textContent = msg; };
if (btn) btn.disabled = true;
setStatus("Starting...");
try {
const dataUrl = layer.canvas.toDataURL("image/png");
let resultDataUrl;
if (model === "imgly") {
resultDataUrl = await this._removeImgly(dataUrl, setStatus);
} else {
resultDataUrl = await this._removeBiRefNet(dataUrl, setStatus);
}
const img = await new Promise((resolve, reject) => {
const i = new Image();
i.onload = () => resolve(i);
i.onerror = () => reject(new Error("Result image load failed"));
i.src = resultDataUrl;
});
this._cb.saveUndo();
if (asNew) {
const newL = layerMgr.addLayer("image", layer.name + " (no bg)", {
contentW: img.width, contentH: img.height,
displayW: layer.displayW, displayH: layer.displayH,
x: layer.x, y: layer.y,
});
newL.ctx.drawImage(img, 0, 0);
layerMgr.setActive(newL.id);
this._cb.onLayerAdded(newL);
} else {
layer.canvas.width = img.width;
layer.canvas.height = img.height;
layer.ctx = layer.canvas.getContext("2d");
layer.ctx.drawImage(img, 0, 0);
}
this._cb.updateCompositeView();
this._cb.refreshLayerList();
setStatus("Done!");
setTimeout(() => setStatus(""), 3000);
showToast("Background removed", "success");
} catch (err) {
setStatus("Error: " + err.message);
showToast("BG remove failed: " + err.message, "error");
} finally {
if (btn) btn.disabled = false;
}
}
async _removeImgly(dataUrl, onStatus) {
if (!window._wfmImglyRemoveBg) {
onStatus("Loading model...");
const mod = await import("https://esm.sh/@imgly/background-removal@1.5.7?bundle&target=es2022");
window._wfmImglyRemoveBg = mod.removeBackground;
}
onStatus("Processing...");
const res = await fetch(dataUrl);
const blob = await res.blob();
const resultBlob = await window._wfmImglyRemoveBg(blob, {
publicPath: "https://staticimgly.com/@imgly/background-removal-data/1.5.7/dist/",
});
return await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(resultBlob);
});
}
async _removeBiRefNet(dataUrl, onStatus) {
const NODE_ID = "wfs_bgremove";
// 1. アクティブレイヤー画像を Mask Editor One のキャッシュに登録
onStatus("Sending image...");
const storeResp = await fetch("/mask_editor/store_image", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ node_id: NODE_ID, image_b64: dataUrl }),
});
if (!storeResp.ok) throw new Error("Failed to cache image for BiRefNet");
// 2. BiRefNet 推論実行
onStatus("Running BiRefNet...");
const resp = await fetch("/mask_editor/birefnet/remove_bg", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ node_id: NODE_ID }),
});
const json = await resp.json();
if (json.error) throw new Error(json.error);
// 3. グレースケールマスク (白=前景) → RGBA PNG に変換して返す
onStatus("Compositing...");
return await this._applyMaskToImage(dataUrl, json.mask_b64);
}
async _applyMaskToImage(imageB64, maskB64) {
const loadImage = src => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("Image load failed: " + src.slice(0, 40)));
img.src = src;
});
const [origImg, maskImg] = await Promise.all([loadImage(imageB64), loadImage(maskB64)]);
const w = origImg.naturalWidth;
const h = origImg.naturalHeight;
// マスク: グレースケール輝度値 → アルファチャンネル (RGBA 白マスク)
const maskCanvas = document.createElement("canvas");
maskCanvas.width = w;
maskCanvas.height = h;
const mc = maskCanvas.getContext("2d");
mc.drawImage(maskImg, 0, 0, w, h);
const maskData = mc.getImageData(0, 0, w, h);
const md = maskData.data;
for (let i = 0; i < md.length; i += 4) {
md[i + 3] = md[i]; // 輝度 → アルファ
md[i] = md[i + 1] = md[i + 2] = 255;
}
mc.putImageData(maskData, 0, 0);
// 元画像にマスクを destination-in で適用
const out = document.createElement("canvas");
out.width = w;
out.height = h;
const ctx = out.getContext("2d");
ctx.drawImage(origImg, 0, 0, w, h);
ctx.globalCompositeOperation = "destination-in";
ctx.drawImage(maskCanvas, 0, 0, w, h);
return out.toDataURL("image/png");
}
}
+259
View File
@@ -0,0 +1,259 @@
/**
* Image Edit Tab - Blur / Mosaic Tool
* Whole-layer blur/mosaic buttons plus a drag-to-select rectangle mode
* that applies blur or mosaic to just the dragged region.
*/
import { showToast } from "../app.js";
function _applyMosaicToRegion(ctx, x, y, w, h, size) {
if (w <= 0 || h <= 0 || size < 1) return;
const imgData = ctx.getImageData(x, y, w, h);
const d = imgData.data;
for (let py = 0; py < h; py += size) {
for (let px = 0; px < w; px += size) {
const i = (py * w + px) * 4;
const r = d[i], g = d[i + 1], b = d[i + 2], a = d[i + 3];
for (let by = py; by < Math.min(py + size, h); by++) {
for (let bx = px; bx < Math.min(px + size, w); bx++) {
const j = (by * w + bx) * 4;
d[j] = r; d[j + 1] = g; d[j + 2] = b; d[j + 3] = a;
}
}
}
}
ctx.putImageData(imgData, x, y);
}
export class BlurTool {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => number} callbacks.getZoom
* @param {() => void} callbacks.saveUndo
* @param {() => void} callbacks.updateCompositeView
* @param {() => void} callbacks.refreshLayerList
* @param {(toolId: string) => void} callbacks.renderToolOptions
*/
constructor(callbacks) {
this._cb = callbacks;
this.rectMode = null; // null | 'blur' | 'mosaic'
this._dragging = false;
this._dragStart = null;
this._dragCur = null;
}
activate() {
const overlay = document.getElementById("ie-canvas-overlay");
if (overlay) overlay.style.cursor = this.rectMode ? "crosshair" : "default";
}
deactivate() {
this.rectMode = null;
this._dragging = false;
const overlay = document.getElementById("ie-canvas-overlay");
if (overlay) {
overlay.style.cursor = "";
overlay.getContext("2d").clearRect(0, 0, overlay.width, overlay.height);
}
}
renderPanel(el) {
const blurOn = this.rectMode === "blur";
const mosaicOn = this.rectMode === "mosaic";
el.innerHTML = `
<div class="ie-opt-group">
<span style="font-size:11px;color:var(--wfm-text-secondary);">Whole:</span>
</div>
<div class="ie-opt-group">
<label style="font-size:11px;">Blur</label>
<input type="range" id="ie-whole-blur" min="1" max="50" value="10" style="width:70px;">
<span id="ie-whole-blur-val" style="font-size:11px;min-width:22px;">10</span>px
<button class="wfm-btn wfm-btn-sm" id="ie-whole-blur-apply">Apply</button>
</div>
<div class="ie-opt-group">
<label style="font-size:11px;">Mosaic</label>
<input type="range" id="ie-whole-mosaic" min="5" max="100" value="20" style="width:70px;">
<span id="ie-whole-mosaic-val" style="font-size:11px;min-width:22px;">20</span>px
<button class="wfm-btn wfm-btn-sm" id="ie-whole-mosaic-apply">Apply</button>
</div>
<div style="width:1px;height:22px;background:var(--wfm-border);margin:0 6px;flex-shrink:0;"></div>
<div class="ie-opt-group">
<span style="font-size:11px;color:var(--wfm-text-secondary);">Rect:</span>
</div>
<div class="ie-opt-group">
<button class="wfm-btn wfm-btn-sm${blurOn ? " ie-opt-active" : ""}" id="ie-rect-blur-toggle"
style="${blurOn ? "background:var(--wfm-accent,#4682e6);color:#fff;" : ""}">
Rect Blur: ${blurOn ? "ON" : "OFF"}
</button>
<input type="range" id="ie-rect-blur" min="1" max="50" value="10" style="width:70px;">
<span id="ie-rect-blur-val" style="font-size:11px;min-width:22px;">10</span>px
</div>
<div class="ie-opt-group">
<button class="wfm-btn wfm-btn-sm${mosaicOn ? " ie-opt-active" : ""}" id="ie-rect-mosaic-toggle"
style="${mosaicOn ? "background:var(--wfm-accent,#4682e6);color:#fff;" : ""}">
Rect Mosaic: ${mosaicOn ? "ON" : "OFF"}
</button>
<input type="range" id="ie-rect-mosaic" min="5" max="50" value="15" style="width:70px;">
<span id="ie-rect-mosaic-val" style="font-size:11px;min-width:22px;">15</span>px
</div>
`;
document.getElementById("ie-whole-blur")?.addEventListener("input", e => {
document.getElementById("ie-whole-blur-val").textContent = e.target.value;
});
document.getElementById("ie-whole-mosaic")?.addEventListener("input", e => {
document.getElementById("ie-whole-mosaic-val").textContent = e.target.value;
});
document.getElementById("ie-whole-blur-apply")?.addEventListener("click", () => {
this.applyWholeBlur(parseInt(document.getElementById("ie-whole-blur").value));
});
document.getElementById("ie-whole-mosaic-apply")?.addEventListener("click", () => {
this.applyWholeMosaic(parseInt(document.getElementById("ie-whole-mosaic").value));
});
document.getElementById("ie-rect-blur-toggle")?.addEventListener("click", () => {
this.rectMode = this.rectMode === "blur" ? null : "blur";
this._cb.renderToolOptions("blur");
const ov = document.getElementById("ie-canvas-overlay");
if (ov) ov.style.cursor = this.rectMode ? "crosshair" : "default";
});
document.getElementById("ie-rect-mosaic-toggle")?.addEventListener("click", () => {
this.rectMode = this.rectMode === "mosaic" ? null : "mosaic";
this._cb.renderToolOptions("blur");
const ov = document.getElementById("ie-canvas-overlay");
if (ov) ov.style.cursor = this.rectMode ? "crosshair" : "default";
});
document.getElementById("ie-rect-blur")?.addEventListener("input", e => {
document.getElementById("ie-rect-blur-val").textContent = e.target.value;
});
document.getElementById("ie-rect-mosaic")?.addEventListener("input", e => {
document.getElementById("ie-rect-mosaic-val").textContent = e.target.value;
});
}
onMouseDown(pos) {
if (!this.rectMode) return;
this._dragging = true;
this._dragStart = { x: pos.x, y: pos.y };
this._dragCur = { x: pos.x, y: pos.y };
}
onMouseMove(pos) {
if (!this._dragging) return;
this._dragCur = pos;
this._drawPreview();
}
onMouseUp() {
if (!this._dragging) return;
this._dragging = false;
this._applyRectEffect();
const overlay = document.getElementById("ie-canvas-overlay");
if (overlay) overlay.getContext("2d").clearRect(0, 0, overlay.width, overlay.height);
}
onMouseLeave() {
if (!this._dragging) return;
this._dragging = false;
const overlay = document.getElementById("ie-canvas-overlay");
if (overlay) overlay.getContext("2d").clearRect(0, 0, overlay.width, overlay.height);
}
applyWholeBlur(amount) {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) return;
const layer = layerMgr.activeLayer;
if (!layer) { showToast("No active layer", "error"); return; }
this._cb.saveUndo();
const w = layer.canvas.width, h = layer.canvas.height;
const tmp = document.createElement("canvas");
tmp.width = w; tmp.height = h;
const tc = tmp.getContext("2d");
tc.filter = `blur(${amount}px)`;
tc.drawImage(layer.canvas, 0, 0);
layer.ctx.clearRect(0, 0, w, h);
layer.ctx.drawImage(tmp, 0, 0);
this._cb.updateCompositeView();
this._cb.refreshLayerList();
}
applyWholeMosaic(size) {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) return;
const layer = layerMgr.activeLayer;
if (!layer) { showToast("No active layer", "error"); return; }
this._cb.saveUndo();
_applyMosaicToRegion(layer.ctx, 0, 0, layer.canvas.width, layer.canvas.height, size);
this._cb.updateCompositeView();
this._cb.refreshLayerList();
}
// canvas座標 (cx,cy) → layer.canvas 座標への逆変換
_canvasToLayerCoords(layer, cx, cy) {
const centerX = layer.x + layer.displayW / 2;
const centerY = layer.y + layer.displayH / 2;
const dx = cx - centerX, dy = cy - centerY;
const angle = -(layer.rotation || 0) * Math.PI / 180;
const rdx = dx * Math.cos(angle) - dy * Math.sin(angle);
const rdy = dx * Math.sin(angle) + dy * Math.cos(angle);
const scaleX = layer.displayW / layer.canvas.width;
const scaleY = layer.displayH / layer.canvas.height;
let lx = rdx / scaleX + layer.canvas.width / 2;
let ly = rdy / scaleY + layer.canvas.height / 2;
if (layer.flipX) lx = layer.canvas.width - lx;
if (layer.flipY) ly = layer.canvas.height - ly;
return { x: lx, y: ly };
}
_drawPreview() {
const overlay = document.getElementById("ie-canvas-overlay");
if (!overlay) return;
const ctx = overlay.getContext("2d");
ctx.clearRect(0, 0, overlay.width, overlay.height);
const s = this._dragStart, c = this._dragCur;
if (!s || !c) return;
const x = Math.min(s.x, c.x), y = Math.min(s.y, c.y);
const w = Math.abs(c.x - s.x), h = Math.abs(c.y - s.y);
const zoom = this._cb.getZoom();
ctx.strokeStyle = this.rectMode === "blur" ? "#4af" : "#fa4";
ctx.lineWidth = 1 / zoom;
ctx.setLineDash([4 / zoom, 2 / zoom]);
ctx.strokeRect(x, y, w, h);
ctx.setLineDash([]);
}
_applyRectEffect() {
const layer = this._cb.getLayerManager()?.activeLayer;
if (!layer || !this._dragStart || !this._dragCur) return;
const s = this._dragStart, c = this._dragCur;
if (Math.abs(c.x - s.x) < 3 || Math.abs(c.y - s.y) < 3) return;
const minX = Math.min(s.x, c.x), minY = Math.min(s.y, c.y);
const maxX = Math.max(s.x, c.x), maxY = Math.max(s.y, c.y);
const p1 = this._canvasToLayerCoords(layer, minX, minY);
const p2 = this._canvasToLayerCoords(layer, maxX, maxY);
const lx = Math.round(Math.max(0, Math.min(p1.x, p2.x)));
const ly = Math.round(Math.max(0, Math.min(p1.y, p2.y)));
const lw = Math.round(Math.min(layer.canvas.width - lx, Math.abs(p2.x - p1.x)));
const lh = Math.round(Math.min(layer.canvas.height - ly, Math.abs(p2.y - p1.y)));
if (lw <= 0 || lh <= 0) return;
this._cb.saveUndo();
if (this.rectMode === "blur") {
const amount = parseInt(document.getElementById("ie-rect-blur")?.value ?? "10");
const tmp = document.createElement("canvas");
tmp.width = layer.canvas.width; tmp.height = layer.canvas.height;
const tc = tmp.getContext("2d");
tc.filter = `blur(${amount}px)`;
tc.drawImage(layer.canvas, 0, 0);
layer.ctx.drawImage(tmp, lx, ly, lw, lh, lx, ly, lw, lh);
} else {
const size = parseInt(document.getElementById("ie-rect-mosaic")?.value ?? "15");
_applyMosaicToRegion(layer.ctx, lx, ly, lw, lh, size);
}
this._cb.updateCompositeView();
this._cb.refreshLayerList();
}
}
+362
View File
@@ -0,0 +1,362 @@
/**
* Image Edit Tab - Draw Tool
* Inspired by comfyui-mask-editor-one PaintTool.js
* Supports color drawing and erasing with a soft round brush.
* Also supports image brushes loaded from Mask Editor One's ABR brush library.
*/
export class DrawTool {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas?.getContext("2d") ?? null;
this.brushSize = 20;
this.hardness = 0.8; // 0.0 = very soft, 1.0 = hard edge
this.opacity = 1.0;
this.color = "#ff0000";
this.mode = "draw"; // "draw" | "erase"
this.spacing = 0.25; // stamp interval as fraction of brushSize (image brush only)
this.angle = 0; // degrees [0, 359]
this.sizeJitter = false;
this.sizeJitterAmount = 0.5;
this.rotationJitter = false;
// Pen pressure (0–1, from PointerEvent.pressure; mouse reports 0.5).
// pressure=0.5 maps to a 1.0x multiplier so mouse behavior is unchanged.
this.pressureEnabled = true;
this._lastPressure = 0.5;
// Image brush from ABR library (null = default circle brush)
this.brushImage = null;
this.brushName = "Circle";
this._drawing = false;
this._lastX = 0;
this._lastY = 0;
// Cached circle stamp
this._stamp = null;
this._stampSize = 0;
this._stampHard = 0;
this._stampColor = null;
// Cached image stamp
this._imgStamp = null;
this._imgStampSize = 0;
this._imgStampImg = null;
this._imgStampColor = null;
// Stroke buffer: prevents intra-stroke opacity accumulation (image brush only)
this._baseCanvas = null;
this._strokeCanvas = null;
this._strokeCtx = null;
this._onChange = null;
}
setCanvas(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this._stamp = null;
this._imgStamp = null;
}
onChange(fn) { this._onChange = fn; }
setImageBrush(img, name) {
this.brushImage = img;
this.brushName = name;
this._imgStamp = null;
}
clearImageBrush() {
this.brushImage = null;
this.brushName = "Circle";
this._stamp = null;
this._imgStamp = null;
}
activate() {
if (this.canvas) this.canvas.style.cursor = "none";
}
deactivate() {
this._drawing = false;
this._clearStrokeBuffer();
if (this.canvas) this.canvas.style.cursor = "";
}
onMouseDown(x, y, pressure = 0.5) {
this._drawing = true;
this._lastX = x;
this._lastY = y;
this._lastPressure = pressure;
if (this.brushImage) {
this._initStrokeBuffer();
this._paintToStroke(x, y, pressure);
this._mergeStroke();
} else {
this._paint(x, y, pressure);
}
}
onMouseMove(x, y, pressure = 0.5) {
if (!this._drawing) return;
if (this.brushImage) {
this._paintLineToStroke(this._lastX, this._lastY, x, y, this._lastPressure, pressure);
this._mergeStroke();
} else {
this._paintLine(this._lastX, this._lastY, x, y, this._lastPressure, pressure);
}
this._lastX = x;
this._lastY = y;
this._lastPressure = pressure;
}
onMouseUp() {
if (this._drawing) {
this._drawing = false;
this._clearStrokeBuffer();
if (this._onChange) this._onChange();
}
}
onMouseLeave() {
if (this._drawing) this.onMouseUp();
}
// ── Pressure response ──────────────────────────────────────────────
_effectiveSize(pressure) {
if (!this.pressureEnabled) return this.brushSize;
const p = Math.max(0, Math.min(1, pressure ?? 0.5));
return Math.max(1, this.brushSize * (0.3 + p * 1.4)); // p=0.5 -> 1.0x
}
_effectiveOpacity(pressure) {
if (!this.pressureEnabled) return this.opacity;
const p = Math.max(0, Math.min(1, pressure ?? 0.5));
return Math.max(0, Math.min(1, this.opacity * (0.4 + p * 1.2))); // p=0.5 -> 1.0x
}
// ── Stroke buffer (image brush only) ─────────────────────────────
_initStrokeBuffer() {
const w = this.canvas.width;
const h = this.canvas.height;
this._baseCanvas = document.createElement("canvas");
this._baseCanvas.width = w;
this._baseCanvas.height = h;
this._baseCanvas.getContext("2d").drawImage(this.canvas, 0, 0);
this._strokeCanvas = document.createElement("canvas");
this._strokeCanvas.width = w;
this._strokeCanvas.height = h;
this._strokeCtx = this._strokeCanvas.getContext("2d");
}
_clearStrokeBuffer() {
this._baseCanvas = null;
this._strokeCanvas = null;
this._strokeCtx = null;
}
_mergeStroke() {
const ctx = this.ctx;
const w = this.canvas.width;
const h = this.canvas.height;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(this._baseCanvas, 0, 0);
ctx.save();
if (this.mode === "erase") {
ctx.globalCompositeOperation = "destination-out";
} else {
ctx.globalCompositeOperation = "source-over";
}
ctx.globalAlpha = this.opacity;
ctx.drawImage(this._strokeCanvas, 0, 0);
ctx.restore();
}
_paintToStroke(x, y, pressure = 0.5) {
const saved = this.ctx;
this.ctx = this._strokeCtx;
let size = this._effectiveSize(pressure);
if (this.sizeJitter) {
size = Math.max(1, size * (1 - Math.random() * this.sizeJitterAmount));
}
if (this.rotationJitter) {
const savedAngle = this.angle;
this.angle = Math.random() * 360;
this._paintImageBrush(x, y, size);
this.angle = savedAngle;
} else {
this._paintImageBrush(x, y, size);
}
this.ctx = saved;
}
_paintLineToStroke(x0, y0, x1, y1, p0 = 0.5, p1 = 0.5) {
const dist = Math.hypot(x1 - x0, y1 - y0);
const step = Math.max(1, this.brushSize * this.spacing);
const steps = Math.ceil(dist / step);
for (let i = 1; i <= steps; i++) {
const t = i / steps;
this._paintToStroke(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, p0 + (p1 - p0) * t);
}
}
// ── Circle brush ─────────────────────────────────────────────────
_getStamp(size) {
size = Math.max(1, Math.round(size));
if (
this._stamp &&
this._stampSize === size &&
this._stampHard === this.hardness &&
this._stampColor === this.color
) return this._stamp;
const sc = document.createElement("canvas");
sc.width = size;
sc.height = size;
const sctx = sc.getContext("2d");
const cx = size / 2, cy = size / 2, r = size / 2;
const innerR = r * (1 - Math.min(this.hardness, 0.99)) * 0.95;
const grd = sctx.createRadialGradient(cx, cy, innerR, cx, cy, r);
grd.addColorStop(0, this.color);
grd.addColorStop(1, this.color + "00");
sctx.fillStyle = grd;
sctx.beginPath();
sctx.arc(cx, cy, r, 0, Math.PI * 2);
sctx.fill();
this._stamp = sc;
this._stampSize = size;
this._stampHard = this.hardness;
this._stampColor = this.color;
return sc;
}
_paint(x, y, pressure = 0.5) {
const size = this._effectiveSize(pressure);
const stamp = this._getStamp(size);
const s = stamp.width;
this.ctx.save();
this.ctx.globalAlpha = this._effectiveOpacity(pressure);
if (this.mode === "erase") {
this.ctx.globalCompositeOperation = "destination-out";
}
this.ctx.drawImage(stamp, x - s / 2, y - s / 2);
this.ctx.restore();
}
_paintLine(x0, y0, x1, y1, p0 = 0.5, p1 = 0.5) {
const dist = Math.hypot(x1 - x0, y1 - y0);
const spacing = Math.max(1, this.brushSize * 0.2);
const steps = Math.max(1, Math.ceil(dist / spacing));
for (let i = 1; i <= steps; i++) {
const t = i / steps;
this._paint(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, p0 + (p1 - p0) * t);
}
}
// ── Image brush ──────────────────────────────────────────────────
_getImageStamp(size) {
size = Math.max(1, size);
if (
this._imgStamp &&
this._imgStampSize === size &&
this._imgStampImg === this.brushImage &&
this._imgStampColor === this.color
) return this._imgStamp;
const img = this.brushImage;
const srcW = img.naturalWidth || img.width;
const srcH = img.naturalHeight || img.height;
const aspect = (srcW > 0 && srcH > 0) ? srcW / srcH : 1;
const stampH = size;
const stampW = Math.max(1, Math.round(size * aspect));
const sc = document.createElement("canvas");
sc.width = stampW;
sc.height = stampH;
const stx = sc.getContext("2d");
stx.drawImage(img, 0, 0, stampW, stampH);
const imgData = stx.getImageData(0, 0, stampW, stampH);
const d = imgData.data;
// Detect alpha channel (ABR-exported PNGs carry alpha = brush density)
let hasAlpha = false;
for (let i = 3; i < d.length; i += 4) {
if (d[i] < 250) { hasAlpha = true; break; }
}
let invertLum = false;
if (!hasAlpha) {
const corners = [0, stampW - 1, stampW * (stampH - 1), stampW * stampH - 1];
let bgLum = 0;
for (const ci of corners) {
const ii = ci * 4;
bgLum += (d[ii] * 0.299 + d[ii + 1] * 0.587 + d[ii + 2] * 0.114) / 255;
}
invertLum = (bgLum / corners.length) > 0.5;
}
// Parse target color
const hex = this.color.replace("#", "");
const cr = parseInt(hex.slice(0, 2), 16);
const cg = parseInt(hex.slice(2, 4), 16);
const cb = parseInt(hex.slice(4, 6), 16);
// Convert to target color pixels; alpha = brush density
for (let i = 0; i < d.length; i += 4) {
let alpha;
if (hasAlpha) {
alpha = d[i + 3] / 255;
} else {
const lum = (d[i] * 0.299 + d[i + 1] * 0.587 + d[i + 2] * 0.114) / 255;
alpha = invertLum ? 1 - lum : lum;
}
d[i] = cr; d[i + 1] = cg; d[i + 2] = cb;
d[i + 3] = Math.round(alpha * 255);
}
stx.putImageData(imgData, 0, 0);
this._imgStamp = sc;
this._imgStampSize = size;
this._imgStampImg = this.brushImage;
this._imgStampColor = this.color;
return sc;
}
_paintImageBrush(x, y, size = this.brushSize) {
const stamp = this._getImageStamp(Math.round(size));
this.ctx.globalCompositeOperation = "source-over";
if (this.angle) {
this.ctx.save();
this.ctx.translate(Math.round(x), Math.round(y));
this.ctx.rotate((this.angle * Math.PI) / 180);
this.ctx.drawImage(stamp, -stamp.width / 2, -stamp.height / 2);
this.ctx.restore();
} else {
this.ctx.drawImage(stamp, Math.round(x - stamp.width / 2), Math.round(y - stamp.height / 2));
}
this.ctx.globalCompositeOperation = "source-over";
}
static getCanvasPos(canvas, event) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY,
};
}
}
+222
View File
@@ -0,0 +1,222 @@
/**
* Image Edit Tab - File Export
* Composites the visible layers (respecting mask-apply clipping) into a
* flat canvas and offers three destinations: local PNG download, WFS
* Gallery, and the selected node's image widget on the ComfyUI canvas
* (Send to LI node).
*/
import { showToast } from "../app.js";
import { Layer } from "./LayerManager.js";
export class FileExport {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => {w: number, h: number}} callbacks.getCanvasSize
* @param {() => string} callbacks.getBaseName
* @param {(ctx: CanvasRenderingContext2D, drawCanvas: HTMLCanvasElement, maskLayer: object, targetLayer: object, showOverlay: boolean) => void} callbacks.renderMaskedLayer
*/
constructor(callbacks) {
this._cb = callbacks;
}
_buildCompositeCanvas() {
const { w, h } = this._cb.getCanvasSize();
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) return canvas;
this._compositeForExport(canvas, layerMgr);
return canvas;
}
// 保存用合成: maskApply=true のクリッピングを適用、マスクオーバーレイは除外
_compositeForExport(target, layerMgr) {
const ctx = target.getContext("2d");
ctx.clearRect(0, 0, target.width, target.height);
const layers = layerMgr.layers;
const maskedIndices = new Set();
for (let i = 0; i < layers.length; i++) {
if (layers[i].type === "mask" && layers[i].maskApply && layers[i].visible && i + 1 < layers.length) {
maskedIndices.add(i + 1);
}
}
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i];
if (!layer.visible) continue;
if (maskedIndices.has(i)) continue;
if (layer.type === "mask") {
if (layer.maskApply && i + 1 < layers.length) {
this._cb.renderMaskedLayer(ctx, target, layer, layers[i + 1], false);
}
// maskApply=false のマスクはエクスポートに含めない
} else {
ctx.save();
ctx.globalAlpha = layer.opacity;
ctx.globalCompositeOperation = layer.blendMode;
Layer.applyTransform(ctx, layer);
ctx.drawImage(layer.canvas, -layer.canvas.width / 2, -layer.canvas.height / 2);
ctx.restore();
}
}
}
// 保存用レイヤー配列を構築: 各レイヤーを個別のcanvas(ドキュメント全体サイズ)に
// 回転・反転・拡縮のみベイクして描画する。opacity/blendModeはピクセルに焼き込まず
// PSDレイヤー属性として渡すためメタデータのまま残す。
// maskApply=true のクリッピングマスクは対象レイヤーと合成して1枚にベイクする
// (PSDの本物のレイヤーマスクとしては書き出さない簡略化)。
_buildLayerExportList(layerMgr, w, h) {
const layers = layerMgr.layers;
const maskedIndices = new Set();
for (let i = 0; i < layers.length; i++) {
if (layers[i].type === "mask" && layers[i].maskApply && layers[i].visible && i + 1 < layers.length) {
maskedIndices.add(i + 1);
}
}
const exportLayers = [];
// 背面→前面の順(PSD側で後から追加したレイヤーほど上に重なるため、この順で送る)
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i];
if (maskedIndices.has(i)) continue; // マスク側の処理でまとめて扱う
if (layer.type === "mask") {
if (!(layer.maskApply && layer.visible && i + 1 < layers.length)) continue;
const target = layers[i + 1];
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
this._cb.renderMaskedLayer(canvas.getContext("2d"), canvas, layer, target, false);
exportLayers.push({
name: target.name || "Layer",
visible: target.visible,
opacity: 1,
blendMode: "source-over",
imageData: canvas.toDataURL("image/png"),
});
continue;
}
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
ctx.save();
Layer.applyTransform(ctx, layer);
ctx.drawImage(layer.canvas, -layer.canvas.width / 2, -layer.canvas.height / 2);
ctx.restore();
exportLayers.push({
name: layer.name || "Layer",
visible: layer.visible,
opacity: layer.opacity,
blendMode: layer.blendMode,
imageData: canvas.toDataURL("image/png"),
});
}
return exportLayers;
}
async saveAsPsd() {
if (!this._cb.getLayerManager()) { showToast("No image loaded", "error"); return; }
const layerMgr = this._cb.getLayerManager();
const { w, h } = this._cb.getCanvasSize();
const exportLayers = this._buildLayerExportList(layerMgr, w, h);
if (exportLayers.length === 0) { showToast("No layers to export", "error"); return; }
try {
const r = await fetch("/wfm/gallery/image/export-psd-layers", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ width: w, height: h, layers: exportLayers }),
});
if (!r.ok) {
const e = await r.json().catch(() => ({}));
throw new Error(e.error || r.statusText);
}
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = (this._cb.getBaseName() || "wfs-edit") + ".psd";
a.click();
URL.revokeObjectURL(url);
showToast("PSD saved", "success");
} catch (err) {
showToast(`PSD save failed: ${err.message}`, "error");
}
}
savePng() {
if (!this._cb.getLayerManager()) { showToast("No image loaded", "error"); return; }
const canvas = this._buildCompositeCanvas();
const a = document.createElement("a");
a.href = canvas.toDataURL("image/png");
a.download = (this._cb.getBaseName() || "wfs-edit") + "-output.png";
a.click();
showToast("PNG saved", "success");
}
async saveToGallery() {
if (!this._cb.getLayerManager()) { showToast("No image loaded", "error"); return; }
// デフォルトファイル名: wfs-image-YYYYMMDDHHmmss
const now = new Date();
const pad = n => String(n).padStart(2, "0");
const ts = `${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
const defaultName = `wfs-image-${ts}`;
const filename = window.prompt("Save to Gallery — file name (without extension):", defaultName);
if (filename === null) return; // キャンセル
const safeName = filename.trim() || defaultName;
const canvas = this._buildCompositeCanvas();
const imageData = canvas.toDataURL("image/png");
try {
const r = await fetch("/wfm/gallery/image/save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename: safeName, imageData }),
});
if (!r.ok) {
const e = await r.json().catch(() => ({}));
throw new Error(e.error || r.statusText);
}
showToast(`Saved to Gallery: ${safeName}.png`, "success");
} catch (err) {
showToast(`Gallery save failed: ${err.message}`, "error");
}
}
// Uploads the composite via /upload/image, then (via window.opener,
// since WFS runs in its own window — same cross-window pattern as
// wfmReceiveWorkflow/wfmOpenMaskEditorForNode) writes the resulting
// filename into the "image" widget of the currently selected ComfyUI
// node (falling back to the first node in the graph with one), mirroring
// the chat_TE custom node's "Send to workflow" button.
async sendToWorkflow() {
if (!this._cb.getLayerManager()) { showToast("No image loaded", "error"); return; }
if (!window.opener || typeof window.opener.wfmSendImageToSelectedNode !== "function") {
showToast("Open Workflow Studio from ComfyUI's top menu to use this feature", "error");
return;
}
const canvas = this._buildCompositeCanvas();
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
const file = new File([blob], (this._cb.getBaseName() || "wfs-edit") + "-output.png", { type: "image/png" });
const form = new FormData();
form.append("image", file);
form.append("overwrite", "true");
try {
const r = await fetch("/upload/image", { method: "POST", body: form });
const data = await r.json();
const filename = data.subfolder ? `${data.subfolder}/${data.name}` : data.name;
window.opener.wfmSendImageToSelectedNode(filename);
showToast(`Sent "${filename}" to LI node`, "success");
} catch (err) {
showToast(`Send to LI node failed: ${err.message}`, "error");
}
}
}
+228
View File
@@ -0,0 +1,228 @@
/**
* Image Edit Tab - Fill Tool (bucket fill)
* Flood-fills a contiguous same-color region on the active layer canvas,
* either with a solid color or a linear/radial gradient.
* Gradient ramp math (evalGradient / hex<->rgb) is ported from
* comfyUI-particle-pixijs's particle_engine.js.
*/
function _hexToRgb01(hex) {
const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex || "#000000");
if (!m) return { r: 0, g: 0, b: 0 };
return { r: parseInt(m[1], 16) / 255, g: parseInt(m[2], 16) / 255, b: parseInt(m[3], 16) / 255 };
}
function _rgb01ToHex({ r, g, b }) {
const h = v => Math.round(Math.max(0, Math.min(1, v)) * 255).toString(16).padStart(2, "0");
return `#${h(r)}${h(g)}${h(b)}`;
}
function _lerp(a, b, t) { return a + (b - a) * t; }
export class FillTool {
constructor() {
// fill settings
this.tolerance = 32; // 0-255
this.fillMode = "solid"; // "solid" | "gradient"
this.color = "#ff0000"; // solid fill color
this.opacity = 1.0;
// gradient settings
this.gradientShape = "linear"; // "linear" | "radial"
this.gradientAngleDeg = 0; // linear direction
this.gradientStrength = 1.0; // 0.2-3.0, length/radius multiplier
this.gradientStops = [
{ pos: 0.0, color: "#ffffff" },
{ pos: 1.0, color: "#888888" },
];
this.selectedStopIdx = 0;
// internal state
this._active = false;
this._canvas = null;
this._ctx = null;
this._onChange = null;
}
setCanvas(canvas) {
this._canvas = canvas;
this._ctx = canvas ? canvas.getContext("2d") : null;
}
onChange(cb) { this._onChange = cb; }
activate() { this._active = true; }
deactivate() { this._active = false; }
// ── color ramp evaluation (ported from particle_engine.js evalGradient) ──
static evalGradient(stops, t) {
if (!stops || stops.length === 0) return { r: 0, g: 0, b: 0 };
const sorted = [...stops].sort((a, b) => a.pos - b.pos);
if (t <= sorted[0].pos) return _hexToRgb01(sorted[0].color);
const last = sorted[sorted.length - 1];
if (t >= last.pos) return _hexToRgb01(last.color);
for (let i = 0; i < sorted.length - 1; i++) {
const a = sorted[i], b = sorted[i + 1];
if (t >= a.pos && t <= b.pos) {
const span = b.pos - a.pos;
const localT = span > 0 ? (t - a.pos) / span : 0;
const ca = _hexToRgb01(a.color), cb = _hexToRgb01(b.color);
return {
r: _lerp(ca.r, cb.r, localT),
g: _lerp(ca.g, cb.g, localT),
b: _lerp(ca.b, cb.b, localT),
};
}
}
return _hexToRgb01(last.color);
}
/** Preview swatch color (hex) of the ramp at position t. */
evalGradientHex(t) {
return _rgb01ToHex(FillTool.evalGradient(this.gradientStops, t));
}
// ── stop editing helpers (ported from particle_widget.js addStop/removeStop/selectStop) ──
addStop() {
const sorted = [...this.gradientStops].sort((a, b) => a.pos - b.pos);
let bestGapStart = 0, bestGapSize = 0;
for (let i = 0; i < sorted.length - 1; i++) {
const gap = sorted[i + 1].pos - sorted[i].pos;
if (gap > bestGapSize) { bestGapSize = gap; bestGapStart = sorted[i].pos; }
}
const pos = sorted.length < 2 ? 0.5 : bestGapStart + bestGapSize / 2;
const color = _rgb01ToHex(FillTool.evalGradient(this.gradientStops, pos));
this.gradientStops.push({ pos, color });
this.selectedStopIdx = this.gradientStops.length - 1;
}
removeStop(idx = this.selectedStopIdx) {
if (this.gradientStops.length <= 1) return;
this.gradientStops.splice(idx, 1);
this.selectedStopIdx = Math.max(0, Math.min(this.selectedStopIdx, this.gradientStops.length - 1));
}
selectStop(idx) {
this.selectedStopIdx = idx;
}
// ── flood fill ────────────────────────────────────────
/**
* Flood-fills the contiguous region matching the pixel at (x, y).
* (x, y) are canvas-pixel coordinates (already converted via DrawTool.getCanvasPos).
*/
onMouseDown(x, y) {
if (!this._active || !this._ctx) return;
const w = this._canvas.width, h = this._canvas.height;
const px = Math.floor(x), py = Math.floor(y);
if (px < 0 || py < 0 || px >= w || py >= h) return;
const imgData = this._ctx.getImageData(0, 0, w, h);
const data = imgData.data;
const mask = this._buildFloodMask(data, w, h, px, py, this.tolerance);
if (!mask) return;
if (this.fillMode === "gradient") {
this._fillMaskWithGradient(data, w, h, mask.pixels, mask.bbox);
} else {
this._fillMaskWithSolid(data, mask.pixels, this.color, this.opacity);
}
this._ctx.putImageData(imgData, 0, 0);
}
/** Scanline stack-based flood fill. Returns { pixels: Uint8Array(w*h), bbox } or null. */
_buildFloodMask(data, w, h, startX, startY, tolerance) {
const idx0 = (startY * w + startX) * 4;
const tr = data[idx0], tg = data[idx0 + 1], tb = data[idx0 + 2], ta = data[idx0 + 3];
const tol2 = tolerance * tolerance;
const matches = (i) => {
const dr = data[i] - tr, dg = data[i + 1] - tg, db = data[i + 2] - tb, da = data[i + 3] - ta;
return (dr * dr + dg * dg + db * db + da * da) <= tol2 * 4;
};
const pixels = new Uint8Array(w * h);
const stack = [[startX, startY]];
let minX = startX, maxX = startX, minY = startY, maxY = startY;
while (stack.length) {
let [x, y] = stack.pop();
while (x >= 0 && matches((y * w + x) * 4)) x--;
x++;
let spanUp = false, spanDown = false;
while (x < w && matches((y * w + x) * 4) && !pixels[y * w + x]) {
pixels[y * w + x] = 1;
if (x < minX) minX = x; if (x > maxX) maxX = x;
if (y < minY) minY = y; if (y > maxY) maxY = y;
if (y > 0) {
const above = matches((( y - 1) * w + x) * 4) && !pixels[(y - 1) * w + x];
if (above && !spanUp) { stack.push([x, y - 1]); spanUp = true; }
else if (!above) spanUp = false;
}
if (y < h - 1) {
const below = matches(((y + 1) * w + x) * 4) && !pixels[(y + 1) * w + x];
if (below && !spanDown) { stack.push([x, y + 1]); spanDown = true; }
else if (!below) spanDown = false;
}
x++;
}
}
return { pixels, bbox: { minX, minY, maxX, maxY } };
}
_fillMaskWithSolid(data, pixels, colorHex, opacity) {
const { r, g, b } = _hexToRgb01(colorHex);
const cr = r * 255, cg = g * 255, cb = b * 255;
const alpha = Math.max(0, Math.min(1, opacity));
for (let i = 0; i < pixels.length; i++) {
if (!pixels[i]) continue;
const di = i * 4;
data[di] = _lerp(data[di], cr, alpha);
data[di + 1] = _lerp(data[di + 1], cg, alpha);
data[di + 2] = _lerp(data[di + 2], cb, alpha);
data[di + 3] = Math.max(data[di + 3], alpha * 255);
}
}
/** Reusable with any {pixels, bbox} mask (flood fill today; rect/ellipse selections in the future). */
_fillMaskWithGradient(data, w, h, pixels, bbox) {
const cx = (bbox.minX + bbox.maxX) / 2, cy = (bbox.minY + bbox.maxY) / 2;
const diagW = bbox.maxX - bbox.minX, diagH = bbox.maxY - bbox.minY;
const diag = Math.max(1, Math.hypot(diagW, diagH));
const strength = Math.max(0.2, Math.min(3.0, this.gradientStrength));
const alpha = Math.max(0, Math.min(1, this.opacity));
const angleRad = this.gradientAngleDeg * Math.PI / 180;
const dirX = Math.cos(angleRad), dirY = Math.sin(angleRad);
const halfLen = (diag / 2) * strength;
const radius = (diag / 2) * strength;
for (let y = bbox.minY; y <= bbox.maxY; y++) {
for (let x = bbox.minX; x <= bbox.maxX; x++) {
const i = y * w + x;
if (!pixels[i]) continue;
const dx = x - cx, dy = y - cy;
let t;
if (this.gradientShape === "radial") {
t = Math.hypot(dx, dy) / radius;
} else {
t = (dx * dirX + dy * dirY) / (halfLen * 2) + 0.5;
}
t = Math.max(0, Math.min(1, t));
const c = FillTool.evalGradient(this.gradientStops, t);
const di = i * 4;
data[di] = _lerp(data[di], c.r * 255, alpha);
data[di + 1] = _lerp(data[di + 1], c.g * 255, alpha);
data[di + 2] = _lerp(data[di + 2], c.b * 255, alpha);
data[di + 3] = Math.max(data[di + 3], alpha * 255);
}
}
}
}
+197
View File
@@ -0,0 +1,197 @@
/**
* Image Edit Tab - G'MIC Integration
* Launches the G'MIC GUI on the server for the active layer, polls job
* status, and applies the resulting image back onto the layer.
*/
import { showToast } from "../app.js";
export class GmicIntegration {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => void} callbacks.syncActiveLayerFromCanvas
* @param {() => void} callbacks.saveUndo
* @param {() => void} callbacks.updateCompositeView
* @param {() => void} callbacks.refreshLayerList
* @param {(toolId: string) => void} callbacks.renderToolOptions
*/
constructor(callbacks) {
this._cb = callbacks;
this.state = {
lastResultJobId: null,
processing: false,
aborted: false
};
}
renderPanel(el) {
const openBtnDisabled = this.state.processing ? "disabled" : "";
const applyBtnDisabled = (!this.state.lastResultJobId || this.state.processing) ? "disabled" : "";
const progressStyle = this.state.processing ? "display:flex" : "display:none";
el.innerHTML = `
<div class="ie-opt-group">
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="ie-gmic-open-btn" ${openBtnDisabled}>G'MIC GUIで編集</button>
<button class="wfm-btn wfm-btn-sm" id="ie-gmic-apply-btn" ${applyBtnDisabled}>結果を反映</button>
</div>
<div class="ie-opt-group" id="ie-gmic-progress-area" style="${progressStyle}; align-items:center; gap:6px;">
<span id="ie-gmic-progress-lbl" style="font-size:11px; color:var(--wfm-text-secondary);">G'MIC GUIを起動中...</span>
<button class="wfm-btn wfm-btn-sm" id="ie-gmic-abort-btn" style="background:#ea4335;color:#fff;">中断</button>
</div>
`;
document.getElementById("ie-gmic-open-btn")?.addEventListener("click", () => this.openGui());
document.getElementById("ie-gmic-apply-btn")?.addEventListener("click", () => this.applyResult());
document.getElementById("ie-gmic-abort-btn")?.addEventListener("click", () => this.abort());
}
async openGui() {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) { showToast("No image loaded", "error"); return; }
const layer = layerMgr.activeLayer;
if (!layer) { showToast("No active layer", "error"); return; }
this._cb.syncActiveLayerFromCanvas();
if (this.state.processing) return;
const dataUrl = layer.canvas.toDataURL("image/png");
this.state.processing = true;
const openBtn = document.getElementById("ie-gmic-open-btn");
const progressArea = document.getElementById("ie-gmic-progress-area");
const progressLbl = document.getElementById("ie-gmic-progress-lbl");
const applyBtn = document.getElementById("ie-gmic-apply-btn");
if (openBtn) openBtn.disabled = true;
if (applyBtn) applyBtn.disabled = true;
if (progressArea) progressArea.style.display = "flex";
if (progressLbl) progressLbl.textContent = "画像をサーバーへ送信中...";
try {
const res = await fetch("/api/wfm/gmic/open", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image_b64: dataUrl })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `HTTP ${res.status}`);
}
const data = await res.json();
this.state.lastResultJobId = data.job_id;
if (progressLbl) progressLbl.textContent = "G'MIC GUIで編集中... フィルターを選択して「OK」を押すと適用可能になります";
await this._waitForJob(data.job_id);
} catch (e) {
if (e.message !== "__aborted__") {
showToast("G'MIC Error: " + e.message, "error");
}
this.state.processing = false;
this.state.aborted = false;
if (openBtn) openBtn.disabled = false;
if (progressArea) progressArea.style.display = "none";
}
}
abort() {
this.state.aborted = true;
this.state.processing = false;
const openBtn = document.getElementById("ie-gmic-open-btn");
const progressArea = document.getElementById("ie-gmic-progress-area");
if (progressArea) progressArea.style.display = "none";
if (openBtn) openBtn.disabled = false;
}
async _waitForJob(jobId) {
const progressLbl = document.getElementById("ie-gmic-progress-lbl");
const applyBtn = document.getElementById("ie-gmic-apply-btn");
const maxWait = 600, interval = 2000;
const start = Date.now();
this.state.aborted = false;
while (true) {
if (this.state.aborted) throw new Error("__aborted__");
if ((Date.now() - start) / 1000 > maxWait) throw new Error("Timeout");
await new Promise(r => setTimeout(r, interval));
if (this.state.aborted) throw new Error("__aborted__");
try {
const res = await fetch(`/api/wfm/gmic/status/${jobId}`);
if (res.status === 404) throw new Error("__aborted__");
if (!res.ok) continue;
const status = await res.json();
if (status.status === "completed") {
this.state.lastResultJobId = jobId;
if (applyBtn) applyBtn.disabled = false;
if (progressLbl) progressLbl.textContent = "処理完了 → 「結果を反映」で画像に適用";
this.state.processing = false;
showToast("G'MIC filtering complete. Click Apply to insert result.", "success");
return;
}
if (status.status === "failed") {
if (progressLbl) progressLbl.textContent = status.error || "G'MIC GUIがキャンセルされました";
throw new Error("__aborted__");
}
if (progressLbl) progressLbl.textContent = status.message || "G'MIC GUIで編集中...";
} catch (e) {
if (e.message === "__aborted__" || e.message.includes("Timeout")) throw e;
}
}
}
async applyResult() {
if (!this.state.lastResultJobId) {
showToast("No G'MIC result to apply", "error");
return;
}
const applyBtn = document.getElementById("ie-gmic-apply-btn");
const openBtn = document.getElementById("ie-gmic-open-btn");
const progressArea = document.getElementById("ie-gmic-progress-area");
if (applyBtn) applyBtn.disabled = true;
try {
const statusRes = await fetch(`/api/wfm/gmic/status/${this.state.lastResultJobId}`);
if (!statusRes.ok) throw new Error(`HTTP ${statusRes.status}`);
const statusData = await statusRes.json();
if (!statusData.result_path) throw new Error("No result path found");
const b64res = await fetch("/api/wfm/gmic/result", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ result_path: statusData.result_path })
});
if (!b64res.ok) throw new Error(`HTTP ${b64res.status}`);
const { image_b64: dataUrl } = await b64res.json();
const img = await new Promise((resolve, reject) => {
const i = new Image();
i.onload = () => resolve(i);
i.onerror = () => reject(new Error("Failed to load result image"));
i.src = dataUrl;
});
this._cb.saveUndo();
const layerMgr = this._cb.getLayerManager();
const layer = layerMgr?.activeLayer;
if (!layer) throw new Error("No active layer");
layer.canvas.width = img.width;
layer.canvas.height = img.height;
layer.ctx = layer.canvas.getContext("2d");
layer.ctx.drawImage(img, 0, 0);
this._cb.updateCompositeView();
this._cb.refreshLayerList();
showToast("G'MIC filter applied successfully", "success");
// Reset G'MIC status
this.state.lastResultJobId = null;
this.state.processing = false;
if (openBtn) openBtn.disabled = false;
if (progressArea) progressArea.style.display = "none";
this._cb.renderToolOptions("filter");
} catch (err) {
showToast("Failed to apply G'MIC result: " + err.message, "error");
if (applyBtn) applyBtn.disabled = false;
}
}
}
+303
View File
@@ -0,0 +1,303 @@
/**
* Image Edit Tab - Inpaint / I2I Actions
* Composites the active mask layer against the background and runs it
* through GenerateUI's currently loaded workflow (or a dedicated one) for
* inpainting, plus a mask-less I2I variant. Also exposes the external
* entry points used by other same-origin panels (e.g. Comic Creator).
*/
import { showToast } from "../app.js";
import { comfyUI } from "../comfyui-client.js";
import { comfyEditor } from "../comfyui-editor.js";
import { comfyWorkflow } from "../comfyui-workflow.js";
export class InpaintI2IActions {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => HTMLCanvasElement} callbacks.buildBgCanvas
*/
constructor(callbacks) {
this._cb = callbacks;
this.positive = "";
this.negative = "";
this.growMaskBy = null; // null = 未初期化(ワークフローの現在値から初期化)
this.denoise = null; // null = 未初期化(ワークフローの現在値から初期化)
this.running = false;
this.resultUrl = null;
this.i2iExternalRunning = false;
// Inpaint 専用ワークフロー(OFF時は GenerateUI で読み込み中のワークフローを使用)
this.useDedicated = false;
this.dedicatedFilename = null;
this.workflowList = [];
}
async fetchWorkflowList(onLoaded) {
try {
const resp = await fetch(`${comfyUI.baseUrl}/api/wfm/workflows`);
if (!resp.ok) return;
const list = await resp.json();
this.workflowList = (list || []).map((w) => w.filename).filter(Boolean);
onLoaded?.();
} catch {
this.workflowList = [];
}
}
renderPanel() {
const pane = document.getElementById("ie-props-pane");
const body = document.getElementById("ie-props-body");
const title = document.getElementById("ie-props-title");
if (!pane || !body) return;
pane.style.display = "flex";
if (title) title.textContent = "Inpaint";
// 未初期化ならワークフローの現在値から初期化(VAEEncodeForInpaint.grow_mask_by / KSampler.denoise)
if (this.growMaskBy == null) {
this.growMaskBy = comfyUI.currentAnalysis?.inpaint_encode_nodes?.[0]?.grow_mask_by ?? 6;
}
if (this.denoise == null) {
const samplerNode = (comfyUI.currentAnalysis?.sampler_nodes || []).find((n) => n.denoise !== undefined);
this.denoise = samplerNode?.denoise ?? 1.0;
}
body.innerHTML = `
<div class="ie-props-row">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="ie-inpaint-use-dedicated" ${this.useDedicated ? "checked" : ""}>
Use dedicated workflow
</label>
</div>
<div class="ie-props-row" id="ie-inpaint-dedicated-row" style="${this.useDedicated ? "" : "display:none;"}">
<select id="ie-inpaint-dedicated-select" style="flex:1;">
<option value="">-- select workflow --</option>
${this.workflowList.map((f) => `<option value="${f}" ${f === this.dedicatedFilename ? "selected" : ""}>${f}</option>`).join("")}
</select>
</div>
<div class="ie-props-row" style="flex-direction:column;align-items:stretch;">
<label>Positive Prompt</label>
<textarea id="ie-inpaint-positive" rows="3" style="width:100%;resize:vertical;font-size:12px;">${this.positive}</textarea>
</div>
<div class="ie-props-row" style="flex-direction:column;align-items:stretch;">
<label>Negative Prompt</label>
<textarea id="ie-inpaint-negative" rows="3" style="width:100%;resize:vertical;font-size:12px;">${this.negative}</textarea>
</div>
<div class="ie-props-row">
<label>Grow Mask By</label>
<input type="number" id="ie-inpaint-grow-mask" min="0" max="200" step="1" value="${this.growMaskBy}" style="width:60px;">
</div>
<div class="ie-props-row">
<label>Denoise</label>
<input type="number" id="ie-inpaint-denoise" min="0" max="1" step="0.01" value="${this.denoise}" style="width:60px;">
</div>
<div class="ie-props-row">
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="ie-inpaint-run-btn" style="flex:1;" ${this.running ? "disabled" : ""}>
${this.running ? "Running..." : "Run"}
</button>
</div>
<span id="ie-inpaint-status" style="font-size:11px;color:var(--wfm-text-secondary);"></span>
${this.resultUrl ? `
<div class="ie-props-row" style="flex-direction:column;align-items:stretch;">
<label>Result</label>
<img src="${this.resultUrl}" style="max-width:100%;border-radius:var(--wfm-radius-sm);border:1px solid var(--wfm-border);">
</div>
` : ""}
`;
document.getElementById("ie-inpaint-use-dedicated")?.addEventListener("change", e => {
this.useDedicated = e.target.checked;
this.renderPanel();
});
document.getElementById("ie-inpaint-dedicated-select")?.addEventListener("change", e => {
this.dedicatedFilename = e.target.value || null;
});
document.getElementById("ie-inpaint-positive")?.addEventListener("input", e => { this.positive = e.target.value; });
document.getElementById("ie-inpaint-negative")?.addEventListener("input", e => { this.negative = e.target.value; });
document.getElementById("ie-inpaint-grow-mask")?.addEventListener("input", e => {
this.growMaskBy = parseInt(e.target.value) || 0;
});
document.getElementById("ie-inpaint-denoise")?.addEventListener("input", e => {
this.denoise = Math.max(0, Math.min(1, parseFloat(e.target.value)));
if (Number.isNaN(this.denoise)) this.denoise = 1.0;
});
document.getElementById("ie-inpaint-run-btn")?.addEventListener("click", () => this.run());
}
_exportMaskCanvas(maskLayer) {
const w = maskLayer.canvas.width, h = maskLayer.canvas.height;
const canvas = document.createElement("canvas");
canvas.width = w; canvas.height = h;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, w, h);
ctx.drawImage(maskLayer.canvas, 0, 0);
return canvas;
}
async run() {
if (this.running) return;
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) { showToast("No image loaded", "error"); return; }
// 非表示のマスクレイヤーはInpaint対象から除外する(目玉アイコンOFF=対象外)
const maskLayer = (layerMgr.activeLayer?.type === "mask" && layerMgr.activeLayer.visible)
? layerMgr.activeLayer
: layerMgr.layers.find(l => l.type === "mask" && l.visible);
if (!maskLayer) { showToast("Create or show a mask layer first (Mask tool)", "info"); return; }
if (this.useDedicated) {
if (!this.dedicatedFilename) { showToast("Select a dedicated workflow first", "info"); return; }
} else if (!comfyUI.currentAnalysis) {
showToast("Load a workflow in GenerateUI first", "info");
return;
}
const runBtn = document.getElementById("ie-inpaint-run-btn");
const statusEl = document.getElementById("ie-inpaint-status");
const setStatus = (msg) => { if (statusEl) statusEl.textContent = msg; };
this.running = true;
if (runBtn) { runBtn.disabled = true; runBtn.textContent = "Running..."; }
setStatus(this.useDedicated ? "Loading dedicated workflow..." : "Compositing...");
try {
// 専用ワークフロー使用時は GenerateUI の comfyUI.currentWorkflow/currentAnalysis には
// 一切触れず、ここでロード・解析したローカルなワークフロー/解析結果だけを使う。
let overrideOpts = {};
if (this.useDedicated) {
const resp = await fetch(`${comfyUI.baseUrl}/api/wfm/workflows/raw?filename=${encodeURIComponent(this.dedicatedFilename)}`);
if (!resp.ok) throw new Error(`Failed to load workflow (HTTP ${resp.status})`);
let dedicatedWorkflow = await resp.json();
const format = comfyWorkflow.detectFormat(dedicatedWorkflow, this.dedicatedFilename);
if (format === "ui") {
dedicatedWorkflow = await comfyWorkflow.convertUiToApi(dedicatedWorkflow);
} else if (format !== "api") {
throw new Error("Unsupported or unrecognized workflow format");
}
overrideOpts = { workflow: dedicatedWorkflow, analysis: comfyWorkflow.analyzeWorkflow(dedicatedWorkflow) };
}
setStatus("Compositing...");
const bgCanvas = this._cb.buildBgCanvas();
const imageBlob = await new Promise((resolve) => bgCanvas.toBlob(resolve, "image/png"));
const maskCanvas = this._exportMaskCanvas(maskLayer);
const maskBlob = await new Promise((resolve) => maskCanvas.toBlob(resolve, "image/png"));
const resultUrl = await this._runWithImages(imageBlob, maskBlob, {
positive: this.positive,
negative: this.negative,
growMaskBy: this.growMaskBy,
denoise: this.denoise,
overrideOpts,
onStatus: setStatus,
});
if (resultUrl) this.resultUrl = resultUrl;
setStatus("Done");
showToast("Inpaint generation complete", "success");
} catch (err) {
setStatus("Error");
showToast(`Inpaint failed: ${err.message}`, "error");
} finally {
this.running = false;
this.renderPanel();
}
}
// 共通処理: 画像+マスクBlobを対象ノード(LoadImage/MaskEditorOne)へ反映し、
// プロンプト/grow_mask_by/denoiseを設定してGenerate UIで実行、結果URLを返す。
// UI駆動の run() と外部(Comic Creator等)向けの runExternal() の両方から使う。
async _runWithImages(imageBlob, maskBlob, { positive, negative, growMaskBy, denoise, overrideOpts = {}, onStatus } = {}) {
const setStatus = onStatus || (() => {});
// LoadImage(の MASK 出力が使われている)スロットを優先し、無ければ Mask Editor One
// ノード(LoadImage を介さず画像/マスクを内包する custom node)にフォールバックする
const analysisForLookup = overrideOpts.analysis || comfyUI.currentAnalysis;
if (!analysisForLookup) throw new Error("No workflow loaded in GenerateUI");
const slotIndex = (analysisForLookup.load_image_nodes || []).findIndex(n => n.mask_used);
const meoNode = (analysisForLookup.mask_editor_one_nodes || [])[0];
if (slotIndex === -1 && !meoNode) {
throw new Error("No inpaint-capable LoadImage or Mask Editor One node found in the workflow");
}
setStatus("Uploading...");
if (slotIndex !== -1) {
await comfyEditor.applyImageAndMaskToSlot(imageBlob, maskBlob, slotIndex, overrideOpts);
} else {
await comfyEditor.applyImageAndMaskToMaskEditorOneNode(imageBlob, maskBlob, meoNode.id, overrideOpts);
}
comfyEditor.setPromptText("positive", positive, overrideOpts);
comfyEditor.setPromptText("negative", negative, overrideOpts);
comfyEditor.setInpaintParams({ growMaskBy, denoise, ...overrideOpts });
if (!window._wfmGenerateTab?.generate) throw new Error("GenerateUI is not ready yet");
setStatus("Generating...");
await window._wfmGenerateTab.generate(overrideOpts.workflow || undefined);
const resultImg = document.getElementById("wfm-gen-result-img");
return resultImg?.src || null;
}
// Comic Creator等、同一オリジンiframe越しの外部呼び出し専用エントリポイント。
// 専用ワークフロー選択(useDedicated)は扱わず、常にGenerate UIに現在
// ロード中のワークフロー(comfyUI.currentWorkflow/currentAnalysis)を対象にする。
async runExternal(imageBlob, maskBlob, { positive = "", negative = "", growMaskBy = 6, denoise = 1.0 } = {}) {
if (this.running) throw new Error("Inpaint is already running");
this.running = true;
try {
const resultUrl = await this._runWithImages(imageBlob, maskBlob, { positive, negative, growMaskBy, denoise });
if (!resultUrl) throw new Error("No result image produced");
return { ok: true, url: resultUrl };
} finally {
this.running = false;
}
}
// 共通処理: 画像Blob(マスクなし)を対象LoadImageノード(slot 0)へ反映し、
// プロンプト/denoiseを設定してGenerate UIで実行、結果URLを返す。
// _runWithImages のマスクなし版(Comic CreatorのSelect I2I連携専用)。
async _runI2IWithImage(imageBlob, { positive, negative, denoise, overrideOpts = {}, onStatus } = {}) {
const setStatus = onStatus || (() => {});
const analysisForLookup = overrideOpts.analysis || comfyUI.currentAnalysis;
if (!analysisForLookup) throw new Error("No workflow loaded in GenerateUI");
if (!(analysisForLookup.load_image_nodes?.length > 0)) {
throw new Error("No LoadImage node found in the workflow");
}
setStatus("Uploading...");
const file = new File([imageBlob], `i2i_${Math.random().toString(36).slice(2, 10)}.png`, { type: "image/png" });
await comfyEditor.applyImageToSlot(file, 0, overrideOpts);
comfyEditor.setPromptText("positive", positive, overrideOpts);
comfyEditor.setPromptText("negative", negative, overrideOpts);
comfyEditor.setInpaintParams({ denoise, ...overrideOpts });
if (!window._wfmGenerateTab?.generate) throw new Error("GenerateUI is not ready yet");
setStatus("Generating...");
await window._wfmGenerateTab.generate(overrideOpts.workflow || undefined);
const resultImg = document.getElementById("wfm-gen-result-img");
return resultImg?.src || null;
}
// Comic Creator等、同一オリジンiframe越しの外部呼び出し専用エントリポイント(I2I版)。
// runExternal と対になる、マスク不要のシンプルなI2I実行。
async runI2IExternal(imageBlob, { positive = "", negative = "", denoise = 1.0 } = {}) {
if (this.i2iExternalRunning) throw new Error("I2I is already running");
this.i2iExternalRunning = true;
try {
const resultUrl = await this._runI2IWithImage(imageBlob, { positive, negative, denoise });
if (!resultUrl) throw new Error("No result image produced");
return { ok: true, url: resultUrl };
} finally {
this.i2iExternalRunning = false;
}
}
}
+242
View File
@@ -0,0 +1,242 @@
/**
* Image Edit Tab - Layer & LayerManager
* Inspired by comfyui-mask-editor-one LayerManager.js
*/
export class Layer {
constructor(name, type, contentW, contentH) {
this.id = crypto.randomUUID();
this.name = name;
this.type = type; // 'draw' | 'image' | 'text'
// layer.canvas のサイズ = コンテンツのネイティブ解像度
this.canvas = document.createElement("canvas");
this.canvas.width = contentW;
this.canvas.height = contentH;
this.ctx = this.canvas.getContext("2d");
// 表示プロパティ
this.visible = true;
this.opacity = 1.0;
this.blendMode = "source-over";
// 変換プロパティ(キャンバス座標系での配置)
this.x = 0; // 左上X
this.y = 0; // 左上Y
this.displayW = contentW; // 表示幅
this.displayH = contentH; // 表示高さ
this.rotation = 0; // 度
this.flipX = false;
this.flipY = false;
this.textProps = null; // テキストレイヤー用プロパティ(再編集・再描画に使用)
this.locked = false; // ロック中は SelectTool の変形を禁止
this.maskApply = false; // マスクレイヤー: true=クリッピングマスクとして機能
this.operation = "add"; // マスクレイヤー合成モード: "add" | "subtract"
}
clear() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
getThumbnailDataURL(size = 32) {
const thumb = document.createElement("canvas");
thumb.width = size;
thumb.height = size;
const ctx = thumb.getContext("2d");
if (this.type === "mask") {
// マスクレイヤー: 黒背景に白マスクのグレースケール表示
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, size, size);
ctx.drawImage(this.canvas, 0, 0, size, size);
} else {
// 通常レイヤー: チェッカーボード背景(透過表示用)
ctx.fillStyle = "#aaa";
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = "#fff";
for (let x = 0; x < size; x += 8)
for (let y = 0; y < size; y += 8)
if ((x / 8 + y / 8) % 2 === 0) ctx.fillRect(x, y, 8, 8);
ctx.drawImage(this.canvas, 0, 0, size, size);
}
return thumb.toDataURL("image/png");
}
toJSON() {
return {
id: this.id, name: this.name, type: this.type,
imageData: this.canvas.toDataURL("image/png"),
visible: this.visible, opacity: this.opacity, blendMode: this.blendMode,
x: this.x, y: this.y, displayW: this.displayW, displayH: this.displayH,
rotation: this.rotation, flipX: this.flipX, flipY: this.flipY,
textProps: this.textProps ?? null,
locked: this.locked ?? false,
maskApply: this.maskApply ?? false,
operation: this.operation ?? "add",
};
}
static fromJSON(json) {
const cw = json.contentW ?? json.displayW ?? 512;
const ch = json.contentH ?? json.displayH ?? 512;
const layer = new Layer(json.name, json.type, cw, ch);
layer.id = json.id;
layer.visible = json.visible ?? true;
layer.opacity = json.opacity ?? 1.0;
layer.blendMode = json.blendMode ?? "source-over";
layer.x = json.x ?? 0;
layer.y = json.y ?? 0;
layer.displayW = json.displayW ?? cw;
layer.displayH = json.displayH ?? ch;
layer.rotation = json.rotation ?? 0;
layer.flipX = json.flipX ?? false;
layer.flipY = json.flipY ?? false;
layer.textProps = json.textProps ?? null;
layer.locked = json.locked ?? false;
layer.maskApply = json.maskApply ?? false;
layer.operation = json.operation ?? "add";
if (json.imageData) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => { layer.ctx.drawImage(img, 0, 0, cw, ch); resolve(layer); };
img.onerror = () => resolve(layer);
img.src = json.imageData;
});
}
return Promise.resolve(layer);
}
/** 変換行列を ctx に適用してから drawImage できる状態にする */
static applyTransform(ctx, layer) {
const cx = layer.x + layer.displayW / 2;
const cy = layer.y + layer.displayH / 2;
ctx.translate(cx, cy);
if (layer.rotation) ctx.rotate(layer.rotation * Math.PI / 180);
ctx.scale(
(layer.flipX ? -1 : 1) * (layer.displayW / layer.canvas.width),
(layer.flipY ? -1 : 1) * (layer.displayH / layer.canvas.height),
);
}
}
export class LayerManager {
constructor(width, height) {
this.width = width;
this.height = height;
this.layers = []; // 先頭 = 最前面
this.activeIndex = 0;
this._listeners = [];
}
get activeLayer() { return this.layers[this.activeIndex] ?? null; }
/**
* @param {string} type "draw" | "image" | "text"
* @param {string} name
* @param {object} opts { contentW, contentH, displayW, displayH, x, y }
*/
addLayer(type = "draw", name = null, opts = {}) {
const n = name ?? `Layer ${this.layers.length + 1}`;
const cw = opts.contentW ?? this.width;
const ch = opts.contentH ?? this.height;
const layer = new Layer(n, type, cw, ch);
layer.displayW = opts.displayW ?? cw;
layer.displayH = opts.displayH ?? ch;
layer.x = opts.x ?? 0;
layer.y = opts.y ?? 0;
this.layers.splice(this.activeIndex, 0, layer);
this._emit("change");
return layer;
}
deleteLayer(id) {
if (this.layers.length <= 1) return;
const idx = this.layers.findIndex(l => l.id === id);
if (idx < 0) return;
this.layers.splice(idx, 1);
this.activeIndex = Math.max(0, Math.min(this.activeIndex, this.layers.length - 1));
this._emit("change");
}
setActive(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx >= 0) { this.activeIndex = idx; this._emit("activeChange", this.layers[idx]); }
}
moveUp(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx <= 0) return;
[this.layers[idx - 1], this.layers[idx]] = [this.layers[idx], this.layers[idx - 1]];
if (this.activeIndex === idx) this.activeIndex = idx - 1;
else if (this.activeIndex === idx - 1) this.activeIndex = idx;
this._emit("change");
}
moveDown(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx < 0 || idx >= this.layers.length - 1) return;
[this.layers[idx], this.layers[idx + 1]] = [this.layers[idx + 1], this.layers[idx]];
if (this.activeIndex === idx) this.activeIndex = idx + 1;
else if (this.activeIndex === idx + 1) this.activeIndex = idx;
this._emit("change");
}
toggleVisible(id) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.visible = !layer.visible; this._emit("change"); }
}
toggleLocked(id) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.locked = !layer.locked; this._emit("change"); }
}
toggleMaskApply(id) {
const layer = this.layers.find(l => l.id === id);
if (layer && layer.type === "mask") { layer.maskApply = !layer.maskApply; this._emit("change"); }
}
toggleOperation(id) {
const layer = this.layers.find(l => l.id === id);
if (layer && layer.type === "mask") {
layer.operation = layer.operation === "add" ? "subtract" : "add";
this._emit("change");
}
}
setOpacity(id, opacity) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.opacity = Math.max(0, Math.min(1, opacity)); this._emit("change"); }
}
/** 全レイヤーを下→上の順で target canvas に変換付きで合成 */
composite(target) {
const ctx = target.getContext("2d");
ctx.clearRect(0, 0, target.width, target.height);
for (let i = this.layers.length - 1; i >= 0; i--) {
const layer = this.layers[i];
if (!layer.visible) continue;
ctx.save();
ctx.globalAlpha = layer.opacity;
ctx.globalCompositeOperation = layer.blendMode;
Layer.applyTransform(ctx, layer);
ctx.drawImage(layer.canvas, -layer.canvas.width / 2, -layer.canvas.height / 2);
ctx.restore();
}
}
on(event, fn) { this._listeners.push({ event, fn }); }
_emit(event, data) {
for (const l of this._listeners) if (l.event === event) l.fn(data);
}
toJSON() {
return { layers: this.layers.map(l => l.toJSON()), width: this.width, height: this.height };
}
async fromJSON(json) {
this.layers = await Promise.all((json.layers || []).map(lj => Layer.fromJSON(lj)));
this.activeIndex = 0;
this._emit("change");
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* Image Edit Tab - Mask Editor One 連携ブリッジ
* WFS Image Edit タブの合成画像を、ComfyUIキャンバス上のMaskEditorOneノード(選択中のノードを
* 優先、無ければグラフ内で最初に見つかったもの)へ送り、window.opener(ComfyUIタブ)側で実際の
* モーダルを開いて編集させ、Apply後の結果マスクを新規マスクレイヤーとしてWFS側に取り込む。
* 「Send to Workflow」の image ウィジェット探索と同じ「選択中優先・フォールバック」方式のため、
* WFS側のワークフロー読み込み状況とは無関係に動作する。
* モーダル自体は ComfyUI ページの LiteGraph ノードに強く依存するため、WFS 側からは
* window.opener.wfmOpenMaskEditorForNode()(web/comfyui/node_sets_menu.js 側で定義)を介して操作する。
*/
import { showToast } from "../app.js";
export class MaskEditorOneBridge {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => void} callbacks.saveUndo
* @param {() => void} callbacks.updateCompositeView
* @param {() => void} callbacks.refreshLayerList
* @param {() => HTMLCanvasElement} callbacks.buildBgCanvas
*/
constructor(callbacks) {
this._cb = callbacks;
this.running = false;
}
get bridgeReady() {
return !!(window.opener && typeof window.opener.wfmOpenMaskEditorForNode === "function");
}
async openEditor() {
if (this.running) return;
if (!this.bridgeReady) {
showToast("Open Workflow Studio from ComfyUI's top menu to use this feature", "error");
return;
}
const layerMgr = this._cb.getLayerManager();
if (!layerMgr) { showToast("No image loaded", "error"); return; }
this.running = true;
try {
const dataUrl = this._cb.buildBgCanvas().toDataURL("image/png");
// アクティブレイヤーが既存のマスクレイヤーなら、その内容もそのまま Mask Editor One の
// 初期マスクとして渡す(画像だけでなく、今描いているマスクも引き継ぐ)
const activeLayer = layerMgr.activeLayer;
const existingMaskDataUrl = activeLayer?.type === "mask" ? activeLayer.canvas.toDataURL("image/png") : null;
window.opener.focus();
showToast("Switch to the ComfyUI tab, edit the mask, then click Apply", "info");
const maskDataUrl = await window.opener.wfmOpenMaskEditorForNode(dataUrl, existingMaskDataUrl);
if (!maskDataUrl) {
showToast("Mask Editor One: cancelled (no changes)", "info");
return;
}
this._cb.saveUndo();
const maskLayer = layerMgr.addLayer("mask", "Mask Editor One", {
contentW: layerMgr.width, contentH: layerMgr.height,
displayW: layerMgr.width, displayH: layerMgr.height,
x: 0, y: 0,
});
layerMgr.setActive(maskLayer.id);
await this._applyMask(maskLayer, maskDataUrl);
this._cb.updateCompositeView();
this._cb.refreshLayerList();
showToast("Mask Editor One: mask imported", "success");
} catch (err) {
showToast("Mask Editor One error: " + err.message, "error");
} finally {
this.running = false;
}
}
// グレースケール輝度 → アルファ白マスクに変換して書き込む(Sam3Segmentation._applyMask と同じ変換)
_applyMask(maskLayer, maskDataUrl) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
const W = maskLayer.canvas.width;
const H = maskLayer.canvas.height;
const off = document.createElement("canvas");
off.width = W; off.height = H;
const mc = off.getContext("2d");
mc.drawImage(img, 0, 0, W, H);
const imgData = mc.getImageData(0, 0, W, H);
const d = imgData.data;
for (let i = 0; i < d.length; i += 4) {
const lum = d[i];
d[i] = d[i + 1] = d[i + 2] = 255;
d[i + 3] = lum;
}
mc.putImageData(imgData, 0, 0);
maskLayer.ctx.drawImage(off, 0, 0);
resolve();
};
img.onerror = resolve;
img.src = maskDataUrl;
});
}
}
+529
View File
@@ -0,0 +1,529 @@
/**
* Image Edit Tab - Mask Editor One 互換追加ツール
* Color, Alpha, Text, Vector, Shape の各マスクツール。
* マスクレイヤー canvas に直接白(add)または destination-out(erase)で描画する。
*/
// ── Color Tool ───────────────────────────────────────────────────────────────
// bgCanvas(背景合成画像)のクリック色に近いピクセルをマスク選択する。
export class MaskColorTool {
constructor() {
this.tolerance = 40; // 0-255
this.feather = 5; // 0-100 (tolerance に対する%)
this.mode = "add"; // "add" | "subtract"
this._canvas = null;
this._ctx = null;
this._bgCanvas = null;
this._onChange = null;
}
setCanvas(canvas) { this._canvas = canvas; this._ctx = canvas.getContext("2d"); }
setBgCanvas(canvas) { this._bgCanvas = canvas; }
onChange(fn) { this._onChange = fn; }
activate() { if (this._canvas) this._canvas.style.cursor = "crosshair"; }
deactivate() { if (this._canvas) this._canvas.style.cursor = ""; }
onMouseDown(x, y) { this._selectByColor(Math.round(x), Math.round(y)); }
onMouseMove() {}
onMouseUp() {}
onMouseLeave() {}
_selectByColor(px, py) {
if (!this._bgCanvas || !this._ctx || !this._canvas) return;
const bgCtx = this._bgCanvas.getContext("2d");
const bw = this._bgCanvas.width;
const bh = this._bgCanvas.height;
if (bw === 0 || bh === 0) return;
const srcData = bgCtx.getImageData(0, 0, bw, bh);
const dw = this._canvas.width;
const dh = this._canvas.height;
const sx = bw / dw;
const sy = bh / dh;
const bpx = Math.min(bw - 1, Math.round(px * sx));
const bpy = Math.min(bh - 1, Math.round(py * sy));
const idx = (bpy * bw + bpx) * 4;
if (idx < 0 || idx + 3 >= srcData.data.length) return;
const tr = srcData.data[idx];
const tg = srcData.data[idx + 1];
const tb = srcData.data[idx + 2];
const outData = new Uint8ClampedArray(dw * dh * 4);
const tol = this.tolerance;
for (let dy = 0; dy < dh; dy++) {
for (let dx = 0; dx < dw; dx++) {
const bx = Math.min(bw - 1, Math.round(dx * sx));
const by = Math.min(bh - 1, Math.round(dy * sy));
const si = (by * bw + bx) * 4;
const r = srcData.data[si];
const g = srcData.data[si + 1];
const b = srcData.data[si + 2];
const dist = Math.sqrt((r - tr) ** 2 + (g - tg) ** 2 + (b - tb) ** 2);
let alpha;
if (tol <= 0) {
alpha = dist === 0 ? 255 : 0;
} else {
const fStart = tol * (1 - this.feather / 100);
if (dist <= fStart) alpha = 255;
else if (dist <= tol) alpha = Math.round(255 * (1 - (dist - fStart) / (tol - fStart)));
else alpha = 0;
}
const j = (dy * dw + dx) * 4;
outData[j] = outData[j + 1] = outData[j + 2] = 255;
outData[j + 3] = alpha;
}
}
const tmp = document.createElement("canvas");
tmp.width = dw; tmp.height = dh;
tmp.getContext("2d").putImageData(new ImageData(outData, dw, dh), 0, 0);
const ctx = this._ctx;
ctx.globalCompositeOperation = this.mode === "subtract" ? "destination-out" : "lighten";
ctx.drawImage(tmp, 0, 0);
ctx.globalCompositeOperation = "source-over";
if (this._onChange) this._onChange();
}
}
// ── Alpha Tool ───────────────────────────────────────────────────────────────
// 元画像のアルファチャンネルをマスクとして抽出する。
export class MaskAlphaTool {
constructor() {
this.threshold = 128; // 0-255
this.invert = false;
this._canvas = null;
this._ctx = null;
this._srcImg = null; // HTMLImageElement or HTMLCanvasElement
this._onChange = null;
}
setCanvas(canvas) { this._canvas = canvas; this._ctx = canvas.getContext("2d"); }
setSourceImage(img) { this._srcImg = img; }
onChange(fn) { this._onChange = fn; }
activate() { if (this._canvas) this._canvas.style.cursor = "default"; }
deactivate() { if (this._canvas) this._canvas.style.cursor = ""; }
onMouseDown() {}
onMouseMove() {}
onMouseUp() {}
onMouseLeave() {}
extract() {
if (!this._srcImg || !this._ctx || !this._canvas) return;
const w = this._canvas.width;
const h = this._canvas.height;
const tmp = document.createElement("canvas");
tmp.width = w; tmp.height = h;
tmp.getContext("2d").drawImage(this._srcImg, 0, 0, w, h);
const src = tmp.getContext("2d").getImageData(0, 0, w, h);
const out = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < src.data.length; i += 4) {
let a = src.data[i + 3];
if (this.threshold > 0) a = a >= this.threshold ? 255 : 0;
if (this.invert) a = 255 - a;
out[i] = out[i + 1] = out[i + 2] = 255;
out[i + 3] = a;
}
this._ctx.clearRect(0, 0, w, h);
this._ctx.putImageData(new ImageData(out, w, h), 0, 0);
if (this._onChange) this._onChange();
}
}
// ── Text Tool ────────────────────────────────────────────────────────────────
// クリック位置にテキストを白(add)または消去(erase)でスタンプする。
export const MASK_TEXT_FONTS = [
"Arial", "Arial Black", "Georgia", "Times New Roman",
"Courier New", "Verdana", "Trebuchet MS", "Impact",
"Comic Sans MS", "Helvetica", "Tahoma",
];
export class MaskTextTool {
constructor() {
this.text = "Hello";
this.fontFamily = "Arial";
this.fontSize = 64;
this.bold = false;
this.italic = false;
this.align = "left";
this.mode = "add";
this._canvas = null;
this._ctx = null;
this._overlay = null;
this._onChange = null;
}
setCanvas(canvas) { this._canvas = canvas; this._ctx = canvas.getContext("2d"); }
onChange(fn) { this._onChange = fn; }
activate() { if (this._canvas) this._canvas.style.cursor = "crosshair"; }
deactivate() { this._closeOverlay(); if (this._canvas) this._canvas.style.cursor = ""; }
onMouseDown(x, y) {
if (this._overlay) { this._closeOverlay(); return; }
this._showOverlay(x, y);
}
onMouseMove() {}
onMouseUp() {}
onMouseLeave() {}
_getFont() {
const parts = [];
if (this.italic) parts.push("italic");
if (this.bold) parts.push("bold");
parts.push(`${this.fontSize}px`);
parts.push(`"${this.fontFamily}", sans-serif`);
return parts.join(" ");
}
_showOverlay(canvasX, canvasY) {
const cv = this._canvas;
const rect = cv.getBoundingClientRect();
const cssX = Math.round(canvasX * (rect.width / cv.width)) + rect.left;
const cssY = Math.round(canvasY * (rect.height / cv.height)) + rect.top;
const overlay = document.createElement("div");
overlay.style.cssText = [
`position:fixed;left:${cssX}px;top:${cssY}px;`,
"background:var(--wfm-surface,#2a2a2a);",
"border:1px solid var(--wfm-border,#444);",
"border-radius:4px;padding:6px;z-index:99999;",
"box-shadow:0 4px 16px rgba(0,0,0,0.5);min-width:200px;",
].join("");
const ta = document.createElement("textarea");
ta.value = this.text;
ta.rows = 3;
ta.placeholder = "Enter text…";
ta.style.cssText = [
"width:100%;resize:vertical;box-sizing:border-box;",
"background:var(--wfm-bg,#1a1a1a);color:var(--wfm-text,#ddd);",
"border:1px solid var(--wfm-border,#444);border-radius:3px;",
"padding:4px;font-size:12px;",
].join("");
overlay.appendChild(ta);
const btnRow = document.createElement("div");
btnRow.style.cssText = "display:flex;gap:4px;margin-top:4px;";
const okBtn = document.createElement("button");
okBtn.textContent = "Stamp";
okBtn.className = "wfm-btn wfm-btn-sm wfm-btn-primary";
okBtn.style.flex = "1";
okBtn.onclick = () => {
if (ta.value.trim()) { this.text = ta.value; this._stamp(canvasX, canvasY); }
this._closeOverlay();
};
const cancelBtn = document.createElement("button");
cancelBtn.textContent = "Cancel";
cancelBtn.className = "wfm-btn wfm-btn-sm";
cancelBtn.style.flex = "1";
cancelBtn.onclick = () => this._closeOverlay();
btnRow.appendChild(okBtn);
btnRow.appendChild(cancelBtn);
overlay.appendChild(btnRow);
const hint = document.createElement("div");
hint.textContent = "Ctrl+Enter: Stamp / Esc: Cancel";
hint.style.cssText = "font-size:10px;color:var(--wfm-text-secondary,#888);margin-top:3px;";
overlay.appendChild(hint);
ta.addEventListener("keydown", e => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); okBtn.click(); }
else if (e.key === "Escape") cancelBtn.click();
e.stopPropagation();
});
overlay.addEventListener("mousedown", e => e.stopPropagation());
document.body.appendChild(overlay);
this._overlay = overlay;
ta.focus(); ta.select();
}
_closeOverlay() {
if (this._overlay) { this._overlay.remove(); this._overlay = null; }
}
_stamp(x, y) {
const ctx = this._ctx;
ctx.save();
ctx.font = this._getFont();
ctx.textAlign = this.align;
ctx.textBaseline = "top";
if (this.mode === "erase") {
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = "rgba(0,0,0,1)";
} else {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "white";
}
const lines = this.text.split("\n");
const lineHeight = this.fontSize * 1.2;
for (let i = 0; i < lines.length; i++) ctx.fillText(lines[i], x, y + i * lineHeight);
ctx.restore();
if (this._onChange) this._onChange();
}
}
// ── Vector Tool ──────────────────────────────────────────────────────────────
// クリックでポイント追加、Catmull-Rom スプラインで閉じたパスを塗りつぶす。
const VECTOR_CLOSE_R = 12;
export class MaskVectorTool {
constructor() {
this.mode = "add";
this._canvas = null;
this._ctx = null;
this._previewCanvas = null;
this._points = [];
this._hoverX = null;
this._hoverY = null;
this.onBeforeCommit = null;
this._onChange = null;
}
setCanvas(canvas) { this._canvas = canvas; this._ctx = canvas.getContext("2d"); }
setPreviewCanvas(canvas) { this._previewCanvas = canvas; }
onChange(fn) { this._onChange = fn; }
activate() { if (this._canvas) this._canvas.style.cursor = "crosshair"; this._renderPreview(); }
deactivate() { if (this._canvas) this._canvas.style.cursor = ""; this._clearPreview(); }
reset() { this._points = []; this._hoverX = null; this._hoverY = null; this._clearPreview(); }
onMouseDown(x, y) {
if (this._points.length >= 3) {
const f = this._points[0];
if (Math.hypot(x - f.x, y - f.y) <= VECTOR_CLOSE_R) { this._commitPath(true); return; }
}
this._points.push({ x, y });
this._renderPreview();
}
onMouseMove(x, y) { this._hoverX = x; this._hoverY = y; this._renderPreview(); }
onMouseLeave() { this._hoverX = null; this._hoverY = null; this._renderPreview(); }
onMouseUp() {}
onKeyDown(e) {
if (e.key === "Escape") {
e.preventDefault(); this.reset();
} else if (e.key === "Enter" && this._points.length >= 2) {
e.preventDefault(); this._commitPath(false);
} else if ((e.key === "Backspace" || e.key === "Delete") && this._points.length > 0) {
e.preventDefault(); this._points.pop(); this._renderPreview();
}
}
_commitPath(closed) {
if (this._points.length < 2) return;
if (this.onBeforeCommit) this.onBeforeCommit();
const ctx = this._ctx;
ctx.save();
if (this.mode === "erase") {
ctx.globalCompositeOperation = "destination-out";
ctx.fillStyle = "rgba(0,0,0,1)";
} else {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "white";
}
ctx.beginPath();
this._buildSpline(ctx, this._points, closed);
ctx.fill();
ctx.restore();
this.reset();
if (this._onChange) this._onChange();
}
_buildSpline(ctx, pts, closed) {
const n = pts.length;
if (n === 0) return;
if (n === 1) { ctx.moveTo(pts[0].x, pts[0].y); return; }
if (n === 2) {
ctx.moveTo(pts[0].x, pts[0].y); ctx.lineTo(pts[1].x, pts[1].y);
if (closed) ctx.closePath(); return;
}
let ext;
if (closed) {
ext = [pts[n - 1], ...pts, pts[0], pts[1]];
} else {
ext = [
{ x: 2 * pts[0].x - pts[1].x, y: 2 * pts[0].y - pts[1].y },
...pts,
{ x: 2 * pts[n-1].x - pts[n-2].x, y: 2 * pts[n-1].y - pts[n-2].y },
];
}
ctx.moveTo(ext[1].x, ext[1].y);
const count = closed ? n : n - 1;
for (let i = 0; i < count; i++) {
const [p0, p1, p2, p3] = [ext[i], ext[i+1], ext[i+2], ext[i+3]];
ctx.bezierCurveTo(
p1.x + (p2.x - p0.x) / 6, p1.y + (p2.y - p0.y) / 6,
p2.x - (p3.x - p1.x) / 6, p2.y - (p3.y - p1.y) / 6,
p2.x, p2.y,
);
}
if (closed) ctx.closePath();
}
_renderPreview() {
if (!this._previewCanvas) return;
const pctx = this._previewCanvas.getContext("2d");
const w = this._previewCanvas.width, h = this._previewCanvas.height;
pctx.clearRect(0, 0, w, h);
const pts = this._points, hx = this._hoverX, hy = this._hoverY;
if (pts.length === 0 && hx === null) return;
if (pts.length >= 2) {
pctx.save();
pctx.strokeStyle = "rgba(255,210,40,0.9)"; pctx.lineWidth = 1.5; pctx.setLineDash([]);
pctx.beginPath(); this._buildSpline(pctx, pts, false); pctx.stroke();
pctx.restore();
}
if (pts.length >= 1 && hx !== null) {
const canClose = pts.length >= 3 && Math.hypot(hx - pts[0].x, hy - pts[0].y) <= VECTOR_CLOSE_R;
pctx.save();
if (canClose) {
pctx.strokeStyle = "rgba(255,100,100,0.55)"; pctx.lineWidth = 1.5; pctx.setLineDash([4, 3]);
pctx.beginPath(); this._buildSpline(pctx, pts, true); pctx.stroke();
} else {
pctx.strokeStyle = "rgba(255,210,40,0.5)"; pctx.lineWidth = 1; pctx.setLineDash([4, 3]);
pctx.beginPath();
pctx.moveTo(pts[pts.length - 1].x, pts[pts.length - 1].y);
pctx.lineTo(hx, hy); pctx.stroke();
}
pctx.restore();
}
for (let i = 0; i < pts.length; i++) {
const p = pts[i], isFirst = i === 0;
const closeable = isFirst && pts.length >= 3 && hx !== null && Math.hypot(hx - p.x, hy - p.y) <= VECTOR_CLOSE_R;
pctx.beginPath();
pctx.arc(p.x, p.y, closeable ? 7 : (isFirst ? 5 : 4), 0, Math.PI * 2);
pctx.fillStyle = closeable ? "rgba(255,80,80,0.95)" : (isFirst ? "rgba(255,210,40,0.95)" : "rgba(255,210,40,0.8)");
pctx.strokeStyle = "rgba(0,0,0,0.6)"; pctx.lineWidth = 1;
pctx.fill(); pctx.stroke();
}
if (hx !== null) {
const onFirst = pts.length >= 3 && Math.hypot(hx - pts[0].x, hy - pts[0].y) <= VECTOR_CLOSE_R;
if (!onFirst) {
pctx.beginPath(); pctx.arc(hx, hy, 3, 0, Math.PI * 2);
pctx.fillStyle = "rgba(255,255,255,0.6)"; pctx.strokeStyle = "rgba(200,200,200,0.5)"; pctx.lineWidth = 1;
pctx.fill(); pctx.stroke();
}
}
}
_clearPreview() {
if (!this._previewCanvas) return;
const c = this._previewCanvas;
c.getContext("2d").clearRect(0, 0, c.width, c.height);
}
}
// ── Shape Tool ───────────────────────────────────────────────────────────────
// ドラッグで矩形または楕円をマスクとして描画する(Shift = 正方形/正円)。
export class MaskShapeTool {
constructor() {
this.mode = "add";
this.shape = "rect"; // "rect" | "ellipse"
this._canvas = null;
this._ctx = null;
this._previewCanvas = null;
this._pCtx = null;
this._startX = 0;
this._startY = 0;
this._curX = 0;
this._curY = 0;
this._curShift = false;
this._drawing = false;
this._onChange = null;
}
setCanvas(canvas) { this._canvas = canvas; this._ctx = canvas.getContext("2d"); }
setPreviewCanvas(canvas) { this._previewCanvas = canvas; this._pCtx = canvas.getContext("2d"); }
onChange(fn) { this._onChange = fn; }
activate() { if (this._canvas) this._canvas.style.cursor = "crosshair"; }
deactivate() { this._drawing = false; this._clearPreview(); if (this._canvas) this._canvas.style.cursor = ""; }
onMouseDown(x, y) {
this._startX = x; this._startY = y;
this._curX = x; this._curY = y; this._curShift = false;
this._drawing = true;
this._drawPreview(x, y, false);
}
onMouseMove(x, y, e) {
if (!this._drawing) return;
this._curX = x; this._curY = y; this._curShift = e?.shiftKey ?? false;
this._drawPreview(x, y, this._curShift);
}
// x/y を省略した場合は最後に記録した座標を使用(mouseupイベント非経由での呼び出し対応)
onMouseUp(x, y, e) {
if (!this._drawing) return;
const cx = x ?? this._curX;
const cy = y ?? this._curY;
const shift = e?.shiftKey ?? this._curShift;
this._drawing = false;
this._clearPreview();
this._commit(cx, cy, shift);
if (this._onChange) this._onChange();
}
onMouseLeave() {}
_getRect(x, y, shift) {
const sx = this._startX, sy = this._startY;
if (shift) {
const half = Math.max(Math.abs(x - sx), Math.abs(y - sy));
return { x: sx - half, y: sy - half, w: half * 2, h: half * 2 };
}
return { x: Math.min(sx, x), y: Math.min(sy, y), w: Math.abs(x - sx), h: Math.abs(y - sy) };
}
_drawPreview(x, y, shift) {
if (!this._pCtx) return;
const pc = this._previewCanvas;
this._pCtx.clearRect(0, 0, pc.width, pc.height);
const { x: rx, y: ry, w, h } = this._getRect(x, y, shift);
if (w < 1 || h < 1) return;
this._pCtx.save();
this._pCtx.strokeStyle = "rgba(0,180,255,0.9)"; this._pCtx.lineWidth = 1.5; this._pCtx.setLineDash([5, 3]);
this._pCtx.beginPath();
if (this.shape === "rect") this._pCtx.rect(rx, ry, w, h);
else this._pCtx.ellipse(rx + w / 2, ry + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
this._pCtx.stroke(); this._pCtx.restore();
}
_clearPreview() {
if (!this._pCtx) return;
this._pCtx.clearRect(0, 0, this._previewCanvas.width, this._previewCanvas.height);
}
_commit(x, y, shift) {
const { x: rx, y: ry, w, h } = this._getRect(x, y, shift);
if (w < 1 || h < 1) return;
const ctx = this._ctx;
ctx.save();
ctx.globalCompositeOperation = this.mode === "erase" ? "destination-out" : "source-over";
ctx.fillStyle = "white";
ctx.beginPath();
if (this.shape === "rect") ctx.rect(rx, ry, w, h);
else ctx.ellipse(rx + w / 2, ry + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
ctx.fill(); ctx.restore();
}
}
+334
View File
@@ -0,0 +1,334 @@
/**
* Image Edit Tab - Mask Tool
* White-paint / erase brush for mask layers.
* paint mode: draws white (opaque) = mask present
* erase mode: destination-out (transparent) = mask absent
*
* Supports circular soft brush (built-in) and image brushes loaded
* from Mask Editor One's ABR brush library (optional).
*/
export class MaskTool {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas?.getContext("2d");
this.brushSize = 30;
this.hardness = 0.85;
this.spacing = 0.25; // stamp interval as fraction of brushSize (image brush only)
this.mode = "paint"; // "paint" | "erase"
// Image brush from ABR library (null = default circle brush)
this.brushImage = null;
this.brushName = "Circle";
this.angle = 0; // degrees [0, 359]
this.sizeJitter = false;
this.sizeJitterAmount = 0.5; // 0–1: fraction of brushSize that can be removed
this.rotationJitter = false;
// Pen pressure (0–1, from PointerEvent.pressure; mouse reports 0.5).
// pressure=0.5 maps to a 1.0x multiplier so mouse behavior is unchanged.
this.pressureEnabled = true;
this._lastPressure = 0.5;
this._drawing = false;
this._lastX = 0;
this._lastY = 0;
// Cached circle stamp
this._stamp = null;
this._stampSize = 0;
this._stampHard = 0;
this._stampMode = null;
// Cached image stamp
this._imgStamp = null;
this._imgStampSize = 0;
this._imgStampImg = null;
// Stroke buffer: prevents intra-stroke opacity accumulation (image brush only)
this._baseCanvas = null;
this._strokeCanvas = null;
this._strokeCtx = null;
this._onChange = null;
}
setCanvas(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this._stamp = null;
this._imgStamp = null;
}
onChange(fn) { this._onChange = fn; }
setImageBrush(img, name) {
this.brushImage = img;
this.brushName = name;
this._imgStamp = null;
}
clearImageBrush() {
this.brushImage = null;
this.brushName = "Circle";
this._stamp = null;
this._imgStamp = null;
}
activate() {
if (this.canvas) this.canvas.style.cursor = "none";
}
deactivate() {
this._drawing = false;
this._clearStrokeBuffer();
if (this.canvas) this.canvas.style.cursor = "";
}
onMouseDown(x, y, pressure = 0.5) {
this._drawing = true;
this._lastX = x;
this._lastY = y;
this._lastPressure = pressure;
if (this.brushImage) {
this._initStrokeBuffer();
this._paintToStroke(x, y, pressure);
this._mergeStroke();
} else {
this._paint(x, y, pressure);
}
}
onMouseMove(x, y, pressure = 0.5) {
if (!this._drawing) return;
if (this.brushImage) {
this._paintLineToStroke(this._lastX, this._lastY, x, y, this._lastPressure, pressure);
this._mergeStroke();
} else {
this._paintLine(this._lastX, this._lastY, x, y, this._lastPressure, pressure);
}
this._lastX = x;
this._lastY = y;
this._lastPressure = pressure;
}
onMouseUp() {
if (this._drawing) {
this._drawing = false;
this._clearStrokeBuffer();
if (this._onChange) this._onChange();
}
}
onMouseLeave() {
if (this._drawing) this.onMouseUp();
}
// ── Pressure response ──────────────────────────────────────────────
_effectiveSize(pressure) {
if (!this.pressureEnabled) return this.brushSize;
const p = Math.max(0, Math.min(1, pressure ?? 0.5));
return Math.max(1, this.brushSize * (0.3 + p * 1.4)); // p=0.5 -> 1.0x
}
// ── Stroke buffer (image brush only) ─────────────────────────────
_initStrokeBuffer() {
const w = this.canvas.width;
const h = this.canvas.height;
this._baseCanvas = document.createElement("canvas");
this._baseCanvas.width = w;
this._baseCanvas.height = h;
this._baseCanvas.getContext("2d").drawImage(this.canvas, 0, 0);
this._strokeCanvas = document.createElement("canvas");
this._strokeCanvas.width = w;
this._strokeCanvas.height = h;
this._strokeCtx = this._strokeCanvas.getContext("2d");
}
_clearStrokeBuffer() {
this._baseCanvas = null;
this._strokeCanvas = null;
this._strokeCtx = null;
}
_mergeStroke() {
const ctx = this.ctx;
const w = this.canvas.width;
const h = this.canvas.height;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(this._baseCanvas, 0, 0);
ctx.globalCompositeOperation = this.mode === "erase" ? "destination-out" : "lighten";
ctx.drawImage(this._strokeCanvas, 0, 0);
ctx.globalCompositeOperation = "source-over";
}
_paintToStroke(x, y, pressure = 0.5) {
const saved = this.ctx;
this.ctx = this._strokeCtx;
let size = this._effectiveSize(pressure);
if (this.sizeJitter) {
size = Math.max(1, size * (1 - Math.random() * this.sizeJitterAmount));
}
if (this.rotationJitter) {
const savedAngle = this.angle;
this.angle = Math.random() * 360;
this._paintImageBrush(x, y, size);
this.angle = savedAngle;
} else {
this._paintImageBrush(x, y, size);
}
this.ctx = saved;
}
_paintLineToStroke(x0, y0, x1, y1, p0 = 0.5, p1 = 0.5) {
const dist = Math.hypot(x1 - x0, y1 - y0);
const step = Math.max(1, this.brushSize * this.spacing);
const steps = Math.ceil(dist / step);
for (let i = 1; i <= steps; i++) {
const t = i / steps;
this._paintToStroke(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, p0 + (p1 - p0) * t);
}
}
// ── Circle brush ─────────────────────────────────────────────────
_getStamp(size) {
size = Math.max(1, Math.round(size));
if (
this._stamp &&
this._stampSize === size &&
this._stampHard === this.hardness &&
this._stampMode === this.mode
) return this._stamp;
const sc = document.createElement("canvas");
sc.width = size;
sc.height = size;
const sctx = sc.getContext("2d");
const cx = size / 2, cy = size / 2, r = size / 2;
const color = this.mode === "paint" ? "#ffffff" : "#000000";
const colorAlpha = this.mode === "paint" ? "rgba(255,255,255,0)" : "rgba(0,0,0,0)";
const innerR = r * (1 - Math.min(this.hardness, 0.99)) * 0.95;
const grd = sctx.createRadialGradient(cx, cy, innerR, cx, cy, r);
grd.addColorStop(0, color);
grd.addColorStop(1, colorAlpha);
sctx.fillStyle = grd;
sctx.beginPath();
sctx.arc(cx, cy, r, 0, Math.PI * 2);
sctx.fill();
this._stamp = sc;
this._stampSize = size;
this._stampHard = this.hardness;
this._stampMode = this.mode;
return sc;
}
_paint(x, y, pressure = 0.5) {
const size = this._effectiveSize(pressure);
const stamp = this._getStamp(size);
const s = stamp.width;
this.ctx.save();
if (this.mode === "erase") {
this.ctx.globalCompositeOperation = "destination-out";
}
this.ctx.drawImage(stamp, x - s / 2, y - s / 2);
this.ctx.restore();
}
_paintLine(x0, y0, x1, y1, p0 = 0.5, p1 = 0.5) {
const dist = Math.hypot(x1 - x0, y1 - y0);
const spacing = Math.max(1, this.brushSize * 0.2);
const steps = Math.max(1, Math.ceil(dist / spacing));
for (let i = 1; i <= steps; i++) {
const t = i / steps;
this._paint(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, p0 + (p1 - p0) * t);
}
}
// ── Image brush ──────────────────────────────────────────────────
_getImageStamp(size) {
size = Math.max(1, size);
if (
this._imgStamp &&
this._imgStampSize === size &&
this._imgStampImg === this.brushImage
) return this._imgStamp;
const img = this.brushImage;
const srcW = img.naturalWidth || img.width;
const srcH = img.naturalHeight || img.height;
const aspect = (srcW > 0 && srcH > 0) ? srcW / srcH : 1;
const stampH = size;
const stampW = Math.max(1, Math.round(size * aspect));
const sc = document.createElement("canvas");
sc.width = stampW;
sc.height = stampH;
const stx = sc.getContext("2d");
stx.drawImage(img, 0, 0, stampW, stampH);
const imgData = stx.getImageData(0, 0, stampW, stampH);
const d = imgData.data;
// Detect alpha channel (ABR-exported PNGs carry alpha = brush density)
let hasAlpha = false;
for (let i = 3; i < d.length; i += 4) {
if (d[i] < 250) { hasAlpha = true; break; }
}
let invertLum = false;
if (!hasAlpha) {
const corners = [0, stampW - 1, stampW * (stampH - 1), stampW * stampH - 1];
let bgLum = 0;
for (const ci of corners) {
const ii = ci * 4;
bgLum += (d[ii] * 0.299 + d[ii + 1] * 0.587 + d[ii + 2] * 0.114) / 255;
}
invertLum = (bgLum / corners.length) > 0.5;
}
// Convert to white pixels; alpha = brush density
for (let i = 0; i < d.length; i += 4) {
let alpha;
if (hasAlpha) {
alpha = d[i + 3] / 255;
} else {
const lum = (d[i] * 0.299 + d[i + 1] * 0.587 + d[i + 2] * 0.114) / 255;
alpha = invertLum ? 1 - lum : lum;
}
d[i] = d[i + 1] = d[i + 2] = 255;
d[i + 3] = Math.round(alpha * 255);
}
stx.putImageData(imgData, 0, 0);
this._imgStamp = sc;
this._imgStampSize = size;
this._imgStampImg = this.brushImage;
return sc;
}
_paintImageBrush(x, y, size = this.brushSize) {
const stamp = this._getImageStamp(Math.round(size));
this.ctx.globalCompositeOperation = "source-over";
if (this.angle) {
this.ctx.save();
this.ctx.translate(Math.round(x), Math.round(y));
this.ctx.rotate((this.angle * Math.PI) / 180);
this.ctx.drawImage(stamp, -stamp.width / 2, -stamp.height / 2);
this.ctx.restore();
} else {
this.ctx.drawImage(stamp, Math.round(x - stamp.width / 2), Math.round(y - stamp.height / 2));
}
this.ctx.globalCompositeOperation = "source-over";
}
}
+248
View File
@@ -0,0 +1,248 @@
/**
* Image Edit Tab - SAM3 Segmentation (Mask Editor One integration)
* Text-prompted segmentation via the Mask Editor One SAM3 server endpoints.
* Rendered as a subtool of the Mask tool; the toolbar shell itself stays in
* ImageEditTab (shared with the other mask subtools), but the prompt/run
* controls and the result thumbnail grid are owned here.
*/
import { showToast } from "../app.js";
export class Sam3Segmentation {
/**
* @param {object} callbacks
* @param {() => object|null} callbacks.getLayerManager
* @param {() => void} callbacks.saveUndo
* @param {() => void} callbacks.updateCompositeView
* @param {() => void} callbacks.refreshLayerList
* @param {(toolId: string) => void} callbacks.renderToolOptions
* @param {(sub: string) => void} callbacks.renderMaskProps
*/
constructor(callbacks) {
this._cb = callbacks;
this.available = false;
this.results = []; // [{mask_b64, score, area}, ...]
this.prompt = "";
this.maxMasks = 9;
this.loading = false;
this.mode = "add"; // "add" | "erase"
this.selected = new Set(); // 選択中の結果インデックス
}
async checkAvailability() {
try {
const resp = await fetch("/mask_editor/sam3/status");
if (!resp.ok) return;
const json = await resp.json();
this.available = json.loaded === true || json.ckpt_found === true;
} catch {
this.available = false;
}
}
// マスクツールバー内、SAM3選択時にのみ表示するprompt/max/runコントロール
renderToolbarExtra(activeSub) {
if (!this.available || activeSub !== "sam3") return "";
return `
<div class="ie-opt-group">
<input type="text" id="ie-sam3-prompt" class="ie-opt-input"
placeholder="e.g. cat, person..."
value="${this.prompt}"
style="width:160px;font-size:11px;padding:2px 6px;border:1px solid var(--wfm-border);border-radius:3px;background:var(--wfm-surface);color:var(--wfm-text);">
</div>
<div class="ie-opt-group">
<label style="font-size:11px;color:var(--wfm-text-secondary);">Max</label>
<select id="ie-sam3-max" class="ie-opt-select" style="width:44px;">
${[3,6,9,12].map(n => `<option value="${n}"${n === this.maxMasks ? " selected" : ""}>${n}</option>`).join("")}
</select>
</div>
<div class="ie-opt-group">
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="ie-sam3-run-btn" ${this.loading ? "disabled" : ""}>
${this.loading ? "Running..." : "Segment"}
</button>
</div>
<span id="ie-sam3-status" style="font-size:11px;color:var(--wfm-text-secondary);margin-left:4px;">
${this.results.length > 0 ? `${this.results.length} masks found` : ""}
</span>
`;
}
bindToolbarEvents() {
document.getElementById("ie-sam3-prompt")?.addEventListener("input", e => {
this.prompt = e.target.value;
});
document.getElementById("ie-sam3-max")?.addEventListener("change", e => {
this.maxMasks = parseInt(e.target.value);
});
document.getElementById("ie-sam3-run-btn")?.addEventListener("click", () => this.runSegment());
}
// props ペイン("sam3" サブツール選択時): モード切替 + 結果サムネイルグリッド
renderResultsPanel(body) {
const modeAdd = this.mode === "add";
const selCount = this.selected.size;
const hasResult = this.results.length > 0;
body.innerHTML = `
<div class="ie-props-row">
<label>Mode</label>
<div style="display:flex;gap:4px;">
<button class="wfm-btn wfm-btn-sm${modeAdd ? " ie-opt-active" : ""}" id="ie-sam3-mode-add" style="flex:1;">Add</button>
<button class="wfm-btn wfm-btn-sm${!modeAdd ? " ie-opt-active" : ""}" id="ie-sam3-mode-erase" style="flex:1;">Erase</button>
</div>
</div>
${hasResult ? `
<div class="ie-props-row" style="flex-direction:column;align-items:stretch;gap:4px;">
<div style="font-size:11px;color:var(--wfm-text-secondary);">Click to select / deselect:</div>
<div id="ie-sam3-results" style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;">
${this.results.map((r, i) => {
const sel = this.selected.has(i);
const borderColor = sel ? "var(--wfm-primary,#4682e6)" : "var(--wfm-border)";
const bg = sel ? "color-mix(in srgb,var(--wfm-primary,#4682e6) 15%,transparent)" : "transparent";
return `<div class="ie-sam3-thumb" data-idx="${i}"
style="cursor:pointer;border:2px solid ${borderColor};border-radius:4px;overflow:hidden;text-align:center;background:${bg};position:relative;">
<img src="${r.mask_b64}" style="width:100%;display:block;background:#000;">
<div style="font-size:10px;padding:2px 0;color:var(--wfm-text-secondary);">
${Math.round((r.score ?? 0) * 100)}%
</div>
${sel ? '<div style="position:absolute;top:2px;right:3px;font-size:12px;line-height:1;color:var(--wfm-primary,#4682e6);">✓</div>' : ""}
</div>`;
}).join("")}
</div>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="ie-sam3-apply-btn"
${selCount === 0 ? "disabled" : ""} style="margin-top:4px;">
Apply Selected${selCount > 0 ? ` (${selCount})` : ""}
</button>
</div>` : `
<div style="font-size:11px;color:var(--wfm-text-secondary);padding:4px 0;">
${this.loading ? "Segmenting..." : "Enter a prompt and press Segment"}
</div>`}
`;
document.getElementById("ie-sam3-mode-add")?.addEventListener("click", () => {
this.mode = "add";
this._cb.renderMaskProps("sam3");
});
document.getElementById("ie-sam3-mode-erase")?.addEventListener("click", () => {
this.mode = "erase";
this._cb.renderMaskProps("sam3");
});
body.querySelectorAll(".ie-sam3-thumb").forEach(el => {
el.addEventListener("click", () => {
const idx = parseInt(el.dataset.idx);
if (this.selected.has(idx)) this.selected.delete(idx);
else this.selected.add(idx);
this._cb.renderMaskProps("sam3");
});
});
document.getElementById("ie-sam3-apply-btn")?.addEventListener("click", () => {
this.applySelectedMasks();
});
}
async runSegment() {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr || this.loading) return;
const prompt = this.prompt.trim();
if (!prompt) { showToast("Please enter a prompt", "warning"); return; }
// 推論対象: アクティブレイヤー(マスクなら下のイメージレイヤーを探す)
let imageLayer = layerMgr.activeLayer;
if (!imageLayer || imageLayer.type === "mask") {
imageLayer = layerMgr.layers.find(l => l.type !== "mask" && l.visible);
}
if (!imageLayer) { showToast("No image layer found", "error"); return; }
const NODE_ID = "wfs_sam3";
this.loading = true;
this.results = [];
this.selected = new Set();
this._cb.renderToolOptions("mask");
this._cb.renderMaskProps("sam3");
try {
const dataUrl = imageLayer.canvas.toDataURL("image/png");
await fetch("/mask_editor/store_image", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ node_id: NODE_ID, image_b64: dataUrl }),
});
const resp = await fetch("/mask_editor/sam3/segment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ node_id: NODE_ID, prompt, max_masks: this.maxMasks }),
});
const json = await resp.json();
if (json.error) throw new Error(json.error);
this.results = json.masks || [];
if (this.results.length === 0) showToast("No masks found", "warning");
else showToast(`${this.results.length} mask(s) found`, "success");
} catch (err) {
showToast("SAM3 error: " + err.message, "error");
} finally {
this.loading = false;
this._cb.renderToolOptions("mask");
this._cb.renderMaskProps("sam3");
}
}
async applySelectedMasks() {
const layerMgr = this._cb.getLayerManager();
if (!layerMgr || this.selected.size === 0) return;
const indices = [...this.selected].sort((a, b) => a - b);
const masks = indices.map(i => this.results[i]).filter(Boolean);
if (masks.length === 0) return;
let maskLayer = layerMgr.activeLayer;
if (!maskLayer || maskLayer.type !== "mask") {
const ref = layerMgr.activeLayer;
maskLayer = layerMgr.addLayer("mask", "SAM3 Mask", {
contentW: ref?.canvas.width ?? layerMgr.width,
contentH: ref?.canvas.height ?? layerMgr.height,
displayW: ref?.displayW ?? layerMgr.width,
displayH: ref?.displayH ?? layerMgr.height,
x: ref?.x ?? 0, y: ref?.y ?? 0,
});
layerMgr.setActive(maskLayer.id);
}
this._cb.saveUndo();
for (const r of masks) {
await this._applyMask(maskLayer, r.mask_b64, this.mode);
}
this._cb.updateCompositeView();
this._cb.refreshLayerList();
showToast(`SAM3: ${masks.length} mask(s) applied (${this.mode})`, "success");
}
_applyMask(maskLayer, maskB64, mode = "add") {
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
const W = maskLayer.canvas.width;
const H = maskLayer.canvas.height;
// グレースケール輝度 → アルファ白マスクに変換
const off = document.createElement("canvas");
off.width = W; off.height = H;
const mc = off.getContext("2d");
mc.drawImage(img, 0, 0, W, H);
const imgData = mc.getImageData(0, 0, W, H);
const d = imgData.data;
for (let i = 0; i < d.length; i += 4) {
const lum = d[i];
d[i] = d[i+1] = d[i+2] = 255;
d[i+3] = lum;
}
mc.putImageData(imgData, 0, 0);
// モードに合わせてマスクキャンバスに合成
maskLayer.ctx.save();
maskLayer.ctx.globalCompositeOperation = mode === "erase" ? "destination-out" : "source-over";
maskLayer.ctx.drawImage(off, 0, 0);
maskLayer.ctx.restore();
resolve();
};
img.onerror = resolve;
img.src = maskB64;
});
}
}

Some files were not shown because too many files have changed in this diff Show More