Compare commits

...
2 Commits
Author SHA1 Message Date
ketle-manandClaude Opus 5.5 20aff8236b chore(release): v0.7.6 - 意思決定モデル設定・フルバックアップのVideo Edit素材対応
- feat(backup): opt-in "Include media used by Video Edit projects" bundles the
  input-dir clips/BGM referenced by saved projects under _video_edit_media/;
  restored into input/ without overwriting existing files
- fix(backup): stream full-backup uploads to a temp file with read_chunk()
  so restores over ComfyUI's --max-upload-size (default 100 MB) no longer fail
  with "Request Entity Too Large"
- docs: help (Decision Model settings, backup), README, DEVLOG
- bump version to 0.7.6

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 12:39:09 +09:00
ketle-manandClaude Opus 5.5 dfe31374cf feat(settings): add dedicated Decision Model (Laya) settings
- New Settings section, stored under wfm_decision_settings independently of
  the AI TOOL / Tagger backends so a decision model can run alongside any
  LLM/VLM: backend (Unsloth for now), URL, model (laya / laya-multilingual /
  laya-english / laya-typed-decisions), default probability threshold
- Test button sends one yes/no question with the unsaved form values and
  shows latency + answer
- decision-client.js reads URL/model/threshold from these settings instead
  of borrowing the AI TOOL backend URL; isYes/pickChoice/pickScore default to
  the saved threshold
- i18n (en/ja/zh)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 12:05:46 +09:00
11 changed files with 363 additions and 45 deletions
+1
View File
@@ -2,6 +2,7 @@
Condensed version-by-version index of DEVLOG.md (each line: version + one-line summary of what changed and why). Full rationale, code details, and "How to apply" lessons live in the excluded DEVLOG.md itself; this index exists so graphify can extract a queryable semantic node per release without feeding the full log to the local Ollama model. Regenerate with `python tools/generate_doc_index.py devlog` whenever DEVLOG.md changes.
- **v0.7.6(2026-09-30)** — Settings: 意思決定モデル (Laya) の専用設定
- **v0.7.5(2026-09-30)** — Ming Image ワークフロー対応(GenerateUI / Gallery・Metadata / サイドパネルIタブ)
- **v0.7.4(2026-09-29)** — Video Edit: BGM/音声トラック合成(Phase 4)— 複数クリップ結合時の音声消失も解消
- **v0.7.3(2026-09-24)** — GenerateUIタブにQwen Image 2.1(TextEncodeQwenImage21)対応を追加
+30
View File
@@ -2,6 +2,36 @@
---
## v0.7.6(2026-09-30)
### Settings: 意思決定モデル (Laya) の専用設定
v0.7.5で入れた`decision-client.js`は接続先を「AI TOOLのバックエンドがUnslothならそのURL、それ以外は8888」とAI TOOL設定から借りていたため、LLM/VLMと併用するとURL変更が連動する・モデルやしきい値を選べない問題があった。Settingsタブに独立したセクションを新設し、`wfm_decision_settings`(backend / baseUrl / model / threshold)としてAI TOOL・Tagger設定とは別に保存する。
- backendは現状Unslothのみだが、同じTypeSafe互換APIを話すollaya(:11435、キー不要)等を後から足せるようフィールドとして持つ。
- モデル: `laya`(Unsloth側で選択中)/ `laya-multilingual` / `laya-english` / `laya-typed-decisions`。
- 既定しきい値(0.5〜0.99、既定0.8): `isYes`/`pickChoice`/`pickScore`でしきい値省略時に使う。
- テストボタン: 保存前のフォーム値でnoul1問を送り、応答時間と回答を表示(`testDecisionConnection()`)。
- **実機確認**: 初回はUnsloth側で Settings → API → Decision API → Serve requests がオフのため HTTP 404 `The Decision API is off`(中継・APIキーは正常に通っている)。オン後は「接続成功 ✓ 10430 ms、テスト回答 yes=0.945」(初回はモデル読み込み込み)。
### Settings: フルバックアップのVideo Edit対応
Video Editのプロジェクト(`video_edit_project/*.json`)はデータフォルダ内なので元からZIPに入っていたが、中身はComfyUIの`input/`にアップロードしたクリップ・BGMへの参照(`serverRef`)だけで、素材そのものは含まれていなかった。別環境への復元や`input/`整理後はプロジェクトを開いてもクリップが読み込めない。説明文にもVideo Editの記載がなかった。
- 3つ目のオプション「Video Editプロジェクトの素材を含める」(`include_video_media=1`): 全プロジェクトの`clips[].serverRef`と`audio.bgm.serverRef`(type=input)を`_video_edit_media/<subfolder>/<filename>`に同梱。重複・欠損は除外し、`input/`の外を指す参照(`..`等)は含めない。
- 復元時、`_video_edit_media/`はデータフォルダではなく`input/`へ戻す。同名ファイルが既にあれば上書きしない(`input/`は他のワークフローと共有のため)。結果に`media_restored`/`media_existing`を返し「Video Edit素材: ○件復元、○件は既存」と表示。エクスポート専用の`_external/`とは扱いが異なる。
- 説明文(Settings注記・ヘルプ・README)のバックアップ対象にVideo Editプロジェクトを追加。
**実機で判明した既存問題(Request Entity Too Large)**: aiohttp 3.14の`BodyPartReader.read()`はComfyUIの`--max-upload-size`(既定100MB)を強制する。workflows/wildcardオプション込みのバックアップは約125MB(`_external/`だけで118MB)で超過し復元できなかった(今回の追加以前から起こり得た)。`handle_import_full`を`read_chunk()`で1MBずつ一時ファイルへ流し込む方式に変更し、上限に関係なく復元できるようにした(ZIP全体をメモリに載せることもなくなった)。
**検証**: 一時フォルダでの単体テスト(素材収集・重複/欠損除外・パストラバーサル遮断・既存非上書き)、上限1MBのaiohttpテストサーバー(ComfyUIと同じ3.14.3)への5MBアップロード、ユーザー実機で「インポート完了: 45件 / Video Edit素材: 1件復元、3件は既存」を確認。
### ヘルプ
Settingsページの「Connections」カードに意思決定モデルの項目(helpSettings17、英日中)を追加。フルバックアップの項目(helpSettings15/16)にVideo Editプロジェクトと素材オプションを追記し、テンプレート側の英語初期表示もi18nと同期(15はVideo Plansが抜けたままになっていた)。
---
## v0.7.5(2026-09-30)
### Ming Image ワークフロー対応(GenerateUI / Gallery・Metadata / サイドパネルIタブ)
+1 -1
View File
@@ -26,7 +26,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.5-green)
![Version](https://img.shields.io/badge/version-0.7.6-green)
## Features (tab -> feature names)
+3 -3
View File
@@ -22,7 +22,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.5-green)
![Version](https://img.shields.io/badge/version-0.7.6-green)
## Screenshots
@@ -238,7 +238,7 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
- ~~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
- **Full Backup (ZIP)** (v0.5.2) — additionally covers what the JSON bundle can't represent: folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, 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. A third opt-in checkbox (v0.7.6) bundles the clips/BGM that saved Video Edit projects reference in ComfyUI's input folder (the project JSON only stores references) under `_video_edit_media/`; unlike `_external/`, these are restored into the input folder, never overwriting a file that already exists there. 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)
@@ -457,7 +457,7 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
- **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
- **Decision API client** (v0.7.5, foundation) — `static/js/decision-client.js` calls Unsloth Desktop's Decision API (`/v1/systemone`, TypeSafe-compatible Laya decision models) through the same key-attaching server proxy: `decide(state, questions)` / `decideMany`, question builders `noul`/`choice`/`score`, and `isYes`/`pickChoice`/`pickScore` helpers that threshold on `probabilities` (as Unsloth recommends) and flag low-probability answers as not confident. Requires **Decision API → Serve requests** enabled in Unsloth Desktop. Text only — Laya has no image input. No UI uses it yet
- **Decision API client** (v0.7.5, foundation) — `static/js/decision-client.js` calls Unsloth Desktop's Decision API (`/v1/systemone`, TypeSafe-compatible Laya decision models) through the same key-attaching server proxy: `decide(state, questions)` / `decideMany`, question builders `noul`/`choice`/`score`, and `isYes`/`pickChoice`/`pickScore` helpers that threshold on `probabilities` (as Unsloth recommends) and flag low-probability answers as not confident. Requires **Decision API → Serve requests** enabled in Unsloth Desktop. Text only — Laya has no image input. Connection settings live in the Settings tab's own **Decision Model (Laya)** section (v0.7.6): backend, URL, model and default probability threshold, stored under `wfm_decision_settings` independently of the AI TOOL / Tagger backends, with a Test button (one yes/no question). No feature uses it yet
- **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)
+106 -10
View File
@@ -5,13 +5,14 @@ import io
import json
import logging
import shutil
import tempfile
import zipfile
from pathlib import Path
from aiohttp import web
from ..services.settings_service import SettingsService
from ..config import DEFAULT_WORKFLOWS_DIR, DATA_DIR
from ..config import DEFAULT_WORKFLOWS_DIR, DATA_DIR, VIDEO_EDIT_PROJECT_DIR
logger = logging.getLogger(__name__)
@@ -305,7 +306,60 @@ def _add_external_dir_to_zip(zf: zipfile.ZipFile, src_dir: Path, zip_prefix: str
zf.write(path, rel)
def _build_full_backup_zip(include_workflows: bool = False, include_wildcard: bool = False) -> bytes:
# Video Edit projects (video_edit_project/*.json, inside DATA_DIR so always backed up) only
# store *references* — serverRef {filename, subfolder, type:"input"} — to clips and the BGM
# uploaded into ComfyUI's input dir, not the media itself. Backing up just the JSON means a
# restored project on another machine (or after input/ is cleaned up) opens with its clips
# missing. Opt-in (include_video_media) because the media can be large; stored under its own
# prefix so _apply_full_backup_zip can route it back into the input dir, not DATA_DIR.
_VIDEO_MEDIA_PREFIX = "_video_edit_media/"
def _comfyui_input_dir() -> Path:
import folder_paths
return Path(folder_paths.get_input_directory())
def _iter_video_edit_media_refs():
"""Yields (subfolder, filename) for every input-dir file referenced by a saved Video
Edit project (clips + BGM). Unreadable project files are skipped."""
if not VIDEO_EDIT_PROJECT_DIR.is_dir():
return
for path in sorted(VIDEO_EDIT_PROJECT_DIR.glob("*.json")):
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
continue
refs = [c.get("serverRef") for c in data.get("clips") or [] if isinstance(c, dict)]
bgm = (data.get("audio") or {}).get("bgm")
if isinstance(bgm, dict):
refs.append(bgm.get("serverRef"))
for ref in refs:
if not isinstance(ref, dict) or not ref.get("filename"):
continue
if (ref.get("type") or "input") != "input":
continue
yield (ref.get("subfolder") or "").strip("/\\"), ref["filename"]
def _add_video_edit_media_to_zip(zf: zipfile.ZipFile) -> None:
input_dir = _comfyui_input_dir().resolve()
seen = set()
for subfolder, filename in _iter_video_edit_media_refs():
src = (input_dir / subfolder / filename).resolve()
try:
rel = src.relative_to(input_dir) # a crafted project file must not reach outside input/
except ValueError:
continue
if rel in seen or not src.is_file():
continue
seen.add(rel)
zf.write(src, _VIDEO_MEDIA_PREFIX + str(rel).replace("\\", "/"))
def _build_full_backup_zip(include_workflows: bool = False, include_wildcard: bool = False,
include_video_media: 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.
@@ -327,10 +381,12 @@ def _build_full_backup_zip(include_workflows: bool = False, include_wildcard: bo
_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")
if include_video_media:
_add_video_edit_media_to_zip(zf)
return buf.getvalue()
def _apply_full_backup_zip(zip_bytes: bytes) -> dict:
def _apply_full_backup_zip(zip_source) -> 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.
@@ -339,17 +395,43 @@ def _apply_full_backup_zip(zip_bytes: bytes) -> dict:
_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": []}
stay in the ZIP for the user to copy back manually if they want them.
Entries under "_video_edit_media/" (media referenced by Video Edit projects) are restored
into ComfyUI's input dir instead, but never overwrite an existing file there — a file
with the same name is assumed to be the same upload (ComfyUI dedupes uploads by renaming),
and input/ is shared with every other workflow."""
summary = {"extracted": [], "skipped": [], "media_restored": [], "media_existing": []}
DATA_DIR.mkdir(parents=True, exist_ok=True)
base = DATA_DIR.resolve()
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
input_base = None
# zip_source: raw bytes, or a seekable file object (the upload handler spools to a temp file).
if isinstance(zip_source, (bytes, bytearray)):
zip_source = io.BytesIO(zip_source)
with zipfile.ZipFile(zip_source) as zf:
for info in zf.infolist():
if info.is_dir():
continue
if info.filename.startswith("_external/"):
summary["skipped"].append(info.filename)
continue
if info.filename.startswith(_VIDEO_MEDIA_PREFIX):
if input_base is None:
input_base = _comfyui_input_dir().resolve()
target = (input_base / info.filename[len(_VIDEO_MEDIA_PREFIX):]).resolve()
try:
target.relative_to(input_base)
except ValueError:
summary["skipped"].append(info.filename)
continue
if target.exists():
summary["media_existing"].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["media_restored"].append(info.filename)
continue
target = (base / info.filename).resolve()
try:
target.relative_to(base)
@@ -368,11 +450,15 @@ async def handle_export_full(request: web.Request) -> web.Response:
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."""
_build_full_backup_zip) — both restore-excluded, export-only, manual-copy-back.
include_video_media=1 adds the input-dir media referenced by Video Edit projects,
which *is* restored (into input/, without overwriting)."""
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)
include_video_media = request.rel_url.query.get("include_video_media") == "1"
zip_bytes = await asyncio.to_thread(
_build_full_backup_zip, include_workflows, include_wildcard, include_video_media)
return web.Response(
body=zip_bytes,
content_type="application/zip",
@@ -390,8 +476,18 @@ async def handle_import_full(request: web.Request) -> web.Response:
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)
# Stream to a temp file with read_chunk() instead of field.read(): aiohttp (3.14+)
# enforces ComfyUI's --max-upload-size (default 100 MB) inside BodyPartReader.read(),
# and a backup with the opt-in workflows/wildcard/Video Edit media easily exceeds it
# ("Request Entity Too Large"). Also avoids holding the whole ZIP in memory.
with tempfile.TemporaryFile() as tmp:
while True:
chunk = await field.read_chunk(1024 * 1024)
if not chunk:
break
await asyncio.to_thread(tmp.write, chunk)
tmp.seek(0)
summary = await asyncio.to_thread(_apply_full_backup_zip, tmp)
return web.json_response({"status": "ok", **summary})
except zipfile.BadZipFile:
return web.json_response({"error": "Not a valid ZIP file"}, status=400)
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
version = "0.7.5"
version = "0.7.6"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+1
View File
@@ -553,6 +553,7 @@ function applyI18nToHtml() {
"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-settings-17": "helpSettings17",
"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",
+60 -17
View File
@@ -7,10 +7,13 @@
* image-based judgments must first be turned into text (Tagger tags / VLM caption).
*
* Unsloth requires an API key even on localhost, so requests go through the same server-side
* proxy as the Unsloth chat backend (py/routes/unsloth_routes.py, key from .env).
* proxy as the Unsloth chat backend (py/routes/unsloth_routes.py, key from .env — the same Unsloth
* Desktop key the chat backend uses). Backend/URL/model/threshold come from the Settings tab's own
* "Decision Model" section (wfm_decision_settings), independent of the AI TOOL / Tagger backends so
* a decision model can run alongside whichever LLM/VLM those use.
* API reference: https://unsloth.ai/docs/models/decision-laya
*
* Usage:
* Usage (threshold defaults to the Settings tab value when omitted):
* import { decide, noul, choice, score, isYes, pickChoice } from "./decision-client.js";
* const answers = await decide(promptText, {
* genre: choice("Which genre fits best?", { portrait: "a person is the main subject", landscape: "scenery" }),
@@ -20,16 +23,47 @@
* const genre = pickChoice(answers.genre, 0.8); // { value, probability, confident }
*/
import { unslothProxy, readJsonStorage, getAiBackendDefaultUrl } from "./util.js";
import { unslothProxy, readJsonStorage } from "./util.js";
// Limits documented by Unsloth's Decision API.
export const DECISION_LIMITS = { maxQuestions: 64, maxChoiceOptions: 255, maxScoreLevels: 10 };
// "laya" / "default" = the model picked in Unsloth's settings. Explicit variants:
// "laya-multilingual" (default download, 100+ languages), "laya-english", "laya-typed-decisions"
// (structured data such as JSON records — e.g. workflow node summaries).
// "laya" = the model picked in Unsloth's settings. Explicit variants: "laya-multilingual" (default
// download, 100+ languages), "laya-english", "laya-typed-decisions" (structured data such as JSON
// records — e.g. workflow node summaries).
export const DECISION_MODELS = ["laya", "laya-multilingual", "laya-english", "laya-typed-decisions"];
export const DEFAULT_DECISION_MODEL = "laya";
// Only Unsloth for now; kept as a field so another TypeSafe-compatible server (e.g. ollaya on
// :11435, which needs no key) can be added later without changing the stored settings shape.
export const DECISION_BACKENDS = { unsloth: { defaultUrl: "http://localhost:8888" } };
export const DECISION_SETTINGS_KEY = "wfm_decision_settings";
const DEFAULT_SETTINGS = {
backend: "unsloth",
baseUrl: DECISION_BACKENDS.unsloth.defaultUrl,
model: DEFAULT_DECISION_MODEL,
threshold: 0.8,
};
/** Saved Decision Model settings merged over the defaults. */
export function getDecisionSettings() {
const saved = readJsonStorage(DECISION_SETTINGS_KEY);
const merged = { ...DEFAULT_SETTINGS, ...saved };
const th = Number(merged.threshold);
merged.threshold = th > 0 && th <= 1 ? th : DEFAULT_SETTINGS.threshold;
if (!DECISION_BACKENDS[merged.backend]) merged.backend = DEFAULT_SETTINGS.backend;
if (!merged.baseUrl) merged.baseUrl = DECISION_BACKENDS[merged.backend].defaultUrl;
if (!merged.model) merged.model = DEFAULT_DECISION_MODEL;
return merged;
}
export function saveDecisionSettings(patch) {
const data = { ...getDecisionSettings(), ...patch };
localStorage.setItem(DECISION_SETTINGS_KEY, JSON.stringify(data));
return data;
}
// ---- Question builders ----
/** Yes/no question — answer.noul is the probability of "yes" (0..1). */
@@ -53,11 +87,6 @@ export function score(instructions, levels) {
// ---- Request ----
/** Unsloth base URL: the AI TOOL setting when its backend is Unsloth, else the default port. */
export function getDecisionBaseUrl() {
const ai = readJsonStorage("wfm_ai_settings");
return (ai.backend === "unsloth" && ai.backendUrl) || getAiBackendDefaultUrl("unsloth");
}
function _validateQuestions(questions) {
const entries = Object.entries(questions || {});
@@ -85,12 +114,13 @@ function _validateQuestions(questions) {
*
* @param {string|object} state Text or any JSON (e.g. { prompt, tags, model }).
* @param {object} questions { key: noul(...) | choice(...) | score(...) }, max 64.
* @param {object} [opts] { model, baseUrl }
* @param {object} [opts] { model, baseUrl } — override the saved Decision Model settings.
*/
export async function decide(state, questions, opts = {}) {
_validateQuestions(questions);
const payload = { model: opts.model || DEFAULT_DECISION_MODEL, state, questions };
const data = await unslothProxy(opts.baseUrl || getDecisionBaseUrl(), "/v1/systemone", "POST", payload);
const settings = getDecisionSettings();
const payload = { model: opts.model || settings.model, state, questions };
const data = await unslothProxy(opts.baseUrl || settings.baseUrl, "/v1/systemone", "POST", payload);
if (!data || typeof data.answers !== "object") throw new Error("Decision API returned no answers");
return data.answers;
}
@@ -118,12 +148,25 @@ export async function decideMany(states, questions, opts = {}) {
return results;
}
/**
* Connection check for the Settings tab: one yes/no question, timed. The first request after
* Unsloth starts also loads the model (10-20 s), so callers should say that a slow first test is
* normal.
*/
export async function testDecisionConnection(opts = {}) {
const started = performance.now();
const answers = await decide("A cat is sitting on a sofa.", {
test: noul("Is there an animal in the text?"),
}, opts);
return { ms: Math.round(performance.now() - started), yes: answers.test?.noul };
}
// ---- Answer helpers ----
// Threshold on `probabilities` (or noul's value), not `confidence` — per Unsloth's docs, confidence
// only says how peaked the distribution is and its formula differs from Jev's.
/** True when the yes-probability of a noul answer reaches `threshold`. */
export function isYes(answer, threshold = 0.8) {
export function isYes(answer, threshold = getDecisionSettings().threshold) {
return typeof answer?.noul === "number" && answer.noul >= threshold;
}
@@ -131,7 +174,7 @@ export function isYes(answer, threshold = 0.8) {
* Most likely option of a choice answer. `confident` is false below `threshold` — callers should
* then show the value as a suggestion for the user to confirm rather than apply it automatically.
*/
export function pickChoice(answer, threshold = 0.8) {
export function pickChoice(answer, threshold = getDecisionSettings().threshold) {
const value = answer?.choice ?? null;
const probability = value != null ? (answer.probabilities?.[value] ?? 0) : 0;
return { value, probability, confident: value != null && probability >= threshold };
@@ -141,7 +184,7 @@ export function pickChoice(answer, threshold = 0.8) {
* Most likely level of a score answer: { level (index from 0), label, value (expected score,
* fractional), probability, confident }.
*/
export function pickScore(answer, threshold = 0.8) {
export function pickScore(answer, threshold = getDecisionSettings().threshold) {
const probs = answer?.probabilities || {};
let level = null, probability = 0;
for (const [k, p] of Object.entries(probs)) {
+54 -9
View File
@@ -922,8 +922,9 @@ const LANGUAGES = {
helpSettings6: "Default workflow setting",
helpSettings7: "Eagle integration URL and auto-save toggle",
helpSettings8: "Data Management: export core settings, metadata, and prompts to a JSON file, or import to restore. After importing, restart ComfyUI.",
helpSettings15: "Full Backup (ZIP): unlike the JSON export above, also includes folder-based data (AI Skills, Lab Plans, Video Plans, Style presets) and the Tagger database — everything the JSON export can't represent. Restoring overwrites existing files; restart ComfyUI afterward.",
helpSettings16: "Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them.",
helpSettings15: "Full Backup (ZIP): unlike the JSON export above, also includes folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger database — everything the JSON export can't represent. Restoring overwrites existing files; restart ComfyUI afterward.",
helpSettings16: "Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them. A third checkbox includes the clips and BGM referenced by saved Video Edit projects (projects only store references to files in ComfyUI's input folder) — unlike the other two, these are restored into the input folder, skipping any file that already exists there.",
helpSettings17: "Decision Model (Laya): its own section, independent of the AI TOOL / Tagger LLM/VLM backends so it can be used alongside them — backend (Unsloth for now), URL, model (laya / laya-multilingual / laya-english / laya-typed-decisions) and a default probability threshold (answers below it are treated as suggestions to confirm). Test sends one yes/no question with the unsaved form values; the first request loads the model (10–20 s). Requires Settings → API → Decision API → Serve requests in Unsloth Desktop (otherwise HTTP 404 \"The Decision API is off\") and UNSLOTH_API_KEY in .env",
helpSettings9: "All sections are collapsible accordion panels",
helpSettings10: "Wildcard Integration: link WFS wildcard dir to ComfyUI-Impact-Pack wildcards (directory junction on Windows / symlink on other OS); existing files migrated automatically",
helpSettings11: "Text Size: one slider (10–28 px) adjusts font size for all prompt and chat textareas at once — Generate UI positive/negative prompts, AI Assistant chat input, Preset positive/negative, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings",
@@ -1233,6 +1234,18 @@ const LANGUAGES = {
defaultWorkflowHint: "Set from the workflow detail modal. Auto-loaded when the page opens.",
clear: "Clear",
eagleIntegration: "Eagle Integration (Optional)",
decisionSection: "Decision Model (Laya)",
decisionHint: "Decision models (Laya via Unsloth Desktop's Decision API) return calibrated probabilities for typed yes/no, choice and score questions about text. Configured separately from the AI TOOL / Tagger backends so they can be used side by side. Requires Decision API → Serve requests in Unsloth Desktop; uses UNSLOTH_API_KEY from .env. Text only (no images).",
decisionBackend: "Backend",
decisionUrl: "URL",
decisionModel: "Model",
decisionModelLaya: "laya (model selected in Unsloth)",
decisionThreshold: "Default probability threshold",
decisionThresholdHint: "Answers below this probability are treated as suggestions to confirm, not applied automatically.",
decisionTesting: "Testing... (the first request loads the model and can take 10-20 s)",
decisionTestOk: "{ms} ms, test answer yes={yes}",
decisionInvalidUrl: "Invalid URL (http/https only)",
decisionInvalidThreshold: "Threshold must be between 0.5 and 0.99",
eagleUrl: "Eagle URL",
eagleAutoSave: "Auto-save generated images to Eagle",
dataManagement: "Data Management",
@@ -1245,10 +1258,12 @@ const LANGUAGES = {
importError: "Import failed",
exportFullBackup: "Full Backup (ZIP)",
importFullBackup: "Restore Full Backup (ZIP)",
fullBackupHint: "Full Backup (ZIP) additionally includes folder-based data (AI Skills, Lab Plans, Video Plans, Style presets) and the Tagger database — everything the JSON export above can't represent. Restoring overwrites existing files; restart ComfyUI afterward.",
fullBackupHint: "Full Backup (ZIP) additionally includes folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger database — everything the JSON export above can't represent. Restoring overwrites existing files; restart ComfyUI afterward.",
fullBackupFilesUnit: "files",
fullBackupIncludeWorkflows: "Include default workflows folder (user/default/workflows)",
fullBackupIncludeWildcard: "Include Impact Pack wildcard folder (if present)",
fullBackupIncludeVideoMedia: "Include media used by Video Edit projects (clips/BGM in the input folder; restored into input without overwriting)",
fullBackupMediaResult: "Video Edit media: {restored} restored, {existing} already present",
fullBackupExternalHint: "These are export-only — restoring a backup never touches them; copy the _external/ folder back manually if needed.",
saveSettings: "Save Settings",
settingsSaved: "Settings saved",
@@ -2399,8 +2414,9 @@ const LANGUAGES = {
helpSettings6: "デフォルトワークフローの設定・解除",
helpSettings7: "Eagle連携URL、自動保存の有効/無効",
helpSettings8: "データ管理:設定・メタデータ・プロンプトなど主要データをJSONにエクスポート、またはインポートして復元。インポート後はComfyUIを再起動してください。",
helpSettings15: "フルバックアップ (ZIP):上記のJSONエクスポートと異なり、フォルダ形式のデータ(AI Skills、Lab Plan、Video Plan、Styleプリセット)とTaggerデータベースも含みます。復元すると既存ファイルは上書きされます。復元後はComfyUIを再起動してください。",
helpSettings16: "フルバックアップのボタン上にある2つのチェックボックスで、デフォルトワークフローフォルダーとImpact Packのwildcardフォルダーもエクスポートに含められます。どちらもエクスポート専用で自動復元はされません。必要な場合はZIP内の_external/フォルダから手動でコピーしてください。",
helpSettings15: "フルバックアップ (ZIP):上記のJSONエクスポートと異なり、フォルダ形式のデータ(AI Skills、Lab Plan、Video Plan、Video Editプロジェクト、Styleプリセット)とTaggerデータベースも含みます。復元すると既存ファイルは上書きされます。復元後はComfyUIを再起動してください。",
helpSettings16: "フルバックアップのボタン上にある2つのチェックボックスで、デフォルトワークフローフォルダーとImpact Packのwildcardフォルダーもエクスポートに含められます。どちらもエクスポート専用で自動復元はされません。必要な場合はZIP内の_external/フォルダから手動でコピーしてください。3つ目のチェックボックスでは、保存済みVideo Editプロジェクトが参照するクリップ・BGMも含められます(プロジェクトにはComfyUIのinputフォルダ内ファイルへの参照しか保存されないため)。こちらは他の2つと異なり、復元時にinputフォルダへ戻されます(同名ファイルが既にある場合はスキップ)。",
helpSettings17: "意思決定モデル (Laya):AI TOOL/TaggerのLLM・VLMと併用できるよう、それらとは独立したセクションで設定します — バックエンド(現在はUnslothのみ)、URL、モデル(laya / laya-multilingual / laya-english / laya-typed-decisions)、既定の確率しきい値(これ未満の回答は確認用の提案として扱う)。テストボタンは保存前のフォーム値でyes/no質問を1問送ります(初回はモデル読み込みで10〜20秒)。Unsloth Desktopで Settings → API → Decision API → Serve requests の有効化(無効だとHTTP 404「The Decision API is off」)と、.envのUNSLOTH_API_KEYが必要です",
helpSettings9: "各セクションはアコーディオン式で折りたたみ可能",
helpSettings10: "Wildcard Integration:WFSのワイルドカードディレクトリをComfyUI-Impact-Packのwildcardsディレクトリへリンク(Windowsはジャンクション、他OSはシンボリックリンク)。既存ファイルは自動で移行されます",
helpSettings11: "テキストサイズ:スライダー1本(10〜28px)でプロンプト・チャット全テキストエリアのフォントサイズを一括調整 — GenerateUI ポジティブ/ネガティブプロンプト、AIアシスタントチャット入力、プリセット ポジティブ/ネガティブ、ワイルドカードプロンプト・ファイルエディタ、メタデータプロンプト全文プレビュー;即時反映・保存で確定",
@@ -2710,6 +2726,18 @@ const LANGUAGES = {
defaultWorkflowHint: "ワークフロー詳細モーダルから設定してください。ページ起動時に自動読み込みされます。",
clear: "クリア",
eagleIntegration: "Eagle 連携 (オプション)",
decisionSection: "意思決定モデル (Laya)",
decisionHint: "意思決定モデル(Unsloth DesktopのDecision API経由のLaya)は、テキストに対するyes/no・選択・段階評価の質問に確率つきで回答します。AI TOOL/TaggerのLLM・VLMと併用できるよう、それらとは別に設定します。Unsloth Desktopで「Decision API → Serve requests」の有効化が必要で、APIキーは.envのUNSLOTH_API_KEYを使います。テキスト専用(画像は不可)。",
decisionBackend: "バックエンド",
decisionUrl: "URL",
decisionModel: "モデル",
decisionModelLaya: "laya(Unsloth側で選択中のモデル)",
decisionThreshold: "既定の確率しきい値",
decisionThresholdHint: "この確率未満の回答は自動適用せず、確認用の提案として扱います。",
decisionTesting: "テスト中...(初回はモデル読み込みで10〜20秒かかります)",
decisionTestOk: "{ms} ms、テスト回答 yes={yes}",
decisionInvalidUrl: "URLが不正です(http/httpsのみ)",
decisionInvalidThreshold: "しきい値は0.5〜0.99で指定してください",
eagleUrl: "Eagle URL",
eagleAutoSave: "生成画像をEagleに自動保存",
dataManagement: "データ管理",
@@ -2722,10 +2750,12 @@ const LANGUAGES = {
importError: "インポート失敗",
exportFullBackup: "フルバックアップ (ZIP)",
importFullBackup: "フルバックアップを復元 (ZIP)",
fullBackupHint: "フルバックアップ(ZIP)は上記のJSONエクスポートでは表現できないフォルダ形式のデータ(AI Skills、Lab Plan、Video Plan、Styleプリセット)とTaggerデータベースも含みます。復元すると既存ファイルは上書きされます。復元後はComfyUIを再起動してください。",
fullBackupHint: "フルバックアップ(ZIP)は上記のJSONエクスポートでは表現できないフォルダ形式のデータ(AI Skills、Lab Plan、Video Plan、Video Editプロジェクト、Styleプリセット)とTaggerデータベースも含みます。復元すると既存ファイルは上書きされます。復元後はComfyUIを再起動してください。",
fullBackupFilesUnit: "件",
fullBackupIncludeWorkflows: "デフォルトワークフローフォルダーを含める (user/default/workflows)",
fullBackupIncludeWildcard: "Impact Packのwildcardフォルダーを含める(存在する場合)",
fullBackupIncludeVideoMedia: "Video Editプロジェクトの素材を含める(inputフォルダ内のクリップ・BGM。復元時はinputへ戻し、既存ファイルは上書きしません)",
fullBackupMediaResult: "Video Edit素材: {restored}件復元、{existing}件は既存",
fullBackupExternalHint: "これらはエクスポート専用です。復元時には一切触れません。必要な場合はZIP内の_external/フォルダから手動でコピーしてください。",
saveSettings: "設定を保存",
settingsSaved: "設定を保存しました",
@@ -3876,8 +3906,9 @@ const LANGUAGES = {
helpSettings6: "默认工作流设置/取消",
helpSettings7: "Eagle集成URL、自动保存开关",
helpSettings8: "数据管理:将设置、元数据、提示词等主要数据导出为JSON文件,或导入以恢复。导入后请重启ComfyUI。",
helpSettings15: "完整备份 (ZIP):与上方的JSON导出不同,还包含文件夹型数据(AI Skills、Lab Plan、Video Plan、Style预设)以及Tagger数据库。恢复会覆盖现有文件,恢复后请重启ComfyUI。",
helpSettings16: "完整备份按钮上方的两个复选框可将ComfyUI默认工作流文件夹和Impact Pack的wildcard文件夹一并导出。两者均仅用于导出,不会自动恢复。如需要,请从ZIP中的_external/文件夹手动复制回去。",
helpSettings15: "完整备份 (ZIP):与上方的JSON导出不同,还包含文件夹型数据(AI Skills、Lab Plan、Video Plan、Video Edit项目、Style预设)以及Tagger数据库。恢复会覆盖现有文件,恢复后请重启ComfyUI。",
helpSettings16: "完整备份按钮上方的两个复选框可将ComfyUI默认工作流文件夹和Impact Pack的wildcard文件夹一并导出。两者均仅用于导出,不会自动恢复。如需要,请从ZIP中的_external/文件夹手动复制回去。第三个复选框可包含已保存的Video Edit项目所引用的片段和BGM(项目中只保存对ComfyUI input文件夹内文件的引用)。与另外两项不同,这些文件在恢复时会放回input文件夹(已存在同名文件时跳过)。",
helpSettings17: "决策模型 (Laya):独立的设置区块,与 AI TOOL / Tagger 的 LLM/VLM 后端分开,可同时使用 — 后端(目前仅 Unsloth)、URL、模型(laya / laya-multilingual / laya-english / laya-typed-decisions)以及默认概率阈值(低于该值的回答作为待确认的建议)。测试按钮使用未保存的表单值发送一个是/否问题(首次请求需加载模型,约 10-20 秒)。需要在 Unsloth Desktop 中启用 Settings → API → Decision API → Serve requests(否则返回 HTTP 404“The Decision API is off”),并在 .env 中设置 UNSLOTH_API_KEY",
helpSettings9: "各部分可折叠展开",
helpSettings10: "Wildcard Integration:将WFS通配符目录链接到ComfyUI-Impact-Pack的wildcards目录(Windows为目录联结,其他OS为符号链接);现有文件自动迁移",
helpSettings11: "文字大小:单个滑块(10–28 px)可一次性调整所有提示词和聊天文本框的字体大小 — GenerateUI正/负向提示词、AI助手聊天输入、预设正/负向提示、通配符提示和文件编辑器、元数据提示词全文预览;即时生效并通过「保存设置」保存",
@@ -4187,6 +4218,18 @@ const LANGUAGES = {
defaultWorkflowHint: "在工作流详情弹窗中设置。页面打开时自动加载。",
clear: "清除",
eagleIntegration: "Eagle 集成 (可选)",
decisionSection: "决策模型 (Laya)",
decisionHint: "决策模型(通过 Unsloth Desktop 的 Decision API 使用 Laya)针对文本的是/否、选择和评分问题返回校准后的概率。与 AI TOOL / Tagger 后端分开配置,可同时使用。需要在 Unsloth Desktop 中启用 Decision API → Serve requests,API 密钥使用 .env 中的 UNSLOTH_API_KEY。仅支持文本(不支持图像)。",
decisionBackend: "后端",
decisionUrl: "URL",
decisionModel: "模型",
decisionModelLaya: "laya(Unsloth 中选定的模型)",
decisionThreshold: "默认概率阈值",
decisionThresholdHint: "低于此概率的回答不会自动应用,而是作为待确认的建议。",
decisionTesting: "测试中...(首次请求需加载模型,约 10-20 秒)",
decisionTestOk: "{ms} ms,测试回答 yes={yes}",
decisionInvalidUrl: "URL 无效(仅限 http/https)",
decisionInvalidThreshold: "阈值必须在 0.5 到 0.99 之间",
eagleUrl: "Eagle URL",
eagleAutoSave: "自动保存生成图片到Eagle",
dataManagement: "数据管理",
@@ -4199,10 +4242,12 @@ const LANGUAGES = {
importError: "导入失败",
exportFullBackup: "完整备份 (ZIP)",
importFullBackup: "恢复完整备份 (ZIP)",
fullBackupHint: "完整备份(ZIP)还包含上方JSON导出无法表示的文件夹型数据(AI Skills、Lab Plan、Video Plan、Style预设)以及Tagger数据库。恢复会覆盖现有文件,恢复后请重启ComfyUI。",
fullBackupHint: "完整备份(ZIP)还包含上方JSON导出无法表示的文件夹型数据(AI Skills、Lab Plan、Video Plan、Video Edit项目、Style预设)以及Tagger数据库。恢复会覆盖现有文件,恢复后请重启ComfyUI。",
fullBackupFilesUnit: "个文件",
fullBackupIncludeWorkflows: "包含默认工作流文件夹 (user/default/workflows)",
fullBackupIncludeWildcard: "包含Impact Pack的wildcard文件夹(如存在)",
fullBackupIncludeVideoMedia: "包含Video Edit项目使用的素材(input文件夹中的片段/BGM;恢复到input,不覆盖已有文件)",
fullBackupMediaResult: "Video Edit素材:已恢复 {restored} 个,{existing} 个已存在",
fullBackupExternalHint: "这些仅用于导出,恢复备份时不会处理它们。如需要,请从ZIP中的_external/文件夹手动复制回去。",
saveSettings: "保存设置",
settingsSaved: "设置已保存",
+103 -2
View File
@@ -7,6 +7,7 @@ import { comfyUI } from "./comfyui-client.js";
import { t, getLang, getSummaryLang, setLang, setSummaryLang, getLanguageOptions, getSummaryLanguageOptions } from "./i18n.js";
import { getSettings, readJsonStorage } from "./util.js";
import { DECISION_BACKENDS, DECISION_MODELS, getDecisionSettings, saveDecisionSettings, testDecisionConnection } from "./decision-client.js";
const SETTINGS_KEY = "wfm_settings";
@@ -455,6 +456,7 @@ export async function initSettingsTab() {
const uiLang = getLang();
const summaryLang = getSummaryLang();
const decisionSettings = getDecisionSettings();
container.innerHTML = `
<h2 style="font-size:18px;margin-bottom:20px;">${t("settingsTitle")}</h2>
@@ -803,6 +805,45 @@ export async function initSettingsTab() {
</div>
</details>
<!-- Decision Model (Laya) — independent of the AI TOOL / Tagger LLM/VLM backends -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("decisionSection")}</summary>
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-bottom:8px;">
${t("decisionHint")}
</small>
<div class="wfm-form-group">
<label>${t("decisionBackend")}</label>
<select class="wfm-select" id="wfm-settings-decision-backend">
${Object.keys(DECISION_BACKENDS).map(b => `<option value="${b}" ${decisionSettings.backend === b ? "selected" : ""}>${b === "unsloth" ? "Unsloth" : b}</option>`).join("")}
</select>
</div>
<div class="wfm-form-group">
<label>${t("decisionUrl")}</label>
<div style="display:flex;gap:8px;">
<input type="text" class="wfm-input" id="wfm-settings-decision-url"
value="${decisionSettings.baseUrl}"
placeholder="${DECISION_BACKENDS[decisionSettings.backend].defaultUrl}">
<button class="wfm-btn" id="wfm-settings-decision-test">${t("test")}</button>
</div>
<div id="wfm-settings-decision-status" style="font-size:12px;margin-top:4px;"></div>
</div>
<div class="wfm-form-group">
<label>${t("decisionModel")}</label>
<select class="wfm-select" id="wfm-settings-decision-model">
${DECISION_MODELS.map(m => `<option value="${m}" ${decisionSettings.model === m ? "selected" : ""}>${m === "laya" ? t("decisionModelLaya") : m}</option>`).join("")}
</select>
</div>
<div class="wfm-form-group">
<label>${t("decisionThreshold")}</label>
<input type="number" class="wfm-input" id="wfm-settings-decision-threshold"
value="${decisionSettings.threshold}" min="0.5" max="0.99" step="0.05" style="width:100px;">
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("decisionThresholdHint")}
</small>
</div>
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-settings-decision-save">${t("save")}</button>
</details>
<!-- G'MIC Integration -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">G'MIC-Qt Integration</summary>
@@ -842,6 +883,10 @@ export async function initSettingsTab() {
<input type="checkbox" id="wfm-settings-backup-include-wildcard">
${t("fullBackupIncludeWildcard")}
</label>
<label class="wfm-lab-checkbox-label" style="font-size:12px;">
<input type="checkbox" id="wfm-settings-backup-include-video-media">
${t("fullBackupIncludeVideoMedia")}
</label>
<span style="font-size:11px;color:var(--wfm-text-secondary);">${t("fullBackupExternalHint")}</span>
</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;">
@@ -1237,6 +1282,55 @@ export async function initSettingsTab() {
}
});
// --- Decision Model (Laya) ---
const readDecisionForm = () => {
const baseUrl = document.getElementById("wfm-settings-decision-url")?.value.trim() || "";
const threshold = parseFloat(document.getElementById("wfm-settings-decision-threshold")?.value);
let urlOk = false;
try { urlOk = ["http:", "https:"].includes(new URL(baseUrl).protocol); } catch {}
if (!urlOk) throw new Error(t("decisionInvalidUrl"));
if (!(threshold >= 0.5 && threshold <= 0.99)) throw new Error(t("decisionInvalidThreshold"));
return {
backend: document.getElementById("wfm-settings-decision-backend")?.value || "unsloth",
baseUrl,
model: document.getElementById("wfm-settings-decision-model")?.value || "laya",
threshold,
};
};
document.getElementById("wfm-settings-decision-backend")?.addEventListener("change", (e) => {
const urlInput = document.getElementById("wfm-settings-decision-url");
const def = DECISION_BACKENDS[e.target.value]?.defaultUrl;
if (urlInput && def) { urlInput.value = def; urlInput.placeholder = def; }
});
document.getElementById("wfm-settings-decision-save")?.addEventListener("click", () => {
try {
saveDecisionSettings(readDecisionForm());
showToast(t("settingsSaved"), "success");
} catch (err) {
showToast(err.message, "error");
}
});
// Tests the values currently in the form (saved or not), same as the Eagle test button.
document.getElementById("wfm-settings-decision-test")?.addEventListener("click", async () => {
const statusEl = document.getElementById("wfm-settings-decision-status");
let form;
try { form = readDecisionForm(); } catch (err) {
statusEl.textContent = err.message;
statusEl.style.color = "var(--wfm-danger)";
return;
}
statusEl.textContent = t("decisionTesting");
statusEl.style.color = "var(--wfm-text-secondary)";
try {
const { ms, yes } = await testDecisionConnection({ baseUrl: form.baseUrl, model: form.model });
statusEl.textContent = `${t("connectedCheck")} ${t("decisionTestOk").replace("{ms}", ms).replace("{yes}", typeof yes === "number" ? yes.toFixed(3) : "?")}`;
statusEl.style.color = "var(--wfm-success)";
} catch (err) {
statusEl.textContent = `${t("failedConnect")}: ${err.message}`;
statusEl.style.color = "var(--wfm-danger)";
}
});
// Test Eagle URL (via server proxy to avoid CORS)
document.getElementById("wfm-settings-test-eagle")?.addEventListener("click", async () => {
const urlInput = document.getElementById("wfm-settings-eagle-url");
@@ -1491,7 +1585,8 @@ export async function initSettingsTab() {
try {
const includeWorkflows = document.getElementById("wfm-settings-backup-include-workflows")?.checked ? "1" : "0";
const includeWildcard = document.getElementById("wfm-settings-backup-include-wildcard")?.checked ? "1" : "0";
const res = await fetch(`/api/wfm/settings/export-full?include_workflows=${includeWorkflows}&include_wildcard=${includeWildcard}`);
const includeVideoMedia = document.getElementById("wfm-settings-backup-include-video-media")?.checked ? "1" : "0";
const res = await fetch(`/api/wfm/settings/export-full?include_workflows=${includeWorkflows}&include_wildcard=${includeWildcard}&include_video_media=${includeVideoMedia}`);
if (!res.ok) throw new Error(await res.text());
const blob = await res.blob();
const url = URL.createObjectURL(blob);
@@ -1522,7 +1617,13 @@ export async function initSettingsTab() {
});
const result = await res.json();
if (!res.ok) throw new Error(result.error || res.statusText);
statusEl.textContent = `${t("importSuccess")}: ${result.extracted?.length ?? 0} ${t("fullBackupFilesUnit")}`;
let msg = `${t("importSuccess")}: ${result.extracted?.length ?? 0} ${t("fullBackupFilesUnit")}`;
const restoredMedia = result.media_restored?.length ?? 0;
const existingMedia = result.media_existing?.length ?? 0;
if (restoredMedia || existingMedia) {
msg += ` / ${t("fullBackupMediaResult").replace("{restored}", restoredMedia).replace("{existing}", existingMedia)}`;
}
statusEl.textContent = msg;
statusEl.style.color = "var(--wfm-success, #4caf50)";
} catch (e) {
statusEl.textContent = t("importError") + ": " + e.message;
+3 -2
View File
@@ -1671,6 +1671,7 @@
<li id="wfm-help-settings-4">ComfyUI connection URL and test</li>
<li id="wfm-help-settings-5">AI Assistant settings have moved out of this tab &mdash; the Prompt tab, Tagger tab, and AI TOOL tab each have their own &#9881; Settings button (backend, URL, model, Thinking mode, Max tokens, unload model), saved independently</li>
<li id="wfm-help-settings-7">Eagle integration URL and auto-save toggle</li>
<li id="wfm-help-settings-17">Decision Model (Laya): its own section, independent of the AI TOOL / Tagger LLM/VLM backends so it can be used alongside them — backend (Unsloth for now), URL, model (laya / laya-multilingual / laya-english / laya-typed-decisions) and a default probability threshold (answers below it are treated as suggestions to confirm). Test sends one yes/no question with the unsaved form values; the first request loads the model (10–20 s). Requires Settings → API → Decision API → Serve requests in Unsloth Desktop (otherwise HTTP 404 "The Decision API is off") and UNSLOTH_API_KEY in .env</li>
</ul>
</div>
<div class="wfm-help-card">
@@ -1693,8 +1694,8 @@
<h3 id="wfm-help-settings-card-misc-title">Data &amp; Misc</h3>
<ul>
<li id="wfm-help-settings-8">Data Management: export core settings/metadata/prompts to JSON / import to restore</li>
<li id="wfm-help-settings-15">Full Backup (ZIP): unlike the JSON export above, also includes folder-based data (AI Skills, Lab Plans, Style presets) and the Tagger database; Restore overwrites existing files — restart ComfyUI afterward</li>
<li id="wfm-help-settings-16">Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them</li>
<li id="wfm-help-settings-15">Full Backup (ZIP): unlike the JSON export above, also includes folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger database — everything the JSON export can't represent. Restoring overwrites existing files; restart ComfyUI afterward.</li>
<li id="wfm-help-settings-16">Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them. A third checkbox includes the clips and BGM referenced by saved Video Edit projects (projects only store references to files in ComfyUI's input folder) — unlike the other two, these are restored into the input folder, skipping any file that already exists there.</li>
<li id="wfm-help-settings-13">CivitAI Host: choose between civitai.com (SFW only) and civitai.red (unrestricted) — determines which site opens when clicking a model link in the Models tab CivitAI panel</li>
</ul>
</div>