Compare commits

...
509 Commits
Author SHA1 Message Date
FranckyB f3205e7959 feat: refactor slide control components for improved usability and styling 2026-11-24 19:11:09 -05:00
FranckyB 965f42e341 feat: add new SVG icons for rotation and scaling controls 2026-11-24 18:00:16 -05:00
FranckyB 3750c0dd2f feat: add PromptManagerV2 for managing prompts with LoRA stacks and trigger words
- Implemented a new prompt management system that allows users to save and manage prompts along with their associated LoRA stacks and trigger words.
- Introduced a user interface that mimics the legacy node's look, featuring a prompt bar, buttons for saving and creating new prompts, and a display for LoRA stacks.
- Added functionality to load, save, import, and delete prompts from a library, including handling of NSFW content.
- Implemented state management for edits to LoRAs and trigger words, ensuring changes are saved with prompts.
- Enhanced user experience with tooltips, context menus, and a responsive layout for managing LoRAs and trigger words.
2026-11-24 10:32:42 -05:00
FranckyBandClaude Opus 5.5 e9be2482bb chore: Sync the FB UI kit (panel height functions)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:45:04 -05:00
FranckyBandClaude Opus 5.5 2651bea9fe Add the new Prompt Manager's node logic (PromptManagerV2), not yet registered
prompt | lora_stacks | manager_data | trigger_words in, prompt | lora_stacks
| manager_data out. LoRA stacks go out as a plain LORA_STACK when one slot
has LoRAs and as a MULTI_LORA_STACK when several do. On/off and strength
edits are overrides in one state widget; panel rows go to the frontend in
a prompt-manager-v2-update message. Re-runs when the saved prompt changes.
Registered with its frontend, when the current node becomes legacy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:42:15 -05:00
FranckyBandClaude Opus 5.5 de4cb93788 Move the LoRA stack and recipe helpers into py/lora_stacks.py
Shared by the Prompt Manager nodes and the Multi LoRA nodes; the Multi LoRA
nodes drop their identical copy of the stack normalizer. No behaviour
change: Prompt Manager runs and saves compare equal to the previous
version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:39:48 -05:00
FranckyBandClaude Opus 5.5 a81d2a9ff9 Add Multi LoRA Relay; Multi LoRA Combine and Splitter become legacy
Multi LoRA Relay takes lora_stacks (a MULTI_LORA_STACK, or a LORA_STACK as
slot A) and lora_stack_a..d, appends each slot input to its slot, and
outputs the set both ways, like Recipe Relay. Same results as Combine
followed by Splitter. Changelog: an Unreleased section for this and the
recent fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:33:02 -05:00
FranckyBandClaude Opus 5.5 3ab48eddf2 Save the Prompt Manager's LoRA slots A-D in one loop
- save-prompt handled slots a-d with pasted copies, two near-identical
  LoRA normalizers and an if/elif per slot whose branches did the same;
  one loop now, and the helpers are module functions. Saved prompts and
  responses are unchanged across 432 save payloads (checked against the
  previous version).
- _has_meaningful_workflow_data loses its pre-v2 branch: its only caller
  passes v2 recipe data.
- datetime.utcnow (deprecated) replaced, same timestamp format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:06:49 -05:00
FranckyBandClaude Opus 5.5 f7b60bd151 Run the Prompt Manager's LoRA slots A-D in one loop; fix toggles reset on every run
- get_prompt handled slots a, b, c and d with four pasted copies of each
  step; one loop now builds the stacks, display, unavailable lists and
  original strengths. Outputs and frontend updates are unchanged across
  7,200 input combinations (checked against the previous version).
- With no LoRAs connected to the inputs, should_reset was sent as [] (an
  empty list), which the frontend's JavaScript reads as true: the node
  cleared and reloaded its LoRA and trigger-word toggles on every run.
  It is now false unless the prompt changed, the inputs changed with a new
  input prompt, or the input LoRAs were cleared.
- Removed the unused toggle-change tracking, the second read of the prompt
  library per run, and the fallbacks for the old data/recipe_data inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:04:40 -05:00
FranckyBandClaude Opus 5.5 5a55a69cd1 Serve the prompt library routes once, under both prefixes
- nodes/prompt_library_routes.py: get-prompts, category and prompt create,
  rename, delete, thumbnail, NSFW, import and the library file routes, each
  answered at /prompt-manager/... and /prompt-manager-advanced/..., with one
  error handler. Basic and Advanced had a copy each; the Basic node keeps
  only its save route, Advanced its save and LoRA routes.
- Prompt rename finds the prompt whatever its case on both prefixes.
- py/prompt_metadata.py: the prompt a node output, recorded in the workflow
  and API prompt save nodes embed; Basic now drops its llm_input link there
  too, as Advanced does with its prompt link.
- Removed routes nothing calls: save-category-base-prompt,
  save-category-prompt-prefix, get-prompt-data, list-checkpoints,
  resolve-loras, and log-thumbnail with the browser call that only printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:00:18 -05:00
FranckyBandClaude Opus 5.5 23cc2c63dc Load the prompt library once per read from one shared store
- py/prompt_store.py: the one place prompt_manager_data.json is loaded,
  seeded, sorted and saved, and the hidden category keys; Basic, Advanced,
  Library Manager and startup use it instead of two class copies.
- Each load parsed the file about four times (the daily backup check ran on
  every load); now once. The backup stays daily, at startup.
- An unreadable library with no readable backup loads empty instead of
  being overwritten with the default prompts.
- First run no longer reports the file as missing or corrupt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:55:10 -05:00
FranckyBandClaude Opus 5.5 1b98ba63dd Fix the Basic node's unsaved-changes warning and empty-category crash
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:55:10 -05:00
FranckyBandClaude Opus 5.5 8b3c774395 Fix prompt data lost on Basic save and on import; open only JSON files
- Prompt Manager (Basic) save kept only a few fields and wiped LoRAs C/D,
  recipe data, negative prompt and other fields saved by the full node.
- Import dropped recipe data, negative prompts and extra fields, and the
  category base prompt / prefix (plain text) never imported.
- Basic's prompt lists choked on the hidden category keys.
- load-prompts-file opens .json files only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:55:10 -05:00
FranckyBandClaude Opus 5.5 02fc7f000a Remove the unregistered Prompt Browser node and the Composer's old JSON browser
- nodes/prompt_browser.py and js/prompt_browser_node.js: the Prompt Browser
  node was no longer registered in __init__.py, so ComfyUI never offered it.
- js/prompt_composer.js: the Composer's own JSON file browser, replaced by
  the shared file browser; nothing calls it any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:55:10 -05:00
FranckyB cb09985ed6 feat: Add slideLabel function for draggable row labels and update KIT_VERSION to 12 2026-11-23 18:27:09 -05:00
FranckyBandClaude Opus 5.5 c442731e95 feat: Prompt Library Hub: Saved Prompts as one section, filtered by Type in the browser
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:29:51 -05:00
FranckyBandClaude Opus 5.5 7148c7f8c5 feat: Edit / Generate Prompt MiniMax Outpaint system prompt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:21:42 -05:00
FranckyBandClaude Opus 5.5 d954aeabfc chore: Sync the FB UI kit (group header tools)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:52:15 -05:00
FranckyBandClaude Opus 5.5 5c9dd9972d chore: Sync the FB UI kit (pad and feather icons)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:46:50 -05:00
FranckyBandClaude Opus 5.5 233216e9f2 chore: Sync the FB UI kit and file browser
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 03:16:31 -05:00
FranckyBandClaude Opus 5.5 25a9c104f9 chore: Sync the FB UI kit (core video preview suppression)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 02:05:55 -05:00
FranckyBandClaude Opus 5.5 f573f7a9df feat: Wrap Prompt Browser category tabs onto rows; kit 10
Many categories no longer run off a horizontal scroll: the tabs wrap onto
up to three rows and scroll vertically past that. With the synced kit,
the edit panel's prompt text is a dark well, and the file browser plays
videos on hover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:46:55 -05:00
FranckyBandClaude Opus 5.5 785f07b0d1 feat: Prompt Browser edit panel controls on the FB UI kit
createInput, createTextarea, createSelect, createNumberInput, the picker
triggers and createButton now make kit text fields, selects and buttons
(primary for the main actions instead of hard-coded green), so the edit
panel, its importers and pickers match the browser; their focus colouring
comes from the kit. No hard-coded colours remain in the panel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:23:53 -05:00
FranckyBandClaude Opus 5.5 1c0839ec50 fix: Edit panel confirms use the kit's danger option
Save and Update confirms are plain, the rest stay destructive; they passed colours the kit confirm does not take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:23:11 -05:00
FranckyBandClaude Opus 5.5 b3fb3087f0 feat: Prompt Browser footer, type rail and its own kit dialogs
The save and multi-select bars use kit buttons (primary for the action,
the kit's disabled state), the save name field is a kit text field, and
the type rail, its tooltip and drop markers use the kit tokens. The
browser now shows its info, confirm, new-category and rename-category
dialogs through the kit (formDialog gains a checkbox field) instead of
borrowing the old-style ones from Prompt Manager Advanced, and drops the
unused base-prompt dialog. No hard-coded colours are left in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:22:37 -05:00
FranckyBandClaude Opus 5.5 a59c9c0bc1 feat: Prompt Browser cards and list on the kit stylesheet
Grid and Icon views are one renderer (the Icon view was a ~400-line copy
at smaller sizes); cards, thumbnails, names and badges are stylesheet
classes with the kit's hover and selected states, and one promptBadges
helper builds the NSFW / C / L / R / P marks for the grid and the list.
List rows, the header, counts, the prompt tooltip and the hover preview
use the kit colours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:20:23 -05:00
FranckyBandClaude Opus 5.5 5ce100ca50 feat: Prompt Browser frame, toolbar and category tabs on the kit
The window, header, search and toolbar use the kit (kit buttons with an
"on" state for active filters and modes, Grid / Icon / List as three icon
buttons like the file browser), and the category bar's tabs are styled by
one stylesheet: selected in the kit's soft blue, NSFW with a red edge.
The scrollbar style that was added to <head> on every open is now part of
that stylesheet, and the never-shown second "+" button is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:18:09 -05:00
FranckyBandClaude Opus 5.5 f673baef1b feat: Prompt Browser dialogs, menus and progress on the FB UI kit
The four hand-built dialogs become the kit prompt and a small form dialog
(js/pm_dialogs.js; built from elements, so names are no longer injected as
HTML). The prompt, category, prompt-group and multi-selection right-click
menus use the kit menu (with separators, kit 9). Thumbnail generation goes
through one queueThumbnail helper instead of four copies, and its progress
toast is kit-styled. Requests use api.fetchApi; the unused progress
builder is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:15:53 -05:00
FranckyBandClaude Opus 5.5 fbafccf86f feat: Put Prompt Manager's modals on the FB UI kit colours
PM_UI_PALETTE now maps its names onto the kit tokens, and the Prompt
Browser and its edit panel use it instead of their own drifting copies,
so every palette-based modal shares the kit's surfaces, text and accent.
Also fixes the edit panel's selectPrompt (bulk/asset import) calling an
undefined renderCategoryTabs, and drops a console.log on every open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:11:12 -05:00
FranckyBandClaude Opus 5.5 2c87cd6501 feat: Add the FB UI kit and FBnodes' file browser
The shared kit (js/fbui/, docs/UI_RULES.md) gives Prompt Manager's nodes
the FBnodes look and its "Node color" setting (Prompt Manager >
Appearance). The Prompt Extractor's file browser is now the same file as
FBnodes' (thumbnails, list views, search, multi-select, Custom folder),
on Prompt Manager's own routes: path_browser.js names them, and the
backend gains the delete route, .hidden folders and JSON in "all".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 01:06:46 -05:00
FranckyB b1bcb515dc feat: enhance file browser dimensions and add arrow-key navigation for prompt extractor 2026-11-19 00:45:33 -05:00
FranckyB 68ab668373 Adding Extract workflow tool 2026-11-02 06:50:27 -05:00
FranckyB 43319e7330 Merge branch 'llama_test' 2026-11-01 11:06:25 -05:00
FranckyB 1db0e6a4f5 feat: enhance GPU detection and symlink handling in prompt generator 2026-11-01 10:58:33 -05:00
Francois Beaudry 54f99f67b7 Merge pull request #50 from FranckyB/llama_test
Fix for newer version of llama
2026-10-30 11:59:59 -04:00
FranckyB 7a894ccb90 fix for latest version of llama 2026-10-28 13:59:31 -04:00
FranckyB 3a182253eb Removed, now redundant Prompt Browser Node, sidebar adds same features 2026-10-28 02:01:09 -04:00
FranckyB b6b243c130 feat: update version to 3.0.0 in __init__.py and pyproject.toml 2026-10-28 01:30:34 -04:00
FranckyB fe5f1080df Add Krea layout workflow from image with prompt generation and image loading 2026-10-28 00:49:48 -04:00
FranckyB e258bd0c47 feat: Update Prompt Manager to use MANAGER_DATA instead of RECIPE_DATA
- Refactored PromptManagerAdvanced to introduce _PROMPT_MANAGER_RECIPE_KEY for better data handling.
- Changed input and output types in RecipeBuilder, WorkflowBuilder, and related classes to use MANAGER_DATA.
- Updated recipe_model_loader, recipe_relay, and recipe_renderer to accept and return MANAGER_DATA.
- Added new JavaScript file for Prompt Library Hub, enabling better management and interaction with saved prompts.
- Enhanced UI components for browsing, importing, and exporting prompts in the library hub.
2026-10-26 21:46:42 -04:00
FranckyB 8c0341771d feat: introduce Prompt Composer Manager for editing and saving compose_data with thumbnail support 2026-10-26 21:46:28 -04:00
FranckyB 433f0ef95c feat: rename Compose Manager to Composition Manager and enhance layout handling in prompt components 2026-10-26 04:02:47 -04:00
FranckyB d9b496df33 feat: add Prompt Layout Builder for MOSS-Image layouts
- Implemented a new node to create and manage MOSS-Image layouts.
- Added functionality to import and export layouts in various formats (JSON, percent, 0-1000).
- Introduced methods for cleaning and validating box data, converting between bounding boxes and layout formats.
- Integrated image background fitting and preview rendering capabilities.
- Enhanced user interface elements for layout management and visualization.
2026-10-26 03:22:36 -04:00
FranckyB 45125d570d feat: implement Node 2.0 Compatibility 2026-10-24 21:11:26 -04:00
FranckyB 3759813b39 feat: add customizable thumbnail generation steps and improve sampler defaults handling 2026-10-19 23:50:38 -04:00
FranckyB edf48eb0bf feat: enhance NSFW handling in prompt browser and save functionality 2026-10-18 18:18:35 -04:00
FranckyB c1b454eaa3 feat: Implement system prompt selector in prompt_generator.js
- Added a new system prompt selector widget to the prompt generator.
- Integrated fetching and displaying of system prompts from the API.
- Implemented navigation through prompts with arrow buttons and a thumbnail browser.
- Enhanced user experience with improved styling and event handling.

refactor: Enhance error handling and logging in prompt_generator.py

- Introduced custom error classes for better error management.
- Added logging capabilities to capture startup errors and provide actionable feedback.
- Improved model selection logic to handle missing models and provide fallbacks.

test: Add comprehensive tests for prompt generator functionality

- Created tests for the new system prompt selector in prompt_generator_selector.test.mjs.
- Implemented unit tests for model selection and error handling in test_prompt_generator_models.py.
- Ensured coverage for various scenarios including fallback mechanisms and user interactions.
2026-10-18 10:33:06 -04:00
FranckyB e735e7317a feat: update prompt editor button behavior for renaming and saving prompts 2026-10-16 22:39:02 -04:00
FranckyB 7a30c6ad89 feat: improve prompt sorting and enhance prompt entry validation in editor 2026-10-14 00:06:54 -04:00
FranckyB 9446358c56 feat: enhance prompt editor with draft metadata handling and update save button behavior 2026-10-09 02:08:46 -04:00
FranckyB 8e99c8e3c3 feat: enhance prompt management with draft metadata handling and save summary updates in the editor 2026-10-07 23:09:55 -04:00
FranckyB 603fbaaeee feat: enhance prompt management with preferred model settings and draft handling in the editor 2026-10-07 22:18:24 -04:00
FranckyB 76f19a75bc feat: add refmod core loading and expand refmod rows functionality in prompt composer 2026-10-01 00:53:20 -04:00
FranckyB f9a9731924 feat: add functionality to clear muted nodes in prompt composer and enhance context menu options 2026-09-29 22:43:11 -04:00
FranckyB 726571abfd feat: improve subject handling in prompt composer with reset functionality and tooltip updates i.e. UI Polish 2026-09-29 10:13:31 -04:00
FranckyB 51dbfcfac0 feat: enhance subject handling in prompt composer and improve text section key generation 2026-09-29 00:33:37 -04:00
FranckyB cc039ee32e feat: enhance LoRA fetching with cache control and update subject handling in composer 2026-09-28 23:40:21 -04:00
FranckyB 72eeb7e303 Similar to Prompt Composer, added the option to export only specific categories from Prompt Manager 2026-09-28 14:25:08 -04:00
FranckyB 369186bda0 UI Polish:
feat: enhance dialog functionality with optional overlay support
2026-09-28 08:17:01 -04:00
FranckyB 77d7ac30e0 feat: add tooltip functionality for prompt text in composer UI 2026-09-27 19:43:13 -04:00
FranckyB 435e7b1d4c Add advanced prompt composer workflow JSON file with image saving and management features 2026-09-27 18:36:21 -04:00
FranckyB dd07bb5aea feat: enhance prompt composer and manager with improved LoRA handling and source tracking 2026-09-27 17:06:28 -04:00
FranckyB d181b50097 fix: adjust prompt merging logic to prioritize existing prompts over incoming ones 2026-09-27 15:00:25 -04:00
FranckyB 14f2f2ffac fix: adjust dimensions and styles in Prompt Composer for improved UI consistency 2026-09-27 14:27:28 -04:00
FranckyB 78a8b16c1a feat: add input prompt and LoRA modes to Prompt Composer and advanced manager. Allowing Compose Data going thru PMA to add loras and be saved for re-use 2026-09-27 13:59:39 -04:00
FranckyB 9815e38c54 feat: enhance workflow manager with new category filtering options and UI improvements (UI Polish) 2026-09-27 11:32:22 -04:00
FranckyB d44ada12bf feat: added a small file management tool to move files without workflows
update: fixed that tab switching would loose composer manager's data
2026-09-27 10:27:18 -04:00
Francois Beaudry d7e6b32480 Merge pull request #48 from Martlet-Tech/fix/lora-stack-wrapper-height
Fix LoRA stack cards collapsing or stretching to viewport height
2026-09-27 09:58:33 -04:00
FranckyB 0c08e843e1 fix: Rename thumbnail_image to image for consistency in PromptComposerManager 2026-09-27 09:42:02 -04:00
FranckyB a47676eea8 Added new Prompt Composer Manager to save Composer Setups 2026-09-27 09:32:50 -04:00
Martlet-Tech 096335993d Fix LoRA stack cards collapsing or stretching to viewport height
The LoRA stack display widgets force-collapse their positioned wrapper
while hidden (Stack C/D) and previously stripped the manager-written
inline height on every draw while visible (Stack A/B).

The wrapper is position:fixed with height:100% (size-full), so a missing
inline height resolves against the viewport and the card stretches to
full screen height. The DOM widget manager only re-applies its style
when widgetState.pos/size change (i.e. while the view is being panned),
so while the canvas is idle the removed height left the card collapsed
or stretched to the viewport.

Pin the wrapper height to the manager's own slot height
(computedHeight - 2*margin) on every draw of visible stacks, and only
undo the forced collapse when a stack transitions from hidden to
visible (tracked per widget instead of unconditionally).
2026-09-27 16:01:57 +08:00
FranckyB 45d9979eec feat: Add PromptComposerManager for enhanced recipe_data management and thumbnail support 2026-09-27 02:56:14 -04:00
FranckyB df030d5db2 feat: Implement effective parts resolution and prompt library signature generation in Prompt Composer 2026-09-27 02:39:23 -04:00
FranckyB bc0f700c81 feat: Enhance Prompt Manager with Composer Manager integration
- Updated `prompt_manager_advanced.js` to support ComposerManager alongside existing managers.
- Modified node definitions to include ComposerManager and its specific functionalities.
- Enhanced workflow management to handle thumbnail images for ComposerManager.
- Introduced new `composer_manager.py` to manage recipe_data for Prompt Composer with thumbnail support.
- Updated `prompt_composer.py` to handle recipe_data payloads and synchronization modes.
- Improved `prompt_manager_adv.py` to accommodate recipe_data inputs and ensure compatibility with ComposerManager.
2026-09-27 02:33:36 -04:00
FranckyB 738ea302d9 Add subject kind normalization and handling in prompt composer store
- Introduced `_default_subject_kind` and `_legacy_subject_kind_for_name` functions to determine the kind of subject based on type.
- Added `_normalize_subject_kind` function to normalize subject kind values.
- Updated `_normalize_type_data` and `_serialize_type_data` to include subject kind in the type data structure.
- Enhanced `_flatten_canonical_library` to handle subject kind when flattening library data.
- Modified `_ensure_type` to set subject kind based on provided subject type and name.
- Updated type validation in `_looks_like_single_type_payload` to include subject kind.
- Adjusted `compose_save_type_settings` to properly handle subject kind during type settings saving.
2026-09-27 00:45:04 -04:00
FranckyB 56c19498c9 Refactor code structure for improved readability and maintainability 2026-09-26 23:40:13 -04:00
FranckyB 4b3c40a150 feat: improve dialog layout handling and responsiveness in thumbnail browser 2026-09-26 23:28:34 -04:00
FranckyB d3460b5f10 feat: enhance subject handling in image rendering and improve label management 2026-09-26 23:03:33 -04:00
FranckyB 87f6bc523c refactor: remove unused prompt type constants and simplify subject type handling 2026-09-26 22:35:45 -04:00
FranckyB a27f9c41ef feat: enhance category resolution and selection handling in prompt composer 2026-09-26 21:51:50 -04:00
FranckyB f0102c96bf feat: add dialog for creating new prompt groups with category selection 2026-09-26 20:08:22 -04:00
FranckyB e70b66dbb0 Refactor Prompt Composer Store for v2 migration and enhance thumbnail quality
- Updated the PromptComposerStore to convert legacy v1 composer libraries to canonical v2 on first load.
- Removed legacy type order presets and adjusted prompt loading methods to utilize canonical v2 data.
- Introduced new methods for saving type files and resolving requested type files.
- Enhanced the normalization process for category and prompt data during migration.
- Improved error handling and logging for loading type files.
- Updated the image_to_base64_thumbnail function to increase JPEG quality from 75 to 85.
2026-09-26 19:50:14 -04:00
FranckyB 64ebd5e192 Refactor code structure for improved readability and maintainability 2026-09-26 17:14:41 -04:00
FranckyB fd9eb00b20 feat: implement ordered category retrieval for composer and enhance drag scrolling 2026-09-26 13:41:14 -04:00
FranckyB 401c003471 Refactor code structure for improved readability and maintainability 2026-09-26 13:27:02 -04:00
FranckyB 2464d45e24 Move over to a V2 data type, that will be much more flexible 2026-09-26 10:41:05 -04:00
FranckyB ce3be7999f Cleanup Thumbnail Generation code
Reduce quality and generation size slightly.
To reduce the json size and speed up generation
2026-09-26 01:11:13 -04:00
FranckyB 4f772ebbba feat: add home button functionality to prompt and composer browsers 2026-09-25 22:11:38 -04:00
FranckyB 31689ecd6f feat: implement double-click selection for prompts in thumbnail browser 2026-09-25 09:51:58 -04:00
FranckyB a3c96f6d84 feat: update subject role terminology and improve image subject prefix handling 2026-09-25 09:45:40 -04:00
FranckyB 98139769c2 feat: add bulk snippet generation prompt and enhance prompt saving logic
- Introduced a new prompt for generating bulk snippets focused on a single subject category, with specific guidelines for format and content.
- Enhanced the prompt saving functionality to handle cases where prompts may be renamed or moved between categories, ensuring no conflicts arise with existing prompts.
- Implemented case-insensitive checks for existing prompts to prevent duplication and maintain consistency across categories.
2026-09-25 09:16:50 -04:00
FranckyB 2b983e2bea feat: Enhance prompt management with export and import functionalities
- Added `_safe_abspath` function to safely resolve file paths.
- Introduced `_count_prompt_totals` to count categories and prompts in the data.
- Implemented `_normalize_export_path` to ensure export paths are valid and have a .json extension.
- Created new endpoint `/prompt-manager/compose/replace-prompts` for replacing prompts with imported data.
- Added `/prompt-manager/compose/export-prompts-file` endpoint to export prompts to a specified file.
- Implemented `/prompt-manager/compose/load-prompts-file` endpoint to load prompts from a JSON file.
- Enhanced error handling and response messages for better user feedback.
2026-09-24 22:46:16 -04:00
FranckyB f68f8f1201 feat: add anima family support with default sampler settings and rendering functionality 2026-09-24 02:55:19 -04:00
FranckyB 7ef3b1d2bf Add prompt composer workflow for generating images with customizable parameters 2026-09-24 00:41:37 -04:00
FranckyB 31391c579f feat: enhance prompt part selection with default category handling and improved structure 2026-09-23 23:08:01 -04:00
FranckyB d5d5bcf7a0 feat: optimize composer UI height calculation for improved responsiveness 2026-09-23 22:17:26 -04:00
FranckyB 7ba9c464fb feat: enhance prompt renaming functionality with case-insensitive checks and improved error handling 2026-09-23 21:51:09 -04:00
FranckyB a01c6c3e0f feat: add prompt store adapters with utility functions and constants
- Introduced new file `prompt_store_adapters.js` to manage prompt-related endpoints and sources.
- Added constants for various prompt endpoints and sources.
- Implemented utility functions to handle prompt entry visibility, category retrieval, and request body construction for saving prompts based on source and endpoint.
2026-09-23 02:44:31 -04:00
FranckyB 284ae4e0b1 feat: enhance text and JSON section handling in Prompt Composer 2026-09-21 23:52:50 -04:00
FranckyB d819748089 feat: update icon assets for improved visual consistency 2026-09-21 22:23:45 -04:00
FranckyB 16ea1d1551 Refactor code structure for improved readability and maintainability 2026-09-21 22:09:55 -04:00
FranckyB a2ea2df2c5 feat: enhance prompt browser and composer functionality
- Added new prompt types: "Characteristic" and "Expression" to the prompt type choices.
- Introduced dynamic width adjustment for the prompt browser edit panel based on user input.
- Enhanced the clearPrompt function to optionally skip confirmation for discarding changes.
- Implemented functions to manage selected part indices in the prompt composer, allowing for better selection handling.
- Added merging and splitting functionality for prompt parts in the composer, improving user experience.
- Updated the prompt selection process to build parts from browser selections more efficiently.
- Modified the forwardWheelToCanvas function to capture events, ensuring better interaction with the canvas.
- Extended the prompt composer store to save additional metadata for prompts, including a new prompt type field.
2026-09-21 11:35:44 -04:00
FranckyB 95a847a9fd feat: Add mute functionality for prompt parts in Prompt Composer 2026-09-21 08:51:15 -04:00
FranckyB 25732b9086 feat: Enhance subject handling in Prompt Composer with new subject types and improved logic for non-subject prompts 2026-09-21 02:27:15 -04:00
FranckyB cfc078a960 feat: Implement subject number handling and enhance subject assignment logic in Prompt Composer 2026-09-21 01:13:05 -04:00
FranckyB ca447b6b62 feat: Add generation mode toggle for Prompt Composer and enhance Lora handling
- Introduced a new generation mode toggle in the Prompt Composer UI to switch between Image and Video LoRAs.
- Updated the prompt composition logic to handle separate Lora settings for image and video modes.
- Enhanced the Lora resolution functions to support relative path matching and improved error handling.
- Modified the prompt saving logic to accommodate new Lora fields for image and video strengths.
- Added functions to merge and manage Lora stacks more effectively.
- Implemented fetching of thumbnail results from history for improved user experience.
2026-09-21 00:47:41 -04:00
FranckyB 98d733faca feat(prompt_composer): add output format and compose position options
- Introduced output format selection (text or JSON) and compose position (before or after) in the prompt composer UI.
- Updated the prompt composer logic to handle new properties and ensure proper serialization of prompts.
- Enhanced the UI with toggle switches for output format and compose position.
- Modified the backend to support new properties in the prompt composition process.
- Improved handling of LoRA and RefMod assets in the prompt composition.
2026-09-20 23:44:00 -04:00
FranckyB 17122db4e3 feat: Add GPU support detection for llama-server and adjust command arguments accordingly 2026-09-17 20:54:07 -04:00
FranckyB 93ad34ecae fix: Improve trigger word processing to retain prompt-saved words while pruning connected-origin words 2026-09-15 08:17:46 -04:00
FranckyB af07ab7f69 fix: Enhance trigger word processing to ensure only connected words are retained and properly marked 2026-09-15 00:59:48 -04:00
FranckyB 0cf69cad19 feat: Add preference to hide downloadable built-in models in Prompt Manager 2026-09-13 23:33:25 -04:00
FranckyB 539926f486 refactor: Remove deprecated image action prompt handling and centralize system prompt management 2026-08-23 22:08:55 -04:00
FranckyB e6ab89c4ec Updated default_system_prompts and Updated examples to clarify speaker identification in MiniMax Prompts. 2026-08-23 19:28:35 -04:00
FranckyB f17cad3a5c Fixed Typos 2026-08-23 17:46:52 -04:00
FranckyB 9db6605473 fix: Revise description in README for clarity and conciseness 2026-08-23 17:42:52 -04:00
Francois Beaudry 9bd5afa256 Revise feature descriptions in README.md
Updated the README to enhance clarity on features and functionalities.
2026-08-23 17:35:01 -04:00
FranckyB b3ccc25cd7 Bump version to 2.7.2 and add system prompt storage format converter
- Updated version number in pyproject.toml to 2.7.2.
- Introduced a new module `system_prompt_converter.py` for converting legacy system prompt formats to a new category-based structure.
- The converter supports in-place JSON file conversion with optional backup creation.
- Ensured that all system prompt categories are present in the converted data.
2026-08-23 17:05:32 -04:00
Francois Beaudry 842dddbfbf Enhance README with additional resource links
Added links to installation guide, node reference, and latest update in README.
2026-08-23 11:03:52 -04:00
FranckyB 68f47d788d feat: Update README and feature reference for improved clarity and navigation; enhance prompt browser functionality and UI styling 2026-08-23 11:00:22 -04:00
FranckyB b449821dfc - Removed legacy migration logic from prompt_manager.js and moved it to a new prompt_generator.js file for better organization.
- Updated the PromptGenerator class to handle prompt input updates and communicate with the frontend.
- Enhanced the UI behavior of the PromptGenOptions and PromptGenerator nodes to ensure proper widget visibility and state management.
2026-08-23 00:36:09 -04:00
FranckyB 36a2c484f7 feat: Update LoRA blacklist to include new keywords for minimax and distilled LoRAs 2026-08-20 22:52:40 -04:00
FranckyB 8a73f906b6 chore: Bump version to 2.7.1 and update README with latest features 2026-08-18 12:54:53 -04:00
FranckyB e5421431c0 feat: Update prompt handling to echo input prompt in UI on execution 2026-08-17 02:04:43 -04:00
FranckyB 645f58da8e feat: Enhance prompt input handling and model management in Prompt Generator 2026-08-17 01:25:16 -04:00
FranckyB 80389a6621 Add comprehensive video prompt writing guides for MiniMax generation
- Introduced VIDEO_PROMPT_WRITING_GUIDE_REF2VA.md for full-reference video prompt structure, detailing core behaviors, output sections, and example formats.
- Created VIDEO_PROMPT_WRITING_GUIDE_T2VA.md for task-oriented video prompt writing, emphasizing user text expansion and output structure without reference labels.
2026-08-16 19:32:54 -04:00
FranckyB bf0a871563 fix: Guard against temporal dead zone for getThumbnailRenderState in thumbnail rendering 2026-08-16 13:04:24 -04:00
FranckyB 8ea8f2866d feat: Add video input support for prompt extraction and update UI behavior 2026-08-15 11:46:15 -04:00
FranckyB 29f4073247 feat: Update prompt text widget behavior to be read-only when using external inputs 2026-08-14 22:51:14 -04:00
FranckyB 11f1f6b798 feat: Update version to 2.7.0 and enhance README with Prompt Browser details 2026-08-12 09:09:07 -04:00
FranckyB 1f09925d4f Add default system prompts for image and video generation models 2026-08-12 08:54:19 -04:00
FranckyB d14422deb4 feat: Enhance prompt management and system prompt categories
- Updated `saveComposerPrompt` function to accept an optional `promptCategory` parameter for better categorization.
- Modified `buildComposerButtonBar` to handle the new payload structure for saving prompts.
- Introduced new constants for system prompt categories and legacy mode mappings in `prompt_generator.py`.
- Implemented functions to read and merge basic system prompts, ensuring essential prompts are always available.
- Added API endpoint to update the category of existing prompts without altering their text.
- Refactored prompt loading logic to accommodate new structure and ensure backward compatibility.
- Created `basic_system_prompts.json` to store default prompts for various media types (Image, Video, Audio).
2026-08-09 00:26:11 -04:00
FranckyB 39426d6a2e Add .gitattributes, normalize line endings to LF 2026-08-08 08:09:05 -04:00
FranckyB a4a5df9e53 feat: Add bulk prompt builder and tools section in prompt editor 2026-08-04 23:45:39 -04:00
FranckyB 2299db05ae fix: Ensure self-contained prompts by removing dangling prompt references in metadata 2026-08-04 23:06:09 -04:00
FranckyB aa8c355461 feat: Enhance prompt editing with unsaved changes confirmation and UI improvements 2026-08-04 22:16:55 -04:00
FranckyB 0133804a7b feat: Implement centralized backup manager for prompt data files with rotating backups 2026-08-04 02:33:49 -04:00
Francois Beaudry a486506317 Merge pull request #44 from sophosympatheia/feat/gpu-device-selection
feat: Add GPU device selection for llama.cpp server (multi-GPU support)
2026-08-04 02:04:04 -04:00
Francois Beaudry 8a84224dea Merge pull request #45 from sophosympatheia/fix/recursive-model-subfolder-discovery
Fix/recursive model subfolder discovery
2026-08-04 02:01:39 -04:00
Francois Beaudry 746cbdb9e1 Merge pull request #43 from sophosympatheia/fix/llama-port-preference
Fix llama-server port always using hardcoded default instead of saved…
2026-08-04 01:59:43 -04:00
sophosympatheia 4459c270c2 Fix mmproj discovery to recurse into subfolders and match same-folder files
get_mmproj_path()'s heuristic search used os.listdir(models_dir), so mmproj
files placed in a model's own subfolder were never found. It also required
>= 4 shared non-quant keywords between model and mmproj filenames, which
fails for generically-named files like 'mmproj-BF16.gguf' that carry no
identifying keywords at all.

Add a same-folder fallback: if the model's directory contains exactly one
mmproj file, use it without requiring any naming convention. Keep the
keyword heuristic as a fallback for mmproj files that live elsewhere, and
make that search recurse into subfolders too.
2026-08-03 21:21:43 -07:00
sophosympatheia fd707a2a05 Fix local model discovery to recurse into subfolders
get_local_models() used a non-recursive glob.glob(models_dir/*.gguf), so
.gguf files placed in subfolders of a configured models directory (e.g.
~/models/Gemma-4-31B-it/gemma-4-31B-it-qat-UD-Q4_K_XL.gguf) were never
listed as available models.

Walk the directory tree with os.walk instead and return each match as a
path relative to its models_dir. This matches the relative-path
convention ComfyUI's own folder_paths.recursive_search uses, so
is_model_local() and get_model_path() (which already join models_dir
with the returned name) work unchanged for subfolder entries.
2026-08-03 21:15:08 -07:00
sophosympatheia 39ea2125d2 Fix GPU pinning for vision models: use CUDA_VISIBLE_DEVICES instead of --device
llama.cpp's mmproj/clip multimodal loader has a known upstream bug
(ggml-org/llama.cpp#15804) where it ignores --main-gpu/--device entirely and
always loads the projector file onto GPU 0, even with 'split-mode none'.
This meant vision mode still OOM'd the wrong GPU regardless of gpu_device.

Restrict GPU visibility via the CUDA_VISIBLE_DEVICES environment variable on
the llama-server subprocess instead. Since this operates at the CUDA driver
level before the process starts, no other GPU is visible to any code path
in llama.cpp -- including the buggy mmproj loader -- so it can't fall back
to the wrong device.
2026-08-03 11:51:49 -07:00
sophosympatheia 8720a8afc8 Fix GPU pinning: use --device instead of --main-gpu
--main-gpu only designates which GPU handles KV cache/intermediate results
while the default split-mode (layer) still spreads model layers across every
visible GPU. This meant setting gpu_device to '1' still loaded weights onto
GPU 0 as well, causing OOM crashes when the diffusion model later needed
that VRAM.

--device restricts offloading to the specified device only, fully pinning
the model to one GPU as intended.
2026-08-03 11:45:24 -07:00
sophosympatheia 4082485800 Fix llama-server port always using hardcoded default instead of saved setting
SERVER_PORT was a class attribute computed once at module import time, before
the frontend has a chance to push the user's saved custom_llama_port setting
to the backend via /prompt-manager/save-preference. As a result the server
always launched on port 8080 regardless of what was configured in settings.

Replace the frozen class attribute with get_server_port(), a static method
that reads the preferences cache fresh on every call.
2026-08-03 10:24:47 -07:00
sophosympatheia 5411a0bf88 feat: Add GPU device selection for llama.cpp server (multi-GPU support)
Add optional gpu_device input to Prompt Generator Options node, allowing users
to specify which GPU loads the LLM weights via llama.cpp's --main-gpu flag.

Use case: with two GPUs, load your diffusion model on cuda:0 and the LLM
on cuda:1 by setting gpu_device to "1".

Changes:
- py/model_manager.py: Add llama_gpu_device preference (global default)
- nodes/prompt_generator_options.py: Add gpu_device optional input string field
- nodes/prompt_generator.py: Pass --main-gpu flag when gpu_device is specified,
  track device in restart condition so server reloads when GPU selection changes
2026-08-03 10:24:47 -07:00
FranckyB 50467d1cc1 feat: Ensure synchronous DOM widget creation for prompt composer during setup and workflow restore 2026-08-03 04:27:41 -04:00
FranckyB d9d49bc368 Seperated System Prompts as standalone prompt_generator.json, since we now have prompt browser to view and edit it. 2026-08-03 03:12:09 -04:00
FranckyB 69da89d7e3 feat: Adjust alignment and overflow behavior in thumbnail browser for improved layout 2026-08-03 01:34:17 -04:00
FranckyB a2c258b654 feat: Refactor category selector into a static controls bar with horizontal scrolling for improved usability 2026-08-03 01:30:14 -04:00
FranckyB d9ae13e4a9 feat: Add category type filter dropdown and enhance prompt type choices 2026-08-03 00:37:22 -04:00
FranckyB 15bca6eaee feat: Implement horizontal scroll for category selector and enhance visibility of selected category 2026-08-03 00:26:55 -04:00
FranckyB c1c6472b94 feat: Update thumbnail browser layout and improve edit panel responsiveness 2026-08-03 00:13:19 -04:00
FranckyB c39c3fd568 feat: Initialize thumbnail area with placeholder and update empty state display in composer preview 2026-08-02 23:17:24 -04:00
FranckyB c07c785192 feat: Adjust minimum grid width calculation and update padding in prompt browser edit panel 2026-08-02 23:05:54 -04:00
FranckyB c6ed164196 feat: Enhance thumbnail browser view mode toggling and auto-save prompt type settings 2026-08-02 22:47:56 -04:00
FranckyB ae98dc306f feat: Move delete category option to the end of the menu for better usability 2026-08-02 22:21:35 -04:00
FranckyB 84a8c5f688 feat: Simplify edit panel behavior in multi-select mode for thumbnail browser 2026-08-02 22:05:55 -04:00
FranckyB bcfe782bfb feat: Implement multi-select functionality in thumbnail browser with initial state option 2026-08-02 21:49:58 -04:00
FranckyB 17f1245eaa feat: Adjust edit panel width and layout for compact mode in prompt browser 2026-08-02 20:57:33 -04:00
FranckyB f7a87346a1 feat: Enhance compact browser mode detection based on viewport size 2026-08-02 20:42:08 -04:00
FranckyB 0f4402f9e0 feat: Adjust thumbnail browser layout and footer hints for improved usability 2026-08-02 20:32:58 -04:00
FranckyB 1b3001cbad feat: Update default value for thumbnail hover preview to false 2026-08-02 20:05:09 -04:00
FranckyB deb4bbb983 feat: Add placeholder thumbnail functionality in composer preview 2026-08-02 15:20:06 -04:00
FranckyB cfd06a0ce1 feat: Enhance restorePromptBrowserSource to conditionally persist source values 2026-08-02 15:15:13 -04:00
FranckyB 39dceb9596 feat: Refactor composer root layout to use flexbox for improved responsiveness and height management 2026-08-02 15:11:24 -04:00
FranckyB 6c27225d92 feat: Add drag-and-drop resizing functionality to composer preview 2026-08-02 14:07:41 -04:00
FranckyB 8e58f3fe06 feat: Implement prompt source management with normalization and persistence 2026-08-02 13:55:11 -04:00
FranckyB 23c5721318 feat: Enhance prompt selection handling and clear functionality in prompt browser 2026-08-02 13:40:36 -04:00
FranckyB 34a6c1a8f3 Add Prompt Mixer Selector and Store for managing prompt fragments
- Implemented PromptMixerSelector to select and format prompt fragments with adjustable strength.
- Created PromptMixerStore for isolated JSON storage of prompt fragments, including loading, saving, and managing categories and prompts.
- Added API endpoints for retrieving, saving, renaming, and deleting prompts and categories.
- Introduced functionality for handling NSFW flags and thumbnail management for prompts.
2026-08-02 13:03:39 -04:00
FranckyB 46e499efb8 fix: Simplify multi-select logic and enhance category settings confirmation in prompt browser 2026-08-02 03:59:23 -04:00
FranckyB add4d1f22c feat: Enhance thumbnail browser interaction and improve UI padding 2026-08-02 03:46:12 -04:00
FranckyB 52b72c9277 Refactor prompt management system
- Removed the ExpressionSelector class and its associated methods from expression_selector.py, consolidating expression handling into a new test file.
- Updated prompt_composer.py to introduce new prompt type handling, including a new function to resolve prompt types.
- Modified prompt_composer_manager.py to accommodate changes in hidden category entry keys.
- Adjusted prompt_composer_store.py to replace legacy prompt prefix handling with prompt type management.
- Added a new JavaScript file (prompt_browser_edit.js) for editing prompt categories, including UI elements for prompt type and base prompt settings.
- Introduced a new test file (expression_selector.py) to ensure the functionality of the expression selection process.
2026-08-02 01:44:13 -04:00
FranckyB 4e8e47f8f4 Refactor Prompt Mixer to Prompt Composer
- Renamed `PromptMixerStore` to `PromptComposerStore` in `prompt_composer_store.py` for consistency.
- Updated method names and comments to reflect the new naming convention.
- Added new JavaScript files: `prompt_composer_common.js` and `prompt_composer_manager.js` to handle prompt composer functionality.
- Implemented functions for loading, saving, deleting, and managing prompts in the composer.
- Enhanced UI components for prompt selection and management, including buttons for saving, creating, and deleting prompts.
- Integrated thumbnail preview functionality for prompts.
- Added JSON import/export capabilities for prompt data.
2026-08-01 21:56:34 -04:00
FranckyB 2af07072fd Updated base composer prompt 2026-08-01 16:19:37 -04:00
FranckyB 229d7291ee feat: Implement Prompt Composer for building prompts from multiple parts
- Added a new PromptComposer node to compose prompt fragments from multiple selectable parts.
- Each part can store category, selected prompt names (multi-select), and strength.
- Introduced functions to normalize strength, format fragments, and resolve prompt prefixes.
- Enhanced prompt mixing functionality by allowing dynamic prompt selection based on user-defined parts.
- Added API endpoints for saving base prompts and prompt prefixes for categories.
- Updated UI components to support the new prompt composer features, including thumbnail zoom and context menus.
- Refactored existing code to improve handling of hidden category entries and prompt selection logic.
2026-08-01 16:00:04 -04:00
FranckyB 99c05514da Refactor Prompt Mixer to Prompt Composer
- Updated `prompt_mixer_manager.js` to handle both PromptMixerManager and PromptComposerManager.
- Changed export filename from `prompt_mixer_data.json` to `prompt_composer_data.json`.
- Modified `prompt_mixer_selector.js` to include a preview box in the mixer preview.
- Removed `prompt_mixer_manager.py` as it is no longer needed.
- Renamed `prompt_mixer_store.py` to `prompt_composer_store.py` and updated its functionality to support the new Prompt Composer structure.
- Added new `default_composer_prompts.json` for default prompts.
- Created `prompt_composer_manager.py` to manage Prompt Composer fragments.
- Updated server routes to handle Prompt Composer requests.
2026-08-01 12:51:49 -04:00
FranckyB e9a28545b1 fix: Adjust thumbnail browser layout and column widths for improved display 2026-08-01 11:58:15 -04:00
FranckyB e4c39ce0f6 Refactor code structure for improved readability and maintainability 2026-08-01 11:37:05 -04:00
FranckyB 16405ceb17 Add Prompt Mixer functionality with isolated storage and selection capabilities
- Implemented PromptMixerManager for saving, loading, and editing prompt fragments.
- Created PromptMixerSelector for selecting prompt fragments with support for strength and random selection.
- Developed PromptMixerStore for managing isolated JSON storage of prompt fragments, including backup and restore functionality.
- Added API endpoints for managing prompt categories and fragments, including save, delete, rename, and toggle NSFW status.
2026-08-01 02:16:12 -04:00
FranckyB b59f1c1bbe fix: Improve VRAM flush logging and handling for CLIP/text encoder 2026-07-31 01:15:38 -04:00
FranckyB ac358436fe feat: - Added support for direct Clip (text encoders in Prompt Generator)
- Update README and documentation for improved clarity on prompt generation options and workflows; bump version to 2.6.0
2026-07-31 00:53:50 -04:00
FranckyB b560c4a17a Fixed bad prompt 2026-07-28 02:26:41 -04:00
FranckyB bc76189941 Added KREA2 workflow JSON
Added Strength Slider to Expression Selector
2026-07-28 00:00:48 -04:00
FranckyB 52e9626059 feat: Add stack count configuration to MultiLoraStackerLM for flexible LoRA stack management 2026-07-26 20:48:14 -04:00
FranckyB 0f50056ab1 fix: Ensure proper handling of hidden LoRA stacks to prevent UI interaction issues 2026-07-26 20:17:44 -04:00
FranckyB 17f577ec8d feat: Enhance expression node handling with graph validation and improved hover detection 2026-07-26 19:27:45 -04:00
FranckyB 819b82af35 feat: Implement arrow navigation for expression selection and improve hover handling 2026-07-26 18:55:46 -04:00
FranckyB deb22acfaa fix: Update default value for static seed in expression thumbnail generation 2026-07-26 15:04:43 -04:00
FranckyB c4faf12236 fix: Remove unused parameters from showThumbnailBrowser function 2026-07-26 13:25:05 -04:00
FranckyB 3cd52a032b fix: Update MIN_NODE_WIDTH to improve layout consistency 2026-07-26 03:38:30 -04:00
FranckyB 0b72ad0c65 chore: Bump version to 2.5.5 in __init__.py and pyproject.toml 2026-07-26 00:02:35 -04:00
FranckyB b60d9b006e Improved Expresion names 2026-07-25 23:50:32 -04:00
FranckyB fef2545c8e Implement code changes to enhance functionality and improve performance 2026-07-25 19:04:10 -04:00
FranckyB 4416ffee23 Fixed Expression name 2026-07-25 17:48:07 -04:00
FranckyB dac1a9a705 feat: Add drag-and-drop functionality for setting prompt thumbnails 2026-07-25 17:36:27 -04:00
FranckyB e1a3e70442 Tweak to expression and node size as well as added thumbnails to default prompts 2026-07-25 17:12:30 -04:00
FranckyB 6a6ed5afd5 feat: Add functionality to merge default expressions into user prompts
- Implemented `hasExpressionCategory` to check for existing Expressions category in prompts.
- Created `ensureExpressionsCategory` to fetch and merge default expressions if the category is missing.
- Updated `loadPrompts` calls to ensure default expressions are merged before retrieving expression names.
- Added a new endpoint `/prompt-manager/merge-default-expressions` to handle merging of default expressions from `expressions.json`.
- Enhanced error handling and logging for merging process.
2026-07-25 15:24:20 -04:00
FranckyB db528293aa Implement code changes to enhance functionality and improve performance 2026-07-25 14:55:23 -04:00
FranckyB 799feac2e9 feat: update compact prompt browser layout for improved usability 2026-07-25 11:32:51 -04:00
FranckyB 0567a5e1fe feat: add compact prompt browser option for enhanced UI flexibility 2026-07-25 11:14:32 -04:00
FranckyB e00f57a5d0 feat: add Expression Selector extension for managing expressions in prompts
- Implemented a new JavaScript module for the Expression Selector UI, allowing users to select and preview expressions stored in the Prompt Manager.
- Created a corresponding Python node to handle expression selection and substitution in prompts, including gender adaptations for pronouns.
- Integrated the expression selection functionality into the existing prompt management system, ensuring compatibility with current workflows.
- Added UI components for expression selection and preview, enhancing user experience and interaction.
2026-07-25 10:10:58 -04:00
FranckyB 2aea1845e6 feat: Refine active trigger word retrieval logic in PromptManagerAdvanced 2026-07-24 13:22:37 -04:00
FranckyB 6697b32e37 feat: Implement prompt input mask shim for PromptManager and PromptManagerAdvanced 2026-07-21 23:49:29 -04:00
FranckyB dda225708b feat: Improve workflow extraction validation and documentation in extract_video_workflow.py 2026-07-19 04:22:55 -04:00
FranckyB adee96644a feat: Enhance prompt management with trigger word parsing and resolution for llama-server path on linux 2026-07-18 23:52:02 -04:00
FranckyB d64b13a54b feat: Add support for mode-specific JSON system prompts and enhance prompt instructions for audio, image, and video 2026-07-17 08:39:05 -04:00
FranckyB 67f12480ae feat: Enhance Prompt Manager with Multi-Slot LoRA Support
- Added support for multiple LoRA slots (C and D) in PromptManagerAdvanced and PromptManager.
- Implemented functions to normalize and combine multi-LORA inputs.
- Updated metadata handling to persist resolved prompts for both workflow and API.
- Enhanced recipe data building to include additional LoRA configurations.
- Refactored existing methods to accommodate new LoRA structures and ensure backward compatibility.
2026-07-17 08:38:41 -04:00
FranckyB 65504b8263 feat: Rename PromptGeneratorKillRelay to PromptGeneratorKillSwitch and remove unused mappings 2026-07-14 00:27:42 -04:00
FranckyB b7862153e5 feat: Implement system prompt override functionality in PromptGenerator instead, for simpler workflows. 2026-07-11 11:36:17 -04:00
FranckyB 922ff007f4 feat: Revise README for clarity and detail on prompt management and recipe tools 2026-07-11 00:21:56 -04:00
FranckyB 5ce3408cfc feat: Enhance media path handling and preview functionality
- Introduced new utility functions in `path_browser.js` for media path classification and URL generation.
- Updated `prompt_extractor.js` to utilize new path handling functions for building preview URLs and resolving media sources.
- Improved image and video preview modals to use the new URL structure.
- Added support for browsing files from custom paths, including enhanced metadata extraction for media files.
- Refactored file listing and directory browsing in `prompt_extractor.py` to support new media types and improved error handling.
- Updated version to 2.5.3 in `pyproject.toml`.
2026-07-07 08:35:16 -04:00
FranckyB b7679d0e5a fix: Update MultiLoraStackerLM and MultiLoraStacker to improve module loading and fast preview functionality 2026-07-04 16:25:48 -04:00
FranckyB ea88616f81 feat: Add LoraStackCombine class to merge multiple LORA_STACK inputs into a single output 2026-07-04 08:56:52 -04:00
FranckyB 7b0e59a502 feat: Add MultiLoraSplitter class to split MULTI_LORA_STACK payload into A/B/C/D outputs 2026-07-03 13:39:49 -04:00
FranckyB 40bfc8e3b7 fix: Adjust margin-top in ensureStyles function for MultiLoraStackerLM to improve layout 2026-07-03 11:14:24 -04:00
FranckyB 782aa7c63b feat: Add PromptGeneratorKillRelay node to manage server shutdown and model unloading, fixed issue with multi lora stack and added that it can be used as a standard Lora Stacker, with sections... 2026-07-03 09:30:50 -04:00
FranckyB 7295cf2e50 feat: Add system prompts for cinematic enhancement and realism, with options for prompt overrides in Prompt Generator Option node. Improved Memory Management for Generator. 2026-06-07 10:38:18 -04:00
FranckyB bb68fd890f feat: Add clear_vram_on_run option to PromptGenerator for improved VRAM management 2026-06-01 04:19:30 -04:00
FranckyB 070b9c2dfe refactor: Remove recipe_data output from PromptExtractor and enhance legacy metadata parsing functions 2026-05-31 02:08:05 -04:00
FranckyB 3cd6c3cf9b fix: Remove Recipe Output from Prompt Extractor, now prompt only 2026-05-28 00:30:46 -04:00
FranckyB d77b89c388 feat: Enhance thumbnail rendering with improved loading UI and LoRA fetching logic 2026-05-24 20:37:46 -04:00
FranckyB e9bfdceee2 feat: Add support for LoRA selection in thumbnail rendering and enhance recipe data normalization 2026-05-24 19:41:15 -04:00
FranckyB b6156bc59a refactor: Update model selection priority logic in PromptGenerator for improved clarity and functionality 2026-05-20 00:56:28 -04:00
FranckyB c765112c38 feat: Implement legacy prompt generation options migration and enhance context size retrieval for GPU compatibility 2026-05-18 20:24:46 -04:00
THE_BEAST\me 9f185c5806 Merge branch 'main' of https://github.com/FranckyB/ComfyUI-Prompt-Manager 2026-05-17 04:41:00 -04:00
THE_BEAST\me c8fb3dada0 feat: Enhance prompt generation options with system prompt mode and update audio prompt description 2026-05-17 04:39:13 -04:00
THE_BEAST\me 98c7d94290 refactor: Consolidate model preference handling by renaming and unifying preferred model settings 2026-05-17 03:48:22 -04:00
Francois Beaudry 7bb27c5c40 Merge pull request #39 from FranckyB/dev
Add video workflow extraction script and update version to 2.5.2
2026-05-14 21:21:58 -04:00
THE_BEAST\me 22facf075b feat: Bump version to 2.5.2 and update changelog with new features 2026-05-14 21:18:35 -04:00
THE_BEAST\me ac7bb560a5 feat: Add video workflow extraction script and batch file for JSON output 2026-05-14 10:02:22 -04:00
Francois Beaudry 6df8cbef30 Merge pull request #38 from FranckyB/dev
Dev
2026-05-01 20:26:52 -04:00
THE_BEAST\meandCopilot a2d8687993 Refactor code structure for improved readability and maintainability
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 20:25:03 -04:00
THE_BEAST\meandCopilot 6931d4811f refactor: Rename WorkflowBuilderMulti to RecipeBuilder for consistency and clarity
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 18:42:30 -04:00
THE_BEAST\meandCopilot 8b3e7adcf4 feat: Enhance prompt payload validation in WorkflowBuilder for improved data handling
Co-authored-by: Copilot <copilot@github.com>
2026-05-01 17:57:15 -04:00
THE_BEAST\me cc2a66c74a feat: Update version to 2.5.1 and enhance recipe relay with improved handling of EXTRA_1 and EXTRA_2 fields 2026-05-01 17:33:25 -04:00
THE_BEAST\me c3f7c85b9e refactor: Rename EXTRA key to EXTRA_1 and EXTRA_2 for clarity in recipe data handling 2026-04-30 07:35:31 -04:00
THE_BEAST\me 01862135da fix: Update changelog to clarify Recipe Builder is now Multi-model Only 2026-04-29 11:00:23 -04:00
THE_BEAST\meandCopilot 46cbe4266b feat: Update README and changelog for v2.5.0, highlighting Multi Model support and new Multi Lora Stack node
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 10:31:03 -04:00
THE_BEAST\me ecf7472ff5 feat: Update version to 2.5.0 and add MultiLoraCombine class for enhanced LoRA stack management 2026-04-29 10:11:08 -04:00
THE_BEAST\meandCopilot 6b3cbb3268 feat: Sync recipe_data model resolutions with Builder UI on execution
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 01:42:42 -04:00
THE_BEAST\meandCopilot 9771f7e3fb feat: Enhance LoRA path resolution and normalization in recipe handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-29 00:10:34 -04:00
THE_BEAST\meandCopilot 90e4c9e24d feat: Add browser content filter functionality to enhance prompt and recipe visibility options
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:51:25 -04:00
THE_BEAST\meandCopilot c96badf1b9 feat: Implement prompt preset payload validation and enhance recipe data building from prompts
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:33:02 -04:00
THE_BEAST\meandCopilot b8286a5e51 feat: Capture original strengths for model slots from slot profiles to enhance reset functionality
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 21:05:54 -04:00
THE_BEAST\meandCopilot d030a3b717 feat: Enhance Recipe Builder with v2 hydration and contract tests
- Implemented _hydrate_v2_recipe_models to ensure v2 recipe_data contains dict blocks for model_a to model_d.
- Updated WorkflowBuilder to cache previous recipe_data for change detection and hydration.
- Added comprehensive contract tests for Recipe Builder's execute behavior, covering model slot preservation, prompt overrides, and LoRA state management.
- Introduced JS contract tests for UI lock and persistence logic in recipe_builder.js.

Co-authored-by: Copilot <copilot@github.com>
2026-04-28 16:50:02 -04:00
THE_BEAST\meandCopilot 4bad6fae7e feat: Improve prompt handling by adding locking mechanism for positive and negative prompts; enhance UI state management for effective values
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 09:55:02 -04:00
THE_BEAST\meandCopilot 9a91d30530 feat: Normalize multi-lora stack handling to ensure consistent list returns and improve input processing
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 09:26:08 -04:00
THE_BEAST\meandCopilot c93d4b013c feat: Enhance LoRA path resolution and availability tracking in prompt extraction
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 08:47:09 -04:00
THE_BEAST\meandCopilot a3b0e7eaff feat: Enhance multi-lora stack handling by adding source tracking for candidates and refining empty list treatment
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 02:12:09 -04:00
THE_BEAST\meandCopilot cfb85445fa feat: Refactor multi-prompt handling and replace RecipeBuilderPromptBundle with RecipeBuilderMultiPrompts; update MultiLoraStackerLM to new structure and improve input normalization
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:55:30 -04:00
THE_BEAST\meandCopilot 9e875c7a99 feat: Update styling for active slots in MultiLoraStackerLM with new accent colors and box-shadow adjustments
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:07:42 -04:00
THE_BEAST\meandCopilot 39b688403d feat: Replace RecipeBuilderDataBundle with RecipeBuilderPromptBundle and update references for multi-prompt integration
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 00:03:06 -04:00
THE_BEAST\meandCopilot 2359960a54 feat: Refactor MultiLoraStackerLM and RecipeBuilder to support multi-lora stack integration and enhance node size constraints
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:44:51 -04:00
THE_BEAST\meandCopilot fffcb49c4d feat: Add prompt serialization shim to ensure correct backend class integration for MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:13:03 -04:00
THE_BEAST\meandCopilot a89b04f81b feat: Enhance scrollbar styling and improve state restoration logic in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 22:07:36 -04:00
THE_BEAST\meandCopilot f137bfc751 feat: Implement dynamic theming using PM_UI_PALETTE in prompt_manager_advanced and recipe_builder
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:50:34 -04:00
THE_BEAST\meandCopilot 6cd2c40fb8 feat: Integrate PM_UI_PALETTE for dynamic styling in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:21:46 -04:00
THE_BEAST\meandCopilot 0fb68ddd16 feat: Enhance styling for MultiLoraStackerLM with flexible height and layout adjustments
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:15:11 -04:00
THE_BEAST\meandCopilot e583c6b529 feat: Refactor height management and slot selection handling in MultiLoraStackerLM
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 21:08:24 -04:00
THE_BEAST\meandCopilot 58b9305a02 First wip of multi Lora Stacker
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 20:34:56 -04:00
THE_BEAST\meandCopilot 654488efd3 feat: Enhance WAN model handling with improved slot resolution and dual-sampler support
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 16:53:50 -04:00
THE_BEAST\me 3e15a45cb8 feat: Refactor visibility handling for family-specific models and enhance error checking for WAN video family consistency 2026-04-27 12:39:57 -04:00
THE_BEAST\meandCopilot 82ea8ce773 feat: Adjust thumbnail preview timing and enhance multi LoRA stack handling for clearer slot management
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 02:55:42 -04:00
THE_BEAST\meandCopilot 8cdf32e3b1 feat: Enhance LoRA handling in WorkflowBuilder and WorkflowRelay for improved state management and path resolution
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 01:21:07 -04:00
THE_BEAST\meandCopilot 1b5eb256f9 feat: Enhance slot profile handling by introducing section locks and effective value resolution in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 00:33:34 -04:00
THE_BEAST\meandCopilot 545332f43e feat: Update default sampler settings and add family override support in WorkflowRelay
Co-authored-by: Copilot <copilot@github.com>
2026-04-27 00:02:39 -04:00
THE_BEAST\meandCopilot 5ce3248216 feat: Add blank model block function to ensure v2 schema compliance and enhance model slot handling in workflow output
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 23:29:10 -04:00
THE_BEAST\meandCopilot c70894a020 feat: Improve recipe data handling by adding legacy support and normalization for v2 structure
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 23:05:28 -04:00
THE_BEAST\meandCopilot a756747d08 feat: Preserve existing denoise value in WorkflowBuilder when omitted in profile
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 21:50:36 -04:00
THE_BEAST\meandCopilot c93e9eada9 feat: Enhance lora handling by introducing preferred profile loras and maintaining drag/drop order in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 21:35:12 -04:00
THE_BEAST\meandCopilot 1fb017f772 feat: Add support for lora ghosting in profile handling within WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 20:37:25 -04:00
THE_BEAST\meandCopilot c4cec35a19 feat: Enhance input ghosting logic in WorkflowBuilder and recipe handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 20:11:22 -04:00
THE_BEAST\meandCopilot 9ee1a0dd52 Refactor model handling and update placeholder strings
- Simplified model slot normalization by removing unnecessary parameters and checks.
- Updated the logic for determining primary and secondary model slots in the workflow builder.
- Changed placeholder strings from '(from checkpoint)' to '(Default)' across various modules for consistency.
- Removed the WAN-specific builder class and adjusted the multi-slot builder to handle model slots more effectively.
- Enhanced the extraction utilities to ensure proper handling of VAE and CLIP information.

Co-authored-by: Copilot <copilot@github.com>
2026-04-26 19:55:45 -04:00
THE_BEAST\meandCopilot 15587a5d56 feat: Refactor RecipeBuilder to integrate builder_data input and streamline multi-slot handling
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 17:58:25 -04:00
THE_BEAST\meandCopilot 75c2ccc562 feat: Simplify RecipeBuilder by removing WAN and Multi variants, streamlining node interactions
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 17:15:00 -04:00
THE_BEAST\me bcd68b11cd Implement feature X to enhance user experience and optimize performance 2026-04-26 16:46:17 -04:00
THE_BEAST\meandCopilot 83cea8e955 feat: Update recipe handling to ensure empty prompts on new node instances and improve workflow data management
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 16:26:27 -04:00
THE_BEAST\meandCopilot 8417d42ff6 feat: Add multi-slot support with new helper nodes for prompts, seeds, and LoRA stacks in Recipe Builder
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 14:39:02 -04:00
THE_BEAST\me 5188d04b02 feat: Merge incoming slot data while preserving lock states for improved profile management 2026-04-26 12:40:43 -04:00
THE_BEAST\meandCopilot f62ff73d2c feat: Add multi-slot support in Recipe Builder for enhanced model management
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 12:10:46 -04:00
THE_BEAST\meandCopilot d348e71664 feat: Update SVG icons and adjust layout dimensions for improved UI consistency
Co-authored-by: Copilot <copilot@github.com>
2026-04-26 01:07:29 -04:00
THE_BEAST\me 98c6f11904 feat: Implement collapsible and lockable sections in the workflow builder 2026-04-26 00:22:23 -04:00
THE_BEAST\meandCopilot 2d3a4ffe32 feat: Enhance workflow data handling to preserve active states and improve LORA management
Co-authored-by: Copilot <copilot@github.com>
2026-04-25 20:28:18 -04:00
THE_BEAST\meandCopilot 8bd45cb519 Refactor workflow data handling to support v2 model structure
- Updated PromptExtractor to construct workflow data with a new v2 model format, including handling of model_a and model_b blocks.
- Enhanced PromptManagerAdvanced to retain Lora paths during normalization for better data integrity.
- Modified RecipeBuilder to apply preferred Lora order and manage model overrides more effectively.
- Improved RecipeManager to ensure proper handling of model_a and model_b outputs, including conditional logic for model retention.
- Adjusted RecipeRelay to streamline model slot management and ensure compatibility with v2 structure.
- Cleaned up RecipeRenderer to align with new model data handling, removing legacy references.
- Removed deprecated legacy top-level keys and streamlined ensure_v2_recipe_data function for clarity and efficiency.

Co-authored-by: Copilot <copilot@github.com>
2026-04-25 18:19:30 -04:00
THE_BEAST\meandCopilot afb9c567eb feat: Refactor WorkflowRelay to handle v2 recipe structures and maintain legacy support
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 22:43:38 -04:00
THE_BEAST\meandCopilot f2ad940d32 feat: Add RecipeModelPicker node and integrate model data handling in WorkflowRelay
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 22:33:16 -04:00
Francois Beaudry 99b44c1bc2 Merge pull request #37 from FranckyB/dev
Dev
2026-04-24 19:02:20 -04:00
THE_BEAST\meandCopilot f721466c14 Enhance prompt filtering to preserve selections during workflow restoration
- Updated `filterPromptDropdown` function to accept an options parameter for preserving dangling selections.
- Modified calls to `filterPromptDropdown` in both `prompt_manager.js` and `prompt_manager_advanced.js` to maintain user selections when loading prompts asynchronously.
- Introduced flags to manage workflow restoration state, preventing unwanted changes to selections during the restore process.
- Ensured that category and prompt widgets retain their values when the current selection is not present in the filtered options.

Co-authored-by: Copilot <copilot@github.com>
2026-04-24 18:59:49 -04:00
THE_BEAST\meandCopilot 2b3a3bfe45 feat: Update version to 2.2.0 and enhance changelog with new features and improvements
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:58:05 -04:00
THE_BEAST\meandCopilot f1cdcfeff5 feat: Add model slot validation in WorkflowRenderer to ensure defined models
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:21:16 -04:00
THE_BEAST\meandCopilot 9f4e02c7f5 feat: Improve LoRA input handling and update authoritative state logic in WorkflowBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 17:03:24 -04:00
THE_BEAST\meandCopilot 05415abf49 feat: Improve update button visibility handling and default selection logic in RecipeBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 16:45:08 -04:00
THE_BEAST\meandCopilot 946400d441 feat: Enhance model slot handling and improve error messaging in RecipeBuilder
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 16:14:46 -04:00
THE_BEAST\meandCopilot 57c56de26b feat: Add workflow summary info button and enhance preview handling in PromptManagerAdvanced
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 14:23:30 -04:00
THE_BEAST\meandCopilot 8e4c230300 feat: Enhance recipe and prompt management with v2 model slot support and extraction improvements
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 13:33:26 -04:00
THE_BEAST\me d365f7752c feat: Enhance recipe management with improved model slot handling and v2 compatibility 2026-04-24 12:06:31 -04:00
THE_BEAST\me e8e5e5a09e feat: Enhance prompt management with v2 compatibility and fallback mechanisms for LoRA handling 2026-04-24 05:01:00 -04:00
THE_BEAST\meandCopilot 3640df2bf4 feat: Initialize model key and weight dtype before normalization for v2 compatibility
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 03:21:05 -04:00
THE_BEAST\meandCopilot ba7e993888 feat: Update model parameters and enhance recipe handling for v2 compatibility
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 03:16:58 -04:00
THE_BEAST\me 9a22a329f3 feat: Add support for model pair options in recipe builder for WAN mode 2026-04-24 02:03:36 -04:00
THE_BEAST\meandCopilot 32f653e18d Refactor recipe management to support v2 model blocks
- Introduced functions to ensure v2 recipe data structure and retrieve model blocks.
- Updated WorkflowManager to utilize new v2 model block structure for handling model_a and model_b.
- Refactored WorkflowRelay to accommodate model slot selection and improved handling of sampler and resolution settings.
- Enhanced RecipeRenderer to support rendering from specified model slots in v2 recipe data.
- Updated workflow_data_utils to normalize legacy recipe data into the new v2 format, preserving necessary fields.
- Improved handling of LoRA stacks and sampler configurations across different recipe data versions.

Co-authored-by: Copilot <copilot@github.com>
2026-04-24 01:45:38 -04:00
THE_BEAST\meandCopilot 03185836b9 fix: Update README for clarity on recipe extraction and modification
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 15:32:19 -04:00
THE_BEAST\meandCopilot 7812a98ddc feat: Bump version to 2.1.1 and update changelog; remove unused check_loaders.py
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 13:16:15 -04:00
THE_BEAST\meandCopilot 609375766b feat: Ensure backend updates are applied on new prompt reset by clearing execution update signals
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 13:13:25 -04:00
THE_BEAST\meandCopilot 7cc6e8c20a feat: Preserve explicit empty selection in prompt dropdown across tab-switch restore
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 12:55:02 -04:00
THE_BEAST\meandCopilot 5acc0d6e8c feat: Enhance workflow data handling with meaningful checks and improve LoRA availability tracking
Co-authored-by: Copilot <copilot@github.com>
2026-04-22 12:36:01 -04:00
THE_BEAST\me ce6d34b24e Updated provided Workflows 2026-04-22 09:42:24 -04:00
THE_BEAST\me 98b53ddd71 feat: Enhance README with new features and update images; rename workflow data to recipe data 2026-04-22 09:30:56 -04:00
THE_BEAST\me d7347e790c feat: Add comprehensive Prompt Manager and Workflow tools for ComfyUI
- Introduced Prompt Manager, Prompt Generator, Prompt Extractor, and Prompt Model Loader.
- Added Workflow Extractor, Builder, Renderer, and Manager for streamlined workflow management.
- Enhanced prompt saving with LoRA and trigger word support.
- Implemented dual LoRA stack functionality and improved metadata extraction from images and videos.
- Updated documentation to reflect new features and usage instructions.
- Version 2.0.0 release with significant improvements and new capabilities.
2026-04-22 08:53:11 -04:00
THE_BEAST\me 3c101e1b8a fix: update README to clarify model support and custom model path 2026-04-22 06:58:56 -04:00
Francois Beaudry fdd64969ae Merge pull request #35 from FranckyB/dev
Dev
2026-04-21 23:55:51 -04:00
THE_BEAST\me 7135b9e721 bump: update version to 2.1.0 in __init__.py and pyproject.toml 2026-04-21 23:53:44 -04:00
THE_BEAST\me 738dd63182 refactor: remove workflow-related options and streamline prompt management logic 2026-04-21 23:52:16 -04:00
THE_BEAST\me f231989e69 fix: update CivitAI search URL to use the correct domain 2026-04-21 23:23:46 -04:00
THE_BEAST\me c42a963d68 Refactor workflow-related terminology to use "recipe" instead of "workflow"
- Updated variable names, comments, and documentation to replace "workflow_data" with "recipe_data" across multiple files.
- Adjusted input and output types in nodes to reflect the new naming convention.
- Modified the functionality of nodes to ensure compatibility with the new "recipe_data" structure.
- Ensured that all references to workflow extraction and management are now aligned with the recipe terminology.
2026-04-21 23:05:01 -04:00
THE_BEAST\me c701bb5002 Add documentation for ComfyUI tab switch and state persistence
- Outline how ComfyUI handles tab switches and the lifecycle of node creation.
- Detail the serialization of node properties and the correct pattern for storing and restoring state.
- Emphasize critical rules for maintaining state and avoiding common pitfalls.
- Provide guidelines for DOM widget sizing and the use of flex properties to prevent layout issues.
- Include reference patterns and best practices for ensuring reliable UI behavior during tab persistence.
2026-04-21 21:44:03 -04:00
THE_BEAST\me 0196bca21e refactor: update README for clarity and improved structure, emphasizing Recipe terminology 2026-04-21 21:10:33 -04:00
THE_BEAST\me d92fcf436c Refactor code structure for improved readability and maintainability, updated Workflows with new naming 2026-04-21 13:12:33 -04:00
THE_BEAST\me 89dc3a4e94 feat: update terminology from Workflow to Recipe across multiple files 2026-04-21 10:22:02 -04:00
THE_BEAST\me 2e8333a4cc feat: update terminology from Workflow to Recipe across multiple files 2026-04-21 09:58:24 -04:00
THE_BEAST\me cc35c8e4e6 Refactor workflow and prompt extraction nodes for Recipe compatibility
- Updated node types in workflow_builder_simple.json to replace WorkflowGenerator with RecipeExtractor and RecipeBuilder.
- Modified prompt_extractor.py to include RecipeExtractor and RecipeRenderer in prompt handling logic.
- Enhanced workflow_extraction_utils.py to support Recipe nodes alongside Workflow nodes for embedded data extraction.
- Ensured backward compatibility with legacy WorkflowGenerator while transitioning to Recipe-based workflows.
2026-04-21 09:33:09 -04:00
THE_BEAST\me f7789930c1 feat: rename workflow terminology to recipe across documentation and codebase 2026-04-21 02:14:17 -04:00
THE_BEAST\me b775a1d93d feat: enhance workflow data handling and input normalization in WorkflowBuilder 2026-04-21 01:21:45 -04:00
Francois Beaudry 430f7cf276 Merge pull request #34 from FranckyB/dev
feat: Add Ernie family support in workflow components and update model handling
2026-04-20 00:55:24 -04:00
THE_BEAST\me df8f2b57d3 chore: Bump version to 2.0.2 and update README with Ernie support details
feat: Add Ernie family support in workflow components and update model handling
fix: Improve handling of missing injections in select rows and align family defaults
2026-04-20 00:52:03 -04:00
Francois Beaudry 42f3559e8c Merge pull request #32 from FranckyB/dev
Add new workflow configuration for high-resolution image processing
2026-04-19 17:21:03 -04:00
THE_BEAST\me ba301ce39a Add new workflow configuration for high-resolution image processing
- Introduced a new workflow JSON file `workflow_builder_simple-hirez.json`
- Configured nodes for image processing including WorkflowRenderer, SaveImage, and WorkflowManager
- Implemented input and output links for workflow data and image handling
- Defined properties and widgets for user interaction and customization
2026-04-19 17:14:50 -04:00
Francois Beaudry 1c86920d3b Merge pull request #31 from FranckyB/dev
Dev
2026-04-19 15:42:25 -04:00
THE_BEAST\me 39ade25cc2 chore: Bump version to 2.0.1 and update changelog with denoise options for workflow pipeline 2026-04-19 15:37:19 -04:00
THE_BEAST\me 3ff5ff7902 fix: Remove redundant inputs from node in Prompt Selector Widget 2026-04-19 15:30:31 -04:00
THE_BEAST\me f764beef53 fix: Improve formatting of use_prompt_input settings in PromptManagerAdvanced 2026-04-19 14:28:29 -04:00
THE_BEAST\me 1fb0d3dcc7 feat: Add denoise parameter to sampler settings across workflow components
- Introduced 'denoise' parameter in workflow_builder.js, workflow_bridge.py, and workflow_renderer.py to enhance rendering control.
- Updated prompt_extractor.py to include default denoise value in extracted workflow data.
- Modified workflow_extraction_utils.py to handle denoise parameter during extraction and building of sampler dictionaries.
- Ensured denoise parameter is properly managed in various functions to maintain consistency across the workflow.
2026-04-19 13:19:47 -04:00
Francois Beaudry f748246801 Merge pull request #26 from FranckyB/dev
Dev
2026-04-19 02:04:20 -04:00
THE_BEAST\me b7905b81da Refactor code structure for improved readability and maintainability 2026-04-19 02:01:13 -04:00
THE_BEAST\me dd78c417ba Refactor workflow saving and management functionality
- Removed the WorkflowSaver module and integrated its functionality into the PromptManagerAdvanced and WorkflowManager classes.
- Enhanced the createWorkflowSaveBrowserModal function to streamline the workflow saving process, including improved handling of existing prompts and categories.
- Updated the savePrompt function to ensure proper normalization of LoRA data and workflow data persistence.
- Improved the handling of workflow data in the WorkflowManager to prioritize live data over local state.
- Added new utility functions for better management of workflow data serialization, ensuring non-serializable objects are stripped before saving.
- Enhanced error handling and user notifications throughout the workflow saving process.
2026-04-19 01:17:30 -04:00
THE_BEAST\me eb9dc96631 feat: Add WorkflowManager for streamlined workflow_data editing
- Introduced WorkflowManager class, a simplified version of PromptManagerAdvanced, focusing solely on workflow_data input/output.
- Updated workflow_builder.js to include WorkflowManager in node type checks and error messages.
- Enhanced error handling and logging for better debugging.
- Implemented thumbnail generation for workflow_data visualization.
- Refactored input types and return structures to accommodate new workflow management features.
2026-04-18 23:44:00 -04:00
THE_BEAST\me 5beaf8e501 feat: Annotate missing LoRAs in workflow data to maintain authored stack information 2026-04-18 21:19:26 -04:00
THE_BEAST\me bf2ad422d7 feat: Improve LoRA handling by filtering out missing LoRAs from workflow data while maintaining UI visibility 2026-04-18 21:00:08 -04:00
THE_BEAST\me 89825a747d feat: Enhance LoRA management with original strengths caching and UI state protection 2026-04-18 20:32:41 -04:00
THE_BEAST\me 0d8e9192f1 Add shared UI palette for Prompt Manager modals
- Introduced a new JavaScript file `ui_palette.js` containing color definitions for modal dialogs.
- Aligned the palette with Workflow Builder's neutral and blue accent styling.
- Defined colors for overlay, panel, borders, text, and accent elements to ensure consistent UI appearance.
2026-04-18 19:59:26 -04:00
THE_BEAST\me 763a340488 Add PromptManager and WorkflowSaver for managing prompts and workflow snapshots
- Implemented PromptManager for saving and loading prompts by category with backup functionality.
- Added API endpoints for managing prompts, including saving, deleting, and importing prompts.
- Introduced WorkflowSaver to capture and save workflow_data snapshots into prompt library entries.
- Included thumbnail generation from images for saved workflows.
- Enhanced error handling and validation for API requests.
2026-04-18 17:23:22 -04:00
THE_BEAST\me 7362da49d9 feat: Implement weekly rotating backup for prompt data to enhance data safety and recovery 2026-04-17 22:35:49 -04:00
THE_BEAST\me 9f4bac5f30 feat: Refactor workflow data handling and input connections for improved prompt management and seed control 2026-04-17 22:21:33 -04:00
THE_BEAST\me f36411aac5 feat: Add workflow_data input support in Prompt Manager Advanced for enhanced prompt and LoRA stack integration 2026-04-17 21:11:17 -04:00
THE_BEAST\me 0d3216d0e9 feat: Enhance workflow toggle handling with state persistence and restoration 2026-04-17 21:05:35 -04:00
THE_BEAST\me 834aff18da feat: Enhance LoRA management and workflow integration
- Introduced sorting functions for LoRAs to prioritize available ones and sort alphabetically.
- Normalized extracted LoRA order in prompt extraction to ensure consistent display.
- Added support for workflow data in the prompt manager, allowing for dynamic updates based on connected inputs.
- Implemented live workflow data pickup to refresh prompts and LoRAs in real-time.
- Updated UI to reflect the presence of workflow data with visual indicators.
- Enhanced backend logic to handle workflow data more effectively, including extraction from connected nodes.
- Added new configuration options for using workflow data in the prompt manager.
2026-04-17 20:53:16 -04:00
THE_BEAST\me bae6df106a feat: Enhance LoRA management and workflow integration
- Added sorting functionality for LoRA lists to ensure consistent ordering.
- Improved merging of LoRA lists to deduplicate entries and maintain order.
- Updated `PromptManagerAdvanced` to support workflow data integration, allowing for LoRAs to be sourced from saved workflow data.
- Refactored handling of workflow data in `get_prompt` method to prioritize connected inputs and saved data.
- Enhanced error messaging for missing connections in workflow data.
- Updated documentation strings for clarity on functionality.
- Bumped version to 1.25.0 to reflect new features and improvements.
2026-04-17 19:20:16 -04:00
THE_BEAST\me 07b428767e feat: Enhance LoRA state persistence and extraction in WorkflowBuilder and PromptExtractor 2026-04-17 16:37:46 -04:00
THE_BEAST\me 6a58f9ce95 feat: Update help text and button labels in Workflow Builder for clarity 2026-04-17 15:17:00 -04:00
THE_BEAST\me bdb1cc4212 feat: Enhance resolution extraction and media dimension handling in PromptExtractor and WorkflowExtractionUtils 2026-04-17 10:39:24 -04:00
THE_BEAST\me cbc0efa839 feat: Enhance model handling by normalizing family selection and improving resolution extraction 2026-04-17 05:44:17 -04:00
THE_BEAST\me 119952a51d feat: Enhance model selection and prompt persistence in WorkflowBuilder 2026-04-17 04:34:30 -04:00
THE_BEAST\me d0e591c24c feat: Replace WorkflowContext with WorkflowBridge and enhance workflow data handling 2026-04-17 03:36:10 -04:00
THE_BEAST\me df148d8cd3 feat: Update family defaults and enhance extractor handling in WorkflowBuilder and WorkflowRenderer 2026-04-17 01:34:28 -04:00
THE_BEAST\me c76a95adf9 Refactor WorkflowBuilder, WorkflowContext, and WorkflowRenderer for improved handling of overrides and conditioning
- Enhanced WorkflowBuilder to allow conditional overrides based on section locks, ensuring local UI overrides are respected only for locked sections when workflow data is present.
- Updated the handling of model, sampler, and resolution parameters to apply overrides conditionally.
- Modified WorkflowContext to include positive and negative conditioning as optional parameters, passing them through to the workflow data.
- Introduced a new method in WorkflowRenderer to encode positive and negative text conditioning using the CLIP encoder, improving the handling of text prompts.
- Ensured that the workflow output includes the newly encoded conditioning data.
2026-04-17 00:18:40 -04:00
THE_BEAST\me 00ed3ffd92 feat: Implement strict family filtering for WAN video models and enhance show-all models functionality 2026-04-16 02:12:25 -04:00
THE_BEAST\me 3d72e8b4ff feat: Enhance Workflow Model Loader with GGUF support and improved model handling
- Added GGUF model loading capabilities to the WorkflowModelLoader.
- Updated WorkflowRenderer to include WORKFLOW_DATA in return types.
- Removed redundant versioning from workflow extraction utility.
- Deleted obsolete workflow model loader test file.
- Introduced a new JavaScript extension for visualizing loaded models in the UI.
- Improved model resolution and loading logic for checkpoints and diffusion models.
- Enhanced error handling and user feedback for missing models and assets.
2026-04-16 01:36:22 -04:00
THE_BEAST\me 5dd666fe3a Enhance workflow prompt extraction and model listing
- Updated prompt extraction logic to include WorkflowBuilder as a source of extracted data, prioritizing it appropriately alongside WorkflowRenderer and WorkflowGenerator.
- Modified the UI response of PromptExtractor and WorkflowExtractor to prevent displaying preview images in Comfy history/tasks, ensuring cleaner output.
- Improved model listing API to support a 'show_all' query parameter, allowing users to retrieve all models or only compatible ones based on the specified family.
- Enhanced fallback mechanisms for model retrieval to accommodate installations with inconsistent folder structures, ensuring better compatibility and user experience.
2026-04-15 23:50:55 -04:00
THE_BEAST\me 4fd7070c97 feat: Enhance VAE and CLIP handling for checkpoint models and preserve not-found LoRAs in workflow_data 2026-04-15 03:46:05 -04:00
THE_BEAST\me 9fcf4ef1a7 feat: Enhance WorkflowBuilder with caching and extraction data retrieval 2026-04-15 03:35:14 -04:00
THE_BEAST\me cb8b7e7205 feat: Add family_override support to workflow extraction process 2026-04-15 03:10:37 -04:00
THE_BEAST\me 661a35f971 feat: Refactor model loading and enhance UI styles for better usability 2026-04-15 03:01:37 -04:00
THE_BEAST\me 27eca5ba94 feat: Update LoRA stack and model labels for WAN Video visibility handling 2026-04-15 02:01:19 -04:00
THE_BEAST\me e7fece763c feat: Update WAN visibility handling for video mode and enhance resolution row layout 2026-04-15 01:42:55 -04:00
THE_BEAST\me 56bdb9e98a feat: Swap width and height values for landscape orientation in workflow builder 2026-04-15 01:23:56 -04:00
THE_BEAST\me 24f6f8ad65 feat: Enhance workflow model loading and sampler parameter extraction
- Added IS_CHANGED method in WorkflowRenderer to provide a stable fingerprint for workflow data, optimizing re-execution.
- Updated sampler parameter extraction to support new 'steps_a' and 'steps_b' keys, replacing legacy 'steps' handling.
- Refactored workflow extraction utilities to accommodate dual-sampler configurations and removed deprecated parameters.
- Introduced WorkflowGetModel node for streamlined model loading, supporting GGUF format and improved error handling.
- Enhanced model compatibility listing with keyword-based sorting for better user experience.
2026-04-15 01:18:57 -04:00
THE_BEAST\me bd8ffdca8a feat: Add right-click context menu for Lora tags with search functionality 2026-04-14 01:45:50 -04:00
THE_BEAST\me 3906e87e19 feat: Enhance model compatibility checks and default value handling for VAE/CLIP in workflow processing 2026-04-14 01:12:14 -04:00
THE_BEAST\me 376a58e27c feat: Show/hide "Update Workflow" button based on workflow_data connection 2026-04-14 00:37:38 -04:00
THE_BEAST\me 711cd87567 fix: Remove unnecessary workflow_data validation in PromptManagerAdvanced 2026-04-14 00:17:05 -04:00
THE_BEAST\me 00f23b4590 feat: Refactor WorkflowExtractor and WorkflowBuilder to streamline workflow data handling and improve prompt management 2026-04-14 00:09:31 -04:00
THE_BEAST\me e8639a5050 Refactor PromptExtractor and WorkflowBuilder for improved workflow data handling
- Set OUTPUT_NODE to False in PromptExtractor to disable preview display.
- Enhance PromptExtractor to merge final LoRA stacks into workflow_data and update the _last_extracted_info cache.
- Introduce WorkflowExtractor class for simplified extraction of workflow data and images, omitting LoRA inputs/outputs.
- Modify WorkflowBuilder to streamline input handling, removing unnecessary flags and improving LoRA merging logic.
- Ensure connected LoRA inputs are merged with existing workflow LoRAs, prioritizing user intent.
- Update input types and tooltips for clarity in the WorkflowBuilder.
2026-04-13 23:33:32 -04:00
THE_BEAST\me 54c9d98e85 feat: Implement "Update Workflow" functionality in WorkflowBuilder to fetch data from PromptExtractor 2026-04-13 20:20:08 -04:00
THE_BEAST\me c78cbd6913 feat: Enhance WorkflowBuilder and WorkflowRenderer to improve clip and VAE handling 2026-04-13 02:13:24 -04:00
THE_BEAST\me adf5766f48 Fix clip model family configuration by updating exclusions
- Removed "clip_l" from the "clip" model family.
- Added "clip_l" to the "clip_exclude" list to ensure proper filtering.
2026-04-13 01:43:24 -04:00
THE_BEAST\me 8accd26d94 fix: Update import statements to correctly reference workflow_renderer for render functions 2026-04-13 00:48:46 -04:00
THE_BEAST\me 7c2dc8248b feat: Enhance _run_standard_ksampler and rendering functions to support additional latent dict parameters 2026-04-13 00:37:04 -04:00
THE_BEAST\me 7eb21c918a feat: Add Test Render Functions and Workflow Model Loader
- Implemented a self-contained test node for rendering functions that auto-discovers compatible models, VAE, and CLIP, and runs the render pipeline, outputting IMAGE, LATENT, and a report.
- Created a Workflow Model Loader to load MODEL, CLIP, and VAE from workflow_data names, optimizing model loading with caching to prevent redundant operations.
- Introduced a new workflow renderer script to set initial node sizes for better UI alignment.
2026-04-13 00:19:21 -04:00
THE_BEAST\me 3d528c2997 feat: enhance WorkflowBuilder to apply lora overrides and filter inactive loras 2026-04-12 17:15:43 -04:00
THE_BEAST\me 6c11ec52de feat: add override_data support and improve model selection in WorkflowContext 2026-04-12 15:20:19 -04:00
THE_BEAST\me 07fd152e84 feat: enhance workflow data handling by supporting dict and JSON string formats 2026-04-12 13:56:43 -04:00
THE_BEAST\me a950ebfa92 Refactor workflow handling and model loading
- Removed the prompt_model_loader.py file as its functionality is now integrated into workflow_context.py.
- Updated workflow_builder.py to use seed_a instead of seed for sampler parameters.
- Changed category from "FBnodes" to "Prompt Manager" in workflow_builder.py and workflow_renderer.py.
- Enhanced workflow extraction utilities to support seed_a and seed_b for dual-sampler configurations.
- Introduced workflow_context.py to manage unpacking and repacking of workflow_data, including model loading and parameter overrides.
2026-04-12 13:27:51 -04:00
THE_BEAST\me 3effd8f1e8 feat: enhance WorkflowBuilder with positive and negative prompt inputs 2026-04-12 10:46:40 -04:00
THE_BEAST\me a1c496ed4c feat: add WorkflowRenderer for render-only node functionality
- Implemented WorkflowRenderer class to handle rendering from WORKFLOW_DATA.
- Supports model loading, sampling, decoding, and output of IMAGE and LATENT.
- Integrated optional GGUF support for enhanced model handling.
- Added error handling for model and VAE loading.
- Introduced patching mechanism for template-driven workflows.
- Enhanced logging for better traceability during execution.
2026-04-12 10:21:37 -04:00
THE_BEAST\me 504b2dce40 fix: adjust latent tensor dimensions for WAN video processing 2026-04-12 00:37:54 -04:00
THE_BEAST\me f8d228b42c Restored tab Switching fix and fixed Wan Video generation 2026-04-12 00:09:25 -04:00
FranckyBandClaude Opus 4.6 69912c724c fix: clamp resolution patch values to max 1280px for i2v, not the source image tensor
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:39:33 +00:00
FranckyBandClaude Opus 4.6 0db278723d fix: call WanImageToVideo.execute() classmethod instead of encode()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:25:26 +00:00
FranckyBandClaude Opus 4.6 a498a5e7f3 fix: clamp i2v source image resolution to max 1280px keeping aspect ratio
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:23:54 +00:00
FranckyBandClaude Opus 4.6 f3607303af fix: i2v api template batch_size=1, start_image from resize node, add SaveImage node
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:18:31 +00:00
FranckyBandClaude Opus 4.6 173328bf2d fix: use patched JSON template for i2v instead of manual Python node execution
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 00:11:42 +00:00
FranckyB 214f653d4e fix: preserve steps_high/low and seed overrides in wfOn mode; use explicit values over auto-split 2026-04-11 23:53:37 +00:00
FranckyB 74005592e8 fix: derive steps_high/low from steps split in JS; default 3/3 instead of 4/20 2026-04-11 23:49:26 +00:00
FranckyB 0939ae11ec fix: when wfOn, syncHidden must not capture model/VAE/CLIP from DOM — wf_data is authoritative for all fields 2026-04-11 23:44:15 +00:00
FranckyB b0ea8f6faf fix: pass fromUpdateUI flag to onFamilyChanged to skip auto-select and syncHidden when called from updateUI 2026-04-11 23:42:19 +00:00
FranckyB cf11bfc9d0 fix: split steps_high/low in wf_data for wan_video; don't overwrite model_a override in onFamilyChanged 2026-04-11 23:36:42 +00:00
FranckyB 0a757baa9b fix: fall back to first compatible family model when model_a not found, show red in UI 2026-04-11 23:33:00 +00:00
FranckyB 944759a05a fix: log source_image tensor shape (or None) for i2v debugging 2026-04-11 23:26:25 +00:00
FranckyB 92bb954fc2 fix: prioritize wf_data family over stale JS _family override in execute() 2026-04-11 23:24:19 +00:00
FranckyB 9fb3ffc6fb fix: use wan_i2v_image map key to patch LoadImage node directly for i2v source image 2026-04-11 22:57:28 +00:00
FranckyB 557152ae96 fix: await updateUI in wfToggle to prevent family snapping to SDXL; fix PIL image shape for i2v source 2026-04-11 22:55:17 +00:00
FranckyB de2c5cd295 fix: always split steps evenly for WAN dual-sampler (high=ceil/2, low=floor/2) 2026-04-11 22:42:15 +00:00
FranckyB d2323da13c fix: pre-load families list in updateUI so family dropdown switches correctly 2026-04-11 22:37:36 +00:00
FranckyB 7be4ea4748 fix: WAN i2v dual-sampler steps split, frame count as length, source image forwarding, add template print
- Bug 1: Split total steps evenly between high/low samplers using
  ceil/floor instead of sending the same value to both
- Bug 2: Extract WanImageToVideo batch_size as frame length (not
  batch_size), keep batch_size=1 for video workflows; add latent_length
  mapping to i2v map JSON
- Bug 3: Save source_image tensor to disk and patch LoadImage node in
  i2v template so the source image is forwarded to WanImageToVideo
- Bug 4: Print template name, family, strategy, and file path at the
  start of execute_template() for easier debugging
2026-04-11 22:24:14 +00:00
FranckyBandClaude Opus 4.6 6e9595a594 fix: remove unnecessary skipAutoSelect flag from onFamilyChanged
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 22:13:11 +00:00
FranckyB f5a66e1995 fix: updateUI reloads family dropdowns before setting model/VAE/CLIP values
When workflow_data specifies a family different from the current UI state
(e.g. wan_video_i2v fed into a node that defaulted to sdxl), updateUI was
setting sel.value = 'wan_video_i2v' visually but never reloading the model,
VAE, and CLIP dropdown lists. _setOriginal then couldn't find the WAN
model/VAE/CLIP names in the SDXL options list and fell back to (Default).

Fix:
- updateUI is now async
- Stores onFamilyChanged on node as node._onFamilyChanged after definition
- When the incoming family differs from node._weFamily, updateUI awaits
  node._onFamilyChanged(newFamily, { skipAutoSelect: true }) before
  setting model/VAE/CLIP — dropdowns are now populated with the correct
  family's options before _setOriginal runs
- skipAutoSelect option added to onFamilyChanged so the auto-first-model
  logic is skipped when called from updateUI (updateUI sets the correct
  model itself from workflow_data)
2026-04-11 22:08:18 +00:00
FranckyB 28e6299bec fix: NameError 'overrides' not defined in PE resolution fallback
'overrides' is a param of extract_all_from_file(), not in scope inside
PromptExtractor.extract(). Simplified the condition — the _from_node_ref
and bare-512 checks are merged into a single guard, and tensor shape
values are explicitly cast to int.
2026-04-11 21:59:36 +00:00
FranckyB 8cbe4943a1 feat: add Seed B for WAN Video dual-sampler (high/low pass get independent seeds)
WAN Video uses two KSamplerAdvanced nodes (high-pass + low-pass). Previously
both got the same seed value, and extract_sampler_params was returning the
first node it found — the second seed was inaccessible.

Changes:
- extract_sampler_params: collect all KSamplerAdvanced nodes instead of
  returning on first match; expose second node seed as 'seed_b' (None if
  only one node found)
- All seed values are guarded against node-ref lists (isinstance list check)
- build_simplified_workflow_data: includes seed_b in sampler output
- workflow_generator.py (wf_data path): reads seed_b from wf_sampler
- execute(): passes seed_b into patch_params; if seed_b is None for a
  wan_video strategy, falls back to seed (same value for both samplers)
- patch_template: ksampler_high_seed gets seed, ksampler_low_seed gets
  seed_b (falling back to seed if None)
- JS: Seed B row added (hidden by default, shown for WAN Video); Seed row
  label renamed to 'Seed A' when WAN Video is active; seed_b synced,
  applied, and deleted in wfOn mode; _onExecutedSeed applies control mode
  (randomize/increment/decrement) to both seeds independently
2026-04-11 21:52:07 +00:00
FranckyB 09597becc5 fix: PE now reports real source dimensions; propagate node-ref flags through wf_data
Problems:
1. PE showed 512x512 for i2v video — extract_resolution resolved node-refs to
   the ImageResizeKJv2 *input* params (512x512 target), not the actual output.
2. _from_node_ref flags were stripped when building workflow_data JSON output,
   so WorkflowGenerator never saw them from the wf_data path.
3. Defensive guard against list-typed sampler scalars (seed, steps, cfg) that
   could arrive via corrupt override_data JSON.

Fixes:
- prompt_extractor.py: after extract_resolution(), if _from_node_ref is set
  OR resolution is still the bare 512x512 default, overwrite with actual
  image_tensor dimensions (already extracted as the preview frame).
  Applies to any source — videos, images, any file type.
- workflow_extraction_utils.py (build_simplified_workflow_data): propagate
  _width_from_node_ref / _height_from_node_ref into the output resolution
  dict so downstream WorkflowGenerator can use source_image dims.
- workflow_generator.py (wf_data path): pass _from_node_ref flags through
  when building extracted['resolution'] from wf_data.
- workflow_generator.py (sampler_params): guard against list-typed seed/steps/
  cfg values coming through overrides or extracted sampler dict.
2026-04-11 21:44:34 +00:00
FranckyB 0fa7eec08d fix: use source_image dimensions as fallback when template uses node-refs for size
Templates like wan_video_i2v wire WanImageToVideo width/height to the output
of an ImageResizeKJv2 node — these are runtime values, not stored in the JSON.
extract_resolution reads the resize node's *input* params (512x512) which is
the resize target, not the actual output size.

Fix: extract_resolution now sets _width_from_node_ref / _height_from_node_ref
flags when width/height are node references. execute() checks these flags and,
when the user hasn't set an explicit UI override, reads actual dimensions from
the source_image tensor shape ([B, H, W, C]) instead. This correctly handles
i2v (and any future template) where the output size tracks the input image.
2026-04-11 21:37:54 +00:00
FranckyB 3df92b0509 fix: resolve node-ref lists in extract_resolution for i2v/flux2 templates
WanImageToVideo (i2v) and EmptyFlux2LatentImage (flux2) store width/height
as node references (['node_id', output_slot]) instead of scalar ints, because
they're wired to upstream ImageResizeKJv2 / PrimitiveInt nodes. This caused:
  TypeError: int() argument must be a string... not 'list'

Fixes:
- extract_resolution (prompt_data path): resolve node-ref lists by looking up
  the referenced node in prompt_data (handles PrimitiveInt 'value' field and
  ImageResizeKJv2 width/height fields)
- batch_size in WanImageToVideo equals 'length' frames (640) — clamp to 1
  when > 64 to avoid nonsensical batch sizes
- Add EmptyHunyuanLatentVideo to VIDEO_LATENT_TYPES (wan_video_t2v uses it)
- execute(): add _to_int() defensive helper as safety net for any edge cases
  that slip through extract_resolution
2026-04-11 21:25:33 +00:00
FranckyB 1556a07653 fix: add CLIPType mappings for all templates (qwen_image, lumina2/z-image)
Every template's CLIPLoader type now maps to the correct CLIPType enum:
- flux2      → CLIPType.FLUX2
- flux       → CLIPType.FLUX
- sd3        → CLIPType.SD3
- wan        → CLIPType.WAN        (umt5-xxl, vocab 256384)
- qwen_image → CLIPType.QWEN_IMAGE (Qwen2.5-VL image encoder)
- lumina2    → CLIPType.LUMINA2    (z-image / Lumina2 encoder)

Also added qwen_image and zimage to the family detection fallback
in execute() so workflow_data mode picks the right sampler strategy
when the model name isn't found in MODEL_FAMILIES.
2026-04-11 21:21:01 +00:00
FranckyB 64bcb706ae fix: use CLIPType.WAN for wan clip_type to fix umt5-xxl shape mismatch
WAN templates (wan_image, wan_video_t2v, wan_video_i2v) all specify
clip_type='wan' in their CLIPLoader nodes. _load_clip() had no 'wan'
case so it fell through to CLIPType.STABLE_DIFFUSION (vocab 32128),
causing a shape mismatch when loading umt5-xxl (vocab 256384).

Added:
- elif 'wan' in t: CLIPType.WAN in _load_clip()
- elif 'wan' in clip_type: family_key='wan_video_t2v' in execute()
  family fallback (for workflow_data mode with unknown model name)
2026-04-11 21:18:32 +00:00
FranckyB 61a7f6bf45 fix: pass batch_size into patch_template params 2026-04-11 21:11:31 +00:00
FranckyB 2f2be6c075 fix: remove dangling else block that broke node UI rendering 2026-04-11 21:09:31 +00:00
FranckyB f4fa4bebff fix: use class-level model cache so models persist across executions
ComfyUI creates a new node instance on every queue run, so the previous
instance-level _model_cache was always empty. Moving to a class-level
dict keyed by (unique_id, full_path, family_key) makes the cache survive
across runs for the lifetime of the ComfyUI process. Each canvas node
keeps its own slot so multiple WorkflowGenerator nodes don't collide.
2026-04-11 21:07:16 +00:00
FranckyB bac173134b fix: workflow_data mode now always populates all fields from source
syncHidden no longer captures sampler/resolution/prompts as overrides
when use_workflow_data is ON — those values always come from the source.
Stale overrides are cleared on each pre-update. onConfigure no longer
restores overrides in workflow_data mode so cached stale values cannot
block source data from populating the UI.
2026-04-11 21:02:54 +00:00
FranckyB 04e403d93b fix: wan_image now shows wan_video_t2v models via compat group 2026-04-11 20:56:49 +00:00
FranckyBandClaude Opus 4.6 e4d58e59ee feat: detect family from clip_type/loader_type in workflow_data
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 20:53:25 +00:00
FranckyB ee2047cac6 Revert "fix: prevent model unloading on every generation"
This reverts commit 6e79a82596.
2026-04-11 20:50:43 +00:00
FranckyBandClaude Opus 4.6 6e79a82596 fix: prevent model unloading on every generation
execute_template() was loading models from disk on every call, bypassing
the WorkflowGenerator's instance-level _model_cache. This caused models
to be fully reloaded (unloaded then loaded from disk) on every generation
run for all template-based families (SDXL, Flux1, Flux2, WAN, etc.).

Pass cached model tuples from WorkflowGenerator._model_cache into
execute_template() so it reuses already-loaded models instead of
reloading from disk each time. Also cache model B in the template
code path (previously only cached in the hardcoded fallback path).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 20:36:52 +00:00
FranckyB b0fdbf1a97 fix: move source_image input to last position, matching PromptExtractor 2026-04-11 20:30:38 +00:00
FranckyB d12d8bb484 fix: add bottom padding to prevent selection toolbox overlap
The ComfyUI selection toolbox (~32px tall) renders as a Vue overlay at
the bottom edge of the selected node, covering the last section header.

Fix: paddingBottom: 38px on root div — scrollHeight includes this
padding so computeSize accounts for it automatically, and the toolbox
always has clear space below the last section.
2026-04-11 20:24:48 +00:00
FranckyB b4a41e2340 fix: correct initial node height — defer setSize until DOM is painted
The previous setSize([MIN_W, root.scrollHeight]) fired synchronously at
node creation when the browser hadn't painted yet, so scrollHeight was 0
and the node defaulted to MIN_H=300, clipping the LoRA section.

Fix:
- Defer initial setSize via double rAF so scrollHeight is real
- Add NATIVE_H=90 (title bar ~30px + 2 toggle widgets ~28px each) to
  both the initial setSize and the onResize minimum, so the total node
  height = DOM content + native widgets above it
- onResize now correctly prevents dragging below content + native height
2026-04-11 20:21:30 +00:00
FranckyB 9ccfc23f66 fix: restore collapsible sections, use computeSize pattern for node sizing
The previous session incorrectly replaced the sizing approach with
getHeight/getMinHeight (which is not how ComfyUI works) and removed
collapsible sections as a side-effect.

Root cause of the grey gap was never getHeight — it was that _weRecalc
called setSize() in a loop fighting LiteGraph. The correct pattern
(used by prompt_manager_advanced.js in this very repo) is:

  domW.computeSize = function(width) { return [width, root.scrollHeight]; }
  app.graph.setDirtyCanvas(true, true)  // on any content change

LiteGraph re-queries computeSize on every canvas redraw automatically.
No setSize(), no manual recalc loop, no getHeight/getMinHeight needed.

Changes:
- Restore makeSection() with collapsible chevron + click handler
  (toggle calls setDirtyCanvas so computeSize is re-queried)
- Replace getHeight/getMinHeight with domW.computeSize = f(scrollHeight)
- Restore onResize minimum height enforcement (content height floor)
  so user cannot drag node smaller than visible UI
- Restore initial node.setSize() call to fit content on creation
2026-04-11 20:15:03 +00:00
FranckyB 55b59f876e fix: wan_image now uses same model/vae/clip filtering as wan_video_t2v
WAN 2.2 T2I models are the same files as T2V — same folders, names,
VAE and CLIP patterns.  wan_image was previously a dead stub (names:
["wan_image"]) that matched nothing.

Changes:
- wan_image gets identical folders/names/vae/clip as wan_video_t2v
- Dict order is now i2v → t2v → image so auto-detection hits t2v first
  (first-match wins; user selects wan_image explicitly from dropdown)
- No compat group needed — filtering is identical, model list is the same
- Sampler stays wan_image (single KSampler, no dual Steps rows)
2026-04-11 20:10:32 +00:00
FranckyB 1f348ea4e8 fix: move Sampler section after Model, auto-select first model on family change
- Section order: Resolution → Model → Sampler → Positive → Negative → LoRAs
- onFamilyChanged now auto-selects options[1] (first real model) after reload
  so (none) is never the active selection when models exist
- Also carries forward: collapsible removal, getHeight/getMinHeight resize fix
2026-04-11 20:06:01 +00:00
FranckyB c3b912aa76 fix: UnboundLocalError for has_both_stacks on template path
has_both_stacks was moved into the hardcoded fallback else-block in the
previous VAE/CLIP refactor, but the template path also references it
when calling loras_to_text(). Hoisted the definition above the
if/else split so both paths can use it, and removed the now-duplicate
definition from the else-block.
2026-04-11 19:48:09 +00:00
FranckyB d154fab852 fix: node height cut-off and expand/collapse not resizing
Two related sizing issues:

1. Section expand/collapse did not update node height.
   The toggle handler called _weRecalc() synchronously, so scrollHeight
   was measured before the browser reflowed the newly shown/hidden body.
   Fix: use double-rAF (same pattern as initial setup at line 1445) in
   the click handler AND in _expand/_collapse so the DOM is fully
   reflowed before we measure.

2. Node bottom was cut off (content clipped).
   NATIVE_H=80 underestimated the LiteGraph title bar (~30px) plus the
   two native toggle widgets (~28px each), leaving ~6px short before any
   padding margin. Bumped to 110 to give a small breathing margin.

No structural changes to _resizeNode or the infinite-loop guard.
2026-04-11 19:47:05 +00:00
FranckyB 10e3998230 fix: (Default) VAE/CLIP no longer crashes diffusion model families
Root cause: VAE and CLIP were loaded in Python unconditionally before
the template/fallback branch split. For diffusion model families (flux1,
flux2, wan, ltxv, zimage) _load_model_from_path returns vae_a=None and
clip_a=None (no bundled VAE/CLIP in the diffusion checkpoint). When the
user selected (Default), vae_name was empty / started with '(' and
_load_vae returned None → FileNotFoundError.

Fix in workflow_generator.py:
- Remove the VAE/CLIP load block that was unconditionally before the
  template/fallback branch.
- Template path: execute_template handles its own VAE/CLIP loading from
  the template JSON values, which are already correct (patch_template
  leaves them untouched when (Default) is selected).
- Hardcoded fallback path: VAE/CLIP are now loaded inside the else block
  with a clear, actionable error message if (Default) is used on a
  family that has no bundled VAE.

Fix in workflow_executor.py:
- Improve the VAE not-found error message to tell the user which file
  was expected and where to put it.
2026-04-11 19:39:53 +00:00
FranckyB 30428e3e20 improve: per-family VAE/CLIP compatibility filtering
- Add vae_exact field: exact basename match (prevents ae.safetensors
  matching files like mae.safetensors via substring)
- Add clip_exclude field: disqualifies files matching any exclude pattern
  even when an include pattern also matches (e.g. umt5_xxl contains 't5xxl'
  substring but is excluded from flux1/ltxv via 'umt5' in clip_exclude)
- Add clip_exact field: exact basename match for CLIPs (reserved for future use)

Updated list_compatible_vaes() and list_compatible_clips() to apply
the new fields in priority order (exact → include patterns, with excludes
checked first for CLIPs).

Family-by-family changes:
- flux1:         vae_exact=[ae.safetensors]; clip_exclude=[umt5,clip_g,qwen,gemma]
- flux2:         vae removes ae.safetensors (wrong VAE); clip_exclude=[t5xxl,umt5,clip_l,clip_g,gemma]
- zimage:        vae_exact=[ae.safetensors]; clip narrows to qwen_3_4b only; clip_exclude expanded
- wan_image/i2v/t2v: clip_exclude=[t5xxl,clip_l,clip_g,qwen,gemma]; adds umt5-xxl pattern
- ltxv:          adds ltxv_vae pattern; clip_exclude=[umt5,clip_l,clip_g,qwen,gemma]
- sdxl:          adds vae-ft-mse pattern; clip_exclude=[t5xxl,umt5,qwen,gemma]
- sd15:          expands vae patterns; clip_exclude=[clip_g,t5xxl,umt5,qwen,gemma]
- qwen_image:    clip_exclude=[qwen_3,t5xxl,umt5,clip_l,clip_g,gemma]
2026-04-11 19:34:59 +00:00
FranckyB b171e97a08 fix: preserve user state on execute, VAE/CLIP always (Default) on family switch
BUG 1 — Reset on first execution (manual mode):
  Python was sending ui_info.extracted with the raw empty 'extracted' dict
  (model_a='', positive_prompt='', etc.) instead of the effective values the
  user had set.  In JS the pre-update handler hit sourceChanged=true (since
  prev was null), wiped _weOverrides, and called updateUI() — erasing the
  user's model and prompt.

  Fix (Python): build effective_sampler / effective_resolution / effective_vae /
  effective_clip by merging 'overrides' on top of 'extracted', then send those
  in ui_info so JS always sees what the user actually has set.

  Fix (JS pre-update + onExecuted): when use_workflow_data is OFF, never reset
  UI fields.
  - First execution (no _weExtracted yet): seed _weExtracted with effective info
    but do NOT call updateUI() — user values are already in the DOM.  Just sync
    the family selector and WAN visibility.
  - Subsequent executions: only update metadata (availability, LoRA list) same
    as before.

BUG 2 — VAE/CLIP auto-selected on family change:
  onFamilyChanged was passing d.recommended to reloadGroupedSelect, which
  silently pre-selected a VAE/CLIP file when switching families.  Since all
  families now have workflow templates that embed the correct VAE/CLIP, the
  dropdown must always land on (Default) = empty string so the template value
  is used.

  Fix: always pass null as recommendedValue in reloadVae / reloadClip.
2026-04-11 19:25:36 +00:00
FranckyB 866ca71053 feat: template-driven execution engine + WAN split + collapsible UI
- workflow_executor.py: new in-process template execution engine
  - load_template() / patch_template() / execute_template()
  - WAN Video i2v latent via WanImageToVideo node
  - Dual-step math: total=high+low, high=[0..H], low=[H..100]
  - loras_to_text() for PromptApplyLora JSON serialisation

- workflow_families.py: split wan → wan_image / wan_video_i2v / wan_video_t2v
  - Added FAMILY_WORKFLOW_STEMS mapping family keys to api/ file stems
  - Sampler strategy: wan_image → single KSampler, wan_video → dual KSamplerAdvanced

- tools/convert_to_api.py: UI JSON → API JSON conversion script (8 workflows)

- workflows/api/: 16 new files (api.json + map.json) for:
  flux_1, flux_2, qwen_image, sdxl, wan_image, wan_video_i2v, wan_video_t2v, z_image

- workflow_generator.py:
  - execute() now uses template-driven path first (load_template → patch → execute_template)
  - Falls back to hardcoded samplers when no template exists (sd15, ltxv)
  - Added source_image optional param for WAN i2v
  - Added steps_high / steps_low override parsing from JS
  - Strategy check updated: wan → wan_video for both i2v and t2v

- workflow_generator.js:
  - makeSection(): collapsible with chevron toggle, all start collapsed
  - updateWanVisibility(): handles wan_image / wan_video_i2v / wan_video_t2v
  - Steps (High) / Steps (Low) rows added to SAMPLER section (WAN Video only)
  - Standard Steps row hidden when WAN Video family selected
  - LoRA Stack A title: 'LoRA Stack (High)' for WAN Video, 'LoRA Stack' otherwise
  - LoRA Stack B: visible only for wan_video_i2v / wan_video_t2v
  - Model B row: visible only for WAN Video families
  - syncHidden(), applyOverrides(), updateUI() updated for steps_high/steps_low
  - Section _setNode() wired up after _weRecalc is defined
2026-04-11 19:02:59 +00:00
THE_BEAST\me 3aa373be3b Modified Prompt Apply Lora, so it can take text enties, either traditional Lora list, or simply path to loras on disk. For Testing Lora generation.
Added new workflows for video and image processing
2026-04-11 14:11:01 -04:00
THE_BEAST\me 1db335d88b refactor: improve code readability by restructuring try-except blocks and formatting print statements 2026-04-11 12:03:56 -04:00
THE_BEAST\me ec4cf272ce feat: enhance prompt extraction and workflow generation with A1111 parameter mapping and embedded data handling 2026-04-11 06:48:59 -04:00
THE_BEAST\me 2e195cfa01 feat: implement update functionality to pull data from connected sources in WorkflowGenerator 2026-04-11 04:26:08 -04:00
THE_BEAST\me 2a3ed8c52c fix: adjust minimum width for DOM widget to improve layout consistency 2026-04-11 02:28:22 -04:00
THE_BEAST\me 41cdfa16c3 feat: add critical rules for DOM widget sizing and resizing in ComfyUI 2026-04-11 02:15:18 -04:00
THE_BEAST\me 7b87283fcd feat: improve UI responsiveness by pushing updates before generation and enhance error handling during model loading 2026-04-11 02:09:40 -04:00
THE_BEAST\me e9d0797d67 feat: enhance model loading and workflow generation with improved handling of workflow_data and LoRA inputs 2026-04-11 01:03:41 -04:00
THE_BEAST\me bfa92d7007 feat: enhance workflow data handling with model and LoRA availability checks 2026-04-11 00:27:24 -04:00
THE_BEAST\me 1c12d99a33 Add LoRA utility functions for fuzzy matching and path resolution
- Implemented functions to retrieve available LoRA files and normalize path separators.
- Added fuzzy matching logic to handle renamed LoRAs and WAN-related tokens.
- Created functions to strip file extensions, normalize names, and resolve LoRA paths.
- Enhanced compatibility with ComfyUI's folder structure for loading LoRAs.
2026-04-10 22:42:49 -04:00
THE_BEAST\me 173b2aceed feat: add workflow extraction utilities for ComfyUI Prompt Manager
- Implemented shared extraction helpers for sampler parameters, VAE info, CLIP info, resolution, and model resolution.
- Added functions to extract sampler parameters, VAE loader information, CLIP loader information, and image/video resolution.
- Introduced model name resolution functions for models, VAEs, and CLIPs.
- Created a comprehensive extraction function to gather all generation parameters from various file types.
- Included a function to enrich extraction results with availability flags for LoRAs, models, VAE, and CLIP.
- Built a simplified workflow data structure for use in WorkflowGenerator and PromptExtractor nodes.
2026-04-10 17:48:05 -04:00
FranckyB a0a886c8a8 fix: Klein CLIPType.FLUX2 shape mismatch + model caching
workflow_families.py:
- flux2 family: replace wrong clip list (mistral/clip_l) with correct
  Qwen encoders (qwen_3_4b, qwen_3_8b) per official ComfyUI Klein docs
- Add clip_type: "flux2" to flux2 family spec for fallback when
  extracted workflow doesn't carry a CLIPLoader type field

workflow_extractor.py:
- _load_clip: check 'flux2' BEFORE 'flux' when mapping to CLIPType —
  'flux2' contains 'flux' so the old order always picked CLIPType.FLUX,
  causing the 2048x15360 vs 12288x4096 shape mismatch with Klein's
  Qwen text encoder. CLIPType.FLUX2 is now correctly used for flux2.
- _load_clip call site: if extracted clip has no type, fall back to the
  family spec's clip_type (flux2 family -> 'flux2' -> CLIPType.FLUX2)
- WorkflowGenerator.__init__: add _model_cache dict keyed by
  (full_path, family_key) so models are only loaded from disk once per
  node instance — subsequent generations with the same model reuse the
  cached patcher, matching how standard ComfyUI loader nodes behave
2026-04-10 18:34:01 +00:00
FranckyB 7c4c1f9172 fix: Klein weights_only error + remove Extract button
workflow_extractor.py:
- _load_model_from_path: wrap load_diffusion_model in try/except;
  on weights_only/UnpicklingError (PyTorch >= 2.6 with .pt/.bin Klein
  models), retry with torch.load(weights_only=False) + load_diffusion_
  model_state_dict. Safe since these are trusted local model files.

workflow_extractor.js:
- Remove 'Extract Parameters' button — extraction runs automatically
  on image select, the manual button is redundant
- Remove EXTRACT_BTN_H constant and its contribution to recalcHeight
2026-04-10 18:23:56 +00:00
FranckyB 5224d650e8 fix(workflow-extractor): allow preview expansion + add 4px bottom padding
- computeSize now uses Math.max(node.size[1], _domH+NATIVE_H) so ComfyUI's
  live generation preview can expand the node without being clamped back
- PADDING 16 → 20 to add 4px breathing room at the bottom of the UI
2026-04-10 18:12:52 +00:00
FranckyB 02246e0612 fix(workflow-extractor): remove statusEl + guard computeSize to fix chin
Three changes to eliminate the 'chin' (node growing blank space at bottom
when mouse moves over it):

1. Remove statusEl entirely — it had minHeight:14px that always added space
   even when empty, slightly distorting the constant-based height math.
   Also removes STATUS_H (18px) from recalcHeight calculation.

2. Add no-op guard in recalcHeight: skip setSize when computed height
   hasn't changed (h === _domH). Prevents spurious setSize calls that
   trigger LiteGraph redraws on mouse enter/leave hover state changes.

3. Override node.computeSize to always return the exact stored _domH
   (not the LiteGraph-derived value). LiteGraph calls computeSize on
   every render frame to check node dimensions — the old impl called
   _origComputeSize which may return a slightly larger value due to
   widget spacing math, causing the node to grow one pixel at a time
   on each frame triggered by onMouseMove's setDirtyCanvas call.
2026-04-10 18:04:39 +00:00
FranckyB 323ece55e8 revert(workflow-extractor): restore original recalcHeight, keep onExecuted
Revert JS height calculation to the proven constant-based approach from 516a226.
The scrollHeight and offsetHeight experiments both caused node collapse.

Kept: onExecuted handler (routes generated image into _weThumbEl, blocks
ComfyUI's default preview injection below the node).
2026-04-10 17:57:47 +00:00
FranckyB 2419567353 fix(workflow-extractor): fix chin/gap — offsetHeight per child + guard against no-op setSize
Two issues:
1. Manual constant math (SEC_HEAD_H, BTN_H, etc.) was overcounting because
   section wrap has marginTop:2px which is outside offsetHeight but still
   consumed space, and flex gap interacts with it unpredictably.

   Fix: iterate root.children, use child.offsetHeight (accurate, not constrained
   by parent), count visible children for gap math. Simple and correct.

2. recalcHeight() calling setSize() even when nothing changed caused ComfyUI
   to re-layout the node on every click/focus, which could expand the node
   slightly each time (the 'chin' effect).

   Fix: only call setSize when newH !== _domH.
2026-04-10 17:55:06 +00:00
FranckyB 2ce93a326a fix(workflow-extractor): fix node shrink loop — compute height from children not root
root.scrollHeight causes a feedback loop: ComfyUI constrains root's height,
scrollHeight shrinks, we report smaller, ComfyUI shrinks more → node collapses.

Fix: compute _domH by summing the intrinsic heights of our own child elements
(button + sections + status + thumb). sec._body.scrollHeight IS reliable
because those inner elements are not constrained by ComfyUI.

_domH is the authority — computeSize returns it directly, never root.scrollHeight.
2026-04-10 17:45:06 +00:00
FranckyB 32400171de fix: gap below KSampler + shared workflow_data format for both nodes
js/workflow_extractor.js:
- Replace manual constant-based recalcHeight() with root.scrollHeight
  (source of truth — no more HEADER_H / EXTRACT_BTN_H / STATUS_H / PADDING guessing)
- Same in domW.computeSize and node.computeSize — all read root.scrollHeight
- Add onExecuted handler: intercepts ComfyUI's auto-preview injection,
  routes generated image into our own _weThumbEl, prevents gap below node

py/workflow_extractor_utils.py:
- Add build_simplified_workflow_data() — shared function that builds the
  canonical workflow_data dict schema (same output from both nodes)

nodes/workflow_extractor.py:
- Remove local _build_simplified_workflow_json (replaced by shared util)
- Import and use build_simplified_workflow_data from py/

nodes/prompt_extractor.py:
- Replace raw JSON dump with call to extract_sampler_params / extract_vae_info
  / extract_clip_info / extract_resolution + build_simplified_workflow_data
- PromptExtractor now outputs workflow_data in identical format to WorkflowGenerator
  (can be used as input to PromptManagerAdvanced to save entire workflows)
2026-04-10 17:33:18 +00:00
FranckyB 516a226f5f fix: correct node name prefix + rename metadata_json to workflow_data
- js/workflow_extractor.js: fix extension name from FBnodes.WorkflowGenerator
  to WorkflowGenerator (matches all other nodes in this package)
- nodes/prompt_extractor.py: rename output metadata_json -> workflow_data
  in RETURN_NAMES and all references in extract(), so both PromptExtractor
  and WorkflowGenerator output the same workflow_data type
2026-04-10 17:11:15 +00:00
FranckyB d6a75f2d70 refactor(workflow-extractor): rename to WorkflowGenerator + major refactor
- Rename node class WorkflowExtractor → WorkflowGenerator
- Remove WorkflowManager and WorkflowGenerator nodes (js + py + __init__)
- Set node creation width to 450px
- Rename workflow_json → workflow_data in RETURN_NAMES and execute()
- Fix INPUT_TYPES: source_folder defaults None, image defaults (none)
- Fix list-files endpoint: JS now calls /workflow-extractor/list-files
- Fix image source filter: input-only at startup (like PromptExtractor)
- Add standalone mode: execute() works without an image using defaults
- Remove denoise from UI; always force 1.0 in execute()
- Update __init__.py registrations
2026-04-10 17:00:35 +00:00
FranckyB 84bf5065d9 fix(workflow-extractor): replace broken Flux2Scheduler with BasicScheduler('beta')
Flux2Scheduler.execute(cls, steps, width, height) is a dimension-based class
method that cannot be called as an instance with get_sigmas() — it has no such
method. Replace the entire Flux2Scheduler usage with BasicScheduler using the
'beta' schedule, which is the correct programmatic equivalent for Flux2/Klein.
Scheduler name is read from sampler_params so extracted workflows pass it
through; defaults to 'beta'.
2026-04-10 16:44:17 +00:00
FranckyB 9ec65b7d8b fix(workflow-extractor): true gap fix via marginTop -10px + green/red workflow status dot
- Gap: root element now uses marginTop:-10px (same technique as Prompt Manager
  button container) to cancel the ~10px ComfyUI injects above every DOM widget.
  Removed the previous padding-toggle approach which was fighting the wrong cause.
- Status dot: green/red circle in title bar (identical to Prompt Extractor).
  Shows as soon as an image is selected. Green = workflow found after Extract,
  red = no workflow found or extract failed. Dot is restored from cache on page
  reload. Triangle shifts left 24px to make room when dot is visible.
2026-04-10 16:33:12 +00:00
FranckyB 08d21b0961 fix(workflow-extractor): thumbnail gap, VAE/CLIP filtering + recommended, thumb restore on refresh
- Fix 1: root padding changed to '0 6px 6px 6px'; loadThumbnail toggles
  paddingTop via node._weRoot so thumb sits flush under Browse Files button
- Fix 2: reloadGroupedSelect now prepends (Default)/value='' for VAE/CLIP rows;
  onFamilyChanged uses reloadVae/reloadClip helpers that fetch recommended from
  API and auto-select best matching file on disk
- Fix 3: list_compatible_vaes/clips gain return_recommended param; endpoints
  return {vaes/clips: [...], recommended: str|null} for first pattern match
- Fix 4: onConfigure calls loadThumbnail(node, img) on refresh when thumb not
  already loaded, restoring the preview after page reload
2026-04-10 16:00:14 +00:00
FranckyBandClaude Opus 4.6 e7c727f102 fix(workflow-extractor): thumb gap, node height, Model A/B, LoRA stacks match PMA UI exactly
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 15:26:07 +00:00
FranckyBandClaude Opus 4.6 639091fd17 fix(workflow-extractor): wider node, video thumbnail, preview arrow, checkpoint B, VAE/CLIP defaults
- Node width 440→560 to fit LoRA tags properly
- loadThumbnail: video-aware (browser canvas + server fallback via /video-frame API)
- Add /workflow-extractor/video-frame Python endpoint (PyAV + ffmpeg fallback)
- Preview arrow in title bar (triangle icon) → opens image/video modal on click
- Checkpoint B always visible (shows '(none)' when source has no model B)
- VAE/CLIP dropdowns: show '(Default)' sentinel instead of '—', lazy-load filters by family
- Family change reloads model B dropdown unconditionally

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 15:00:25 +00:00
FranckyB 977ec9785b refactor: slim down model families, fix sampling strategies per family
- Merge Flux1 variants (dev/schnell/generic) into single 'flux1' family
- Merge Flux2/Klein variants into single 'flux2' family
- Merge SDXL/Pony/Illustrious/SDXLTurbo into single 'sdxl' family
- Merge Z-Image Base/Turbo into single 'zimage' family
- Remove: SD2, SD3, SD3.5, CogVideo, Mochi, HunyuanVideo, Stable Cascade, Kolors, PixArt, AuraFlow
- LTX-Video: correct sampler strategy to flux (SamplerCustomAdvanced)
- WAN: add ModelSamplingSD3 shift=5.0 before dual KSampler passes
- Flux2/Klein: add _run_flux2_sampler() using Flux2Scheduler + CFGGuider
- Fix node sizing: NATIVE_H 104→108 (LiteGraph title bar is 30px not 26px)
- Update PADDING 20→26 to account for flex gaps between sections
2026-04-10 14:30:40 +00:00
FranckyB ca06e1273b feat: add WorkflowManager + WorkflowGenerator nodes, shared py/ layer, family-aware sampling
- Add py/workflow_families.py: MODEL_FAMILIES dict with sampler strategy per family
  (standard, flux, flux2, wan), compatibility groups, model/VAE/CLIP listing helpers

- Add py/workflow_extractor_utils.py: shared extraction helpers used by WorkflowExtractor
  and WorkflowGenerator (extract_sampler_params, extract_vae_info, extract_clip_info,
  extract_resolution, resolve_model_name, resolve_vae_name, resolve_clip_names,
  extract_all_from_file, enrich_with_availability)

- Add py/workflow_node_utils.py: thin re-export of build_node_map/build_link_map

- Refactor nodes/workflow_extractor.py: import from py/, family-aware sampling strategies
  (_run_standard_ksampler, _run_flux_sampler, _run_wan_sampler), WORKFLOW_JSON as
  third output (IMAGE, LATENT, STRING)

- Add nodes/workflow_manager.py: WorkflowManager node - big brother of PM Advanced,
  adds workflow_config key to shared JSON store, outputs prompt + lora_stack_a/b + WORKFLOW_DICT

- Add nodes/workflow_generator.py: WorkflowGenerator node - accepts WORKFLOW_DICT from
  WorkflowManager or manual config, family-aware sampling, outputs IMAGE + LATENT + WORKFLOW_JSON,
  supports WAN dual-sampler, Flux, Flux2, Standard strategies

- Add js/workflow_manager.js: DOM widget panel with family selector, model A/B dropdowns,
  VAE, CLIP, sampler + resolution overrides, Save Config button, state in node.properties

- Add js/workflow_generator.js: status badge (auto vs manual mode), generation feedback

- Patch nodes/prompt_manager_advanced.py: preserve guard in save_prompt_advanced() copies
  any unknown keys (e.g. workflow_config) back into prompt_data so WorkflowManager data
  survives edits from PM Advanced

- Update __init__.py: register WorkflowManager + WorkflowGenerator, bump version to 1.23.0
2026-04-10 13:53:10 +00:00
THE_BEAST\me c2c38e5b9d Merge branch 'dev' of https://github.com/FranckyB/ComfyUI-Prompt-Manager into dev 2026-04-10 08:41:16 -04:00
THE_BEAST\me 6ddf0108be fix: improve LoRA application logic and adjust latent tensor creation parameters 2026-04-10 08:40:04 -04:00
THE_BEAST\me 52990491f3 Improved Tab Switching Code 2026-04-09 21:19:33 -04:00
THE_BEAST\me 3a49fdfa97 First Wip of Workflow Extractor 2026-04-09 15:55:11 -04:00
THE_BEAST\me b98155543b feat: enhance extracted data handling in PromptExtractor and add validation tests 2026-04-08 00:27:17 -04:00
THE_BEAST\me 74716182ce feat: enhance model resolution logic in PromptModelLoader and PromptExtractor 2026-04-07 23:55:44 -04:00
Francois Beaudry d7adb9f5c0 Merge pull request #24 from FranckyB/dev
feat: enhance PromptExtractor to support embedded data extraction and model tracking
2026-04-07 22:28:17 -04:00
THE_BEAST\me c8e103152b feat: enhance PromptExtractor to support embedded data extraction and model tracking 2026-04-07 22:17:40 -04:00
Francois Beaudry 1c3aa77889 Merge pull request #23 from FranckyB/dev
Dev
2026-04-07 01:09:53 -04:00
THE_BEAST\me 501b962408 feat: add thumbnail generation feature in Prompt Manager
- Implement right-click option to generate thumbnails for prompts
- Introduce checkpoint selection for thumbnail generation
- Enhance API endpoints for listing checkpoints and resolving LoRAs
- Update version to 1.22.5
2026-04-07 01:07:05 -04:00
THE_BEAST\me 34df0b0675 fix: enhance prompt extraction logic for low and high model detection 2026-04-06 22:49:01 -04:00
THE_BEAST\me a7bdec56d3 - **Prompt Model Loader Improvements**
- Added GGUF model support via runtime detection of [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) extension
  - Visual model type badge (Checkpoint/Diffusion/GGUF/NOT FOUND) and model name displayed on the node
  - CLIP and VAE output slots automatically hidden for non-checkpoint models
  - State persistence: model info and output slot visibility survive tab switches and workflow reloads
  - Graceful error handling: shows red "NOT FOUND" badge instead of crashing on missing models
  - Searches `unet_gguf` folder paths registered by ComfyUI-GGUF
2026-04-06 21:58:36 -04:00
THE_BEAST\me 41e4c27416 fix: reorder return names in PromptExtractor for consistent output structure 2026-04-06 02:24:16 -04:00
THE_BEAST\me c34fda023c - **New Node: Prompt Model Loader**
- Loads checkpoints or diffusion/UNET models from a string path (output by Prompt Extractor)
  - Auto-detects model type: checkpoints return MODEL + CLIP + VAE, diffusion models return MODEL only
  - Searches ComfyUI checkpoints, diffusion_models, and unet folders automatically
  - Optional weight dtype selection for memory optimization

- **Model/Checkpoint Extraction in Prompt Extractor**
  - Extracts checkpoint and UNET model paths from workflow metadata
  - High/Low (A/B) model assignment for dual-model workflows (e.g., Wan video with different models per noise level)
  - Resolves extracted model names to local file paths using ComfyUI's folder system
  - Supports 11+ model loader types: CheckpointLoaderSimple, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub (dual high/low), and more
  - New `model_a` and `model_b` STRING outputs on the Prompt Extractor node
2026-04-06 02:13:15 -04:00
THE_BEAST\me 6de8bddea5 feat: enhance metadata extraction for JPEG and WebP files in prompt extractor 2026-04-06 00:04:30 -04:00
THE_BEAST\me 1fea03858e refactor: rearrange and update images in README for Prompt Generator usage 2026-04-05 15:53:10 -04:00
THE_BEAST\me 16c01efb0d raise RuntimeError for error handling 2026-04-05 05:52:58 -04:00
THE_BEAST\me f9b7c601f9 prompt extractor:
enhance video thumbnail extraction and error handling for unsupported formats

Prompt Generator:
Improve llama-server startup handling and fix docstring
- Increase server startup timeout from 30s to 120s for large models
- Detect early server crashes and show stderr output to user
- Fix _get_model_keywords docstring to reflect version preservation (qwen3.5)
2026-04-05 05:10:32 -04:00
THE_BEAST\me cb6276ded0 Updated workflow 2026-04-02 12:40:38 -04:00
THE_BEAST\me 894f44d4b5 - **Speed Improvement**: Thumbnail generation now uses server-side PyAV instead of browser-based video decoding — substantially faster, especially with many clips. 2026-04-01 02:16:51 -04:00
THE_BEAST\me 7e1a45fa3c feat: update version to 1.21.1 and fix issues caused by restructure 2026-04-01 00:02:12 -04:00
THE_BEAST\me 616746e07f feat: enhance video frame extraction with server-side fallback for H265/yuv444 formats and update prompts path resolution 2026-03-31 23:32:25 -04:00
THE_BEAST\me 4cdb3a0d68 ### version 1.21.0
- **Removed miscellaneous tools** — Switch Any, Save Video H26x, Apply LoRA Stack, Better Image Loader, and Animated Latent Preview have been moved to a dedicated repository: [ComfyUI-FBnodes](https://github.com/FranckyB/ComfyUI-FBnodes)
- **Project restructure** — Organized node files into `nodes/` and utility modules into `py/` for cleaner codebase
2026-03-31 23:16:02 -04:00
THE_BEAST\me c4eb347b56 feat: enhance video metadata extraction to support source folder selection and refresh file list for output 2026-03-28 00:06:01 -04:00
THE_BEAST\me 356f3af597 feat: recheck LoRA availability after restoring state and remove unused condition handling in SwitchAny 2026-03-27 19:48:56 -04:00
THE_BEAST\me 9be7636d61 feat: Add Better Image Loader node and enhance Prompt Extractor
- Introduced a new node: Better Image Loader for streamlined image and video loading without metadata extraction.
- Enhanced Prompt Extractor with input/output folder switching and improved file browsing capabilities.
- Updated README to reflect new features and changes.
- Fixed various bugs related to folder switching and file extraction.
- Updated version to 1.20.0 in all relevant files.
2026-03-27 16:33:21 -04:00
THE_BEAST\me 6ddf7321a0 feat: add refresh functionality to SwitchAny node and enable output node for SwitchAnyBool 2026-03-27 15:33:30 -04:00
THE_BEAST\me 0af9387da5 feat: remove thumbnail preview toggle button and associated functionality from thumbnail browser 2026-03-27 14:24:31 -04:00
THE_BEAST\me e08f295c25 feat: enhance file browser modal to open in selected subfolder and scroll to selected file 2026-03-25 11:19:48 -04:00
THE_BEAST\me ae5e46fccc feat: add SwitchAnyBool node for boolean input handling in Switch Any 2026-03-21 16:06:50 -04:00
THE_BEAST\me 32a54c4ff0 feat: introduce Switch Any node with customizable inputs and lazy evaluation support 2026-03-21 13:17:33 -04:00
THE_BEAST\me cca1753f10 feat: prevent overwriting node state on workflow restore by adding configuration flag 2026-03-21 11:38:36 -04:00
THE_BEAST\me 81362756b4 feat: enhance metadata extraction and update return types in PromptExtractor 2026-03-20 11:54:52 -04:00
THE_BEAST\me fb1d32d503 feat: add option to use only connected LoRA inputs, skipping extraction 2026-03-18 21:36:52 -04:00
THE_BEAST\me ea21779258 fix: allow negative values for Lora strength input 2026-03-18 21:18:30 -04:00
THE_BEAST\me 6ad2986746 feat: update to version 1.18.0 with thumbnail hover preview and improved thumbnail quality 2026-03-17 23:36:34 -04:00
THE_BEAST\me e80c5bce0e feat: add option to enable thumbnail hover preview in advanced preferences 2026-03-17 23:30:56 -04:00
THE_BEAST\me 88f2e1b109 feat: enhance thumbnail preview system and improve image resizing logic 2026-03-17 09:36:03 -04:00
THE_BEAST\me 6aa194ff95 fix: error in variable when logging error 2026-03-16 01:04:28 -04:00
THE_BEAST\me 3731b4c228 feat: add context menu for video thumbnails with refresh option and reset frame position on new video selection 2026-03-10 02:07:46 -04:00
THE_BEAST\me 8062ede1cd feat: update to version 1.17.6 with LoRA stack output swapping and input handling fixes 2026-03-08 21:22:48 -04:00
THE_BEAST\me 7496c8fd65 fix: streamline LoRA input handling by preserving saved loras from presets 2026-03-08 21:13:01 -04:00
THE_BEAST\me f82ff068e1 feat: add swap functionality for LoRA outputs in prompt manager
fix: Issue with disabling loras, when no lora input is used.
2026-03-08 21:04:15 -04:00
THE_BEAST\me 1029c79881 feat: added back delete prompt functionality to the dropdown menu with confirmation dialog 2026-03-08 16:50:31 -04:00
THE_BEAST\me f20af63926 fix: set default category selection in prompt dialog after DOM build 2026-03-08 16:36:44 -04:00
THE_BEAST\me 82b19c71de fix: tweaked LoRA configuration retrieval by using last-executed state from backend. 2026-03-08 16:22:46 -04:00
THE_BEAST\me 76c30404a8 feat: enhance latent preview initialization handling and improve model identity extraction logic 2026-03-07 18:36:52 -05:00
THE_BEAST\me 10cb9d2bb0 feat: add rename and move prompt functionality to context menu and API 2026-03-07 12:48:44 -05:00
165 changed files with 65084 additions and 11054 deletions
+50
View File
@@ -0,0 +1,50 @@
# Normalize all text files to LF in the repository.
# Working-tree endings are controlled by each machine's core.autocrlf setting;
# the repo always stores LF so Windows/Linux checkouts stop showing phantom diffs.
* text=auto
# Source files: always LF (in repo and on disk)
*.py text eol=lf
*.js text eol=lf
*.json text eol=lf
*.md text eol=lf
*.toml text eol=lf
*.txt text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.cfg text eol=lf
*.ini text eol=lf
*.css text eol=lf
*.html text eol=lf
*.sh text eol=lf
# Windows-only scripts keep CRLF
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# Binary files: never convert
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.ico binary
*.mp4 binary
*.webm binary
*.mkv binary
*.mov binary
*.avi binary
*.mp3 binary
*.wav binary
*.flac binary
*.safetensors binary
*.ckpt binary
*.pt binary
*.pth binary
*.bin binary
*.onnx binary
*.af binary
*.pyc binary
*.pdf binary
*.zip binary
+2
View File
@@ -3,6 +3,7 @@ __pycache__/
*.pyc
*.pyo
*.pyd
.venv/
.Python
build/
develop-eggs/
@@ -19,6 +20,7 @@ wheels/
*.egg-info/
.installed.cfg
*.egg
test/
# VS Code history extension
.history/
+158 -469
View File
@@ -1,118 +1,161 @@
# ComfyUI Prompt Manager
## A comprehensive prompt toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, and Extract prompts with full LoRA support.
## A comprehensive prompt and recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
A complete prompt management solution featuring three core capabilities:
ComfyUI Prompt Manager is a prompt toolkit for ComfyUI. It helps you manage, save, and reuse prompts along with their LoRAs and trigger words. It can generate prompts using a local LLM through llama.cpp or Ollama, or generate them directly with ComfyUI’s own CLIP/text encoders. It also extracts metadata from images, videos, and JSON files, so you can turn them into reusable prompts — and the **Prompts** sidebar and save/load tools keep everything organized.
**Prompt Manager** — Save and organize prompts with categories, simple UI with minimal feature.
[See Installation Guide](#installation)
**Prompt Manager Advanced** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Will also remap Loras if path differs.
[See Node Reference](docs/feature-reference.md)
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
[See Prompt Composer](#prompt-composer)
**Prompt Extractor** — Extract prompts and LoRA configurations from existing images, videos, or JSON workflow files. Will extract first frame from any video. Automatically parses embedded metadata and outputs active LoRA as Lora stacks. When used in conjunction with Prompt Manager Advanced, Loras will be automatically found if available, regardless of path. For those that aren't, right click offers the option to look for them on Civitai.
___
## What This Provides
- **Prompt Manager**:
- For saving and loading Prompts.
- These saved prompts can include LoRA stacks, trigger words, as well as thumbnails.
- **Prompt Generator**:
- To run a local LLM (llama.cpp or Ollama), or directly use ComfyUI's CLIP/text encoders.
- Also supports image analysis when using Vision Capable models.
- **Prompt Composer**:
- For building prompts from reusable prompt fragments such as attire, expression, action, style, ambience, and more.
- Supports the v2 Prompt Composer library format with thumbnails, prompt groups, subject-aware group behavior, LoRAs, RefMods, random multi-prompt selection, and video/image composition modes.
- **Prompt Extractor**:
- Read metadata from images/videos/JSON and output the prompt and LoRAs they use.
- **Lora Preview integration**:
- When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
- **Advanced media loading**:
- Extractor nodes can also act as advanced image loaders, but I'd recommend [FBNodes](https://github.com/FranckyB/ComfyUI-FBnodes) for better solutions.
- **And more**:
- See the [Reference guide](docs/feature-reference.md) for a complete list.
---
<div align="center">
<figcaption>Simple Prompt Generator Usage</figcaption>
<img src="docs/prompt_manager.png" alt="Prompt Manager">
<figcaption>Prompt Creation With Lora and Trigger Words</figcaption>
<img src="docs/images/prompt_generator_text.png" alt="Prompt Manager">
</div>
<div align="center">
<figcaption>Advanced Prompt Generator Usage</figcaption>
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
<figcaption>Generating Prompts based on Images</figcaption>
<img src="docs/images/prompt_generator_image.png" alt="Prompt Generator">
</div>
<div align="center">
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
<figcaption>Advanced Prompt Generation using Multiple Images</figcaption>
<img src="docs/images/prompt_generator_advanced.png" alt="Prompt Generator">
</div>
<div align="center">
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
<figcaption>Recipe extraction and modification (Adding a Style LoRA)</figcaption>
<img src="docs/images/workflow_builder.png" alt="Recipe Builder">
</div>
### Key features:
### Prompt Manager:
- **Category Organization**: Create and manage multiple categories to organize your prompts
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
### Prompt Manager Advanced:
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and Trigger word integration
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs, can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
<div align="center">
<figcaption>Easily find saved Prompts & Recipes using the Built-in File Browser</figcaption>
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
</div>
### Prompt Apply LoRA:
- **Simple LoRA Application**: Takes a LORA_STACK and applies it to your model/clip
- **Works with Any Stacker**: Compatible with LoRA Manager's stacker or any node outputting LORA_STACK
- **Optional CLIP**: CLIP input is optional for workflows that don't need it
## Toolset Overview
### Prompt Extractor:
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
- **Wide Node Compatibility**: Supports extraction from CLIP Text Encode, various sampler nodes, and LoRA stackers including Power Lora Loader
- **Preview in Manager**: View extracted data and repathed loras using Manager Advanced.
### Prompt Toolset
### Prompt Generator
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
- **Custom Image Analysis**: Provide your own instructions for image analysis
- **JSON Output**: Optional structured JSON output with scene breakdown
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
- Prompt Manager: Supports Prompts, LoRA stacks, trigger words and thumbnail for workflows.
- Prompt Manager (Basic): Simple no-frills basic version (The OG).
- Prompt Generator: prompt creation and enhancement using llama.cpp, Ollama, or a connected ComfyUI CLIP/text encoder.
- Prompt Extractor: Reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
- Prompt Composer: Build prompts from reusable fragments, with random prompt groups, subject-aware composition, LoRA/RefMod support, and image/video generation modes.
- Prompt Layout Builder: Draw boxes over a scene prompt (or load them from an LLM) and output a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
- Prompt Library Hub (sidebar **Prompts** button, can be hidden in Settings): browse, edit, import and export System Prompts, Prompt Snippets, and Saved Compose / Prompts / Layouts / Recipes from one panel, with per-category export.
### Prompt Generator Options
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
- **Custom Instructions**: Override default system prompt for different enhancement styles.
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
- **Console Debugging**: Enable outputing the entire process to the console for debugging purposes.
### Recipe Toolset (Experimental)
These tools were an experiment, with some of the tech now used in other parts of the add-on.
- Recipe Extractor: normalizes extracted metadata into reusable `manager_data`.
- Recipe Builder: edit and validate recipe data in a cleaner authoring surface.
- Recipe Renderer: execute recipe data through built-in generation templates.
- Recipe Hub: merge/append model blocks into one `manager_data` and expose each model block as its own output.
- Recipe Relay: edit one model block (`model_data`) with seed and LoRA stack overrides.
- Recipe Model Loader: resolve and load models from recipe data.
- Save and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
### Preference Options
- Set choices for prefered Model for both base mode and vision model.
- Set new default model location, previous folder (gguf and llm) will still be scanned, but model will save in new default.
- Set custom Location for Llama.cpp. If Llama.cpp was not added to the system Path, this option let's you specify it's location.
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
## Workflow Examples
### Save Video H264/H265
- **Codec Selection**: Choose between H.264 (8-bit, better compatibility) or H.265/HEVC (10-bit, better compression and gradients)
- **Chroma Subsampling**: Select yuv420 (most compatible), yuv422 (better for video editing), or yuv444 (best color, no chroma loss)
- **Quality Control**: Constant Rate Factor (CRF) from 0-51 for fine-tuned quality vs file size balance
- **Preview Mode**: Quick preview encoding to temp folder without saving to output
- **Save Latent**: Optionally save the latent alongside the video for later experimentation without regeneration
- **Audio Support**: Preserves audio from VIDEO input with proper sync
- **Workflow Metadata**: Embeds full workflow metadata in MP4 (unlike VideoHelperSuite which strips it from audio clips)
- **Browser Preview**: Automatically generates browser-compatible preview for H.265 + yuv422/444 combinations
Workflow examples are provided to help understand the basics.
### Animated Latent Preview
- **Video Sampling Preview**: Display animated previews during KSampler execution for video models
- **TAESD Support**: Works with both Latent2RGB and TAESD preview methods (including high-quality video TAESD)
- **Auto Frame Rate**: Automatically detects optimal playback rate based on video model (Wan, Mochi, LTXV, HunyuanVideo, etc.)
- **Manual Rate Override**: Optional playback rate override in preferences
- **VHS Compatible**: Automatically defers to VideoHelperSuite if installed to avoid conflicts
## Preferences And Settings
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and more.
- If you want the Prompt Generator dropdowns to show only your local models, enable `Hide downloadable built-in models` in these settings.
- Prompt Generator backend choices (llama.cpp, Ollama) and related options are configured there.
- The Prompt Generator's system prompts are fully user-customizable. They're stored in `user/default/prompt_generator_data.json` and can be created and edited with the **Prompt Library Hub** (sidebar) — your custom prompts then show up directly in the Prompt Generator node.
- **Edit / Generate Prompt MiniMax Outpaint** writes a MiniMax H3 Image outpaint prompt: connect the outpaint canvas (the picture on its gray-padded canvas, e.g. Load Image+'s `canvas` with Pad on) and optionally say what you want in the new area. Existing installs get it with the Prompt Library Hub's re-import of the default prompts.
## Documentation
- Detailed node reference: [docs/feature-reference.md](docs/feature-reference.md)
## Prompt Composer
Prompt Composer is a visual prompt builder for assembling full prompts from reusable fragments such as characters, expressions, attire, action, lighting, ambience, style, environment, and camera.
The Prompt Composer library now uses a more flexible v2 format built around prompt groups. This makes it much easier to add new groups, organize categories inside them, keep subject behavior per group, and manage larger prompt libraries without relying on the older flat composer JSON layout.
- Compose output before or after the selected prompt source, or use it on its own.
- Return output as plain text or JSON.
- Works in both image and video modes. The Video mode being formatted for Minimax.
- Prompt fragments can include LoRAs, RefMods, and thumbnails can be generated easily.
- Categories and prompt groups support prompt types, prefixes, and subject behavior for cleaner browsing and formatting.
- Multi-select can become one random pool or multiple separate prompt parts.
- Parts support subject-aware grouping, muting, reordering, merge/split actions, and per-part strength.
- Prompt Browser integration supports direct editing, easy creation of new prompt groups, thumbnail generation, export, open, merge flows for older composer data, and reopen behavior that preserves browser state.
- Includes an extensive collection of style prompts, including styles based on Reddit user Dear-Spend-2865 prompts.
Node-side Prompt Composer controls include:
- Click a fragment to edit or replace it.
- Middle click to mute or unmute a fragment.
- Ctrl-click to select multiple parts, then right-click to merge compatible selections.
- Right-click a merged part to split it back into separate prompts.
- Drag and drop parts to reorder them.
- Adjust fragment strength directly on the card.
### Saving And Reloading Composer Workflows
The **Library Manager** node (formerly Compose Manager, and replacing Recipe Manager) saves and reloads the `manager_data` of **Prompt Manager**, the **Recipe** nodes, **Prompt Composer** and **Prompt Layout Builder**; they all share the `MANAGER_DATA` type. The Prompt Browser marks their entries **P**, **C** and **L** (recipes show under Type: Recipe). Connect Library Manager's `manager_data` to Prompt Composer's `manager_data` input to restore a saved Composer setup.
To restore a saved Composer setup in **Prompt Composer**, use the **second row of toggles** on the node:
- **Sync** rebuilds the Prompt Composer graph from the incoming `compose_data`
- **Prompt** uses the prompt stored in the incoming `compose_data`
- **LoRA** uses the LoRAs stored in the incoming `compose_data`
This allows `compose_data` to take priority over directly connected prompt and LoRA inputs when those toggles are enabled.
<div align="center">
<figcaption>Use Prompt Composer to build prompts from reusable fragments, including random multi-prompt groups.</figcaption>
<img src="docs/images/prompt_composer.jpg" alt="Prompt Composer Example">
</div>
<div align="center">
<figcaption>Edit prompts in the browser, attach LoRAs or RefMods, and generate thumbnails for any prompt.</figcaption>
<img src="docs/images/prompt_browser_ui.png" alt="Prompt Browser Editor">
</div>
## Prompt Layout Builder
Prompt Layout Builder places the parts of an image in boxes: draw them over a scene prompt, or let the Prompt Generator write the layout for you, then output it in the format your model reads.
- Each box is an Object, Character, Text (with the exact words to render) or Panel, with its own description and colors. Box descriptions can come from Prompt Composer snippets.
- **Output** formats:
- **MOSS**: MOSS-Image layout JSON.
- **Ideogram**: Ideogram 4 JSON caption, with background, style, lighting and medium fields.
- **Krea 2**: Krea 2 grounding lines, with style, medium and background, panels, and character tags and IDs to keep a character consistent across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). Its PROMPTING.md covers the prompt format and sampler settings.
- **Use import_json** loads a layout from the Prompt Generator (system prompts **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** in the **Bbox** category, each with Create and From Image versions), from Create Bounding Boxes, or from a layout saved with Library Manager. Turn it off to keep editing the imported boxes.
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types.
See [docs/feature-reference.md](docs/feature-reference.md#prompt-layout-builder) for details.
## Installation
@@ -120,7 +163,6 @@ ___
```
cd ComfyUI/custom_nodes/
```
2. Clone this repository:
```bash
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
@@ -130,389 +172,36 @@ ___
cd ComfyUI-Prompt-Manager
pip install -r requirements.txt
```
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
Windows:
```bash
winget install llama.cpp
```
Linux:
```bash
brew install llama.cpp
```
5. If you have them, place your .gguf models in the models/gguf folder or set in prererences your preferred folder path.
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master):
- Windows:
```bash
winget install llama.cpp
```
This installs the `ggml.llamacpp` package, which ships the official **Vulkan** Windows build (for example `llama-b11946-bin-win-vulkan-x64.zip`), so GPU offload works on NVIDIA / AMD / Intel GPUs with a working Vulkan driver, and falls back to CPU when there is no Vulkan-capable driver.
If you want CUDA instead (needed for the node's GPU device selector, and generally the fastest on NVIDIA), download `Windows x64 (CUDA 12/13)` from the [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases) page, keep its CUDA DLLs next to `llama-server.exe`, and point **Settings → Prompt Manager → 2. Llama Preferences → Custom Llama Path** at that folder.
- Linux:
```bash
brew install llama.cpp
```
Homebrew builds ggml with **Vulkan** and OpenBLAS on Linux (and Metal on Apple Silicon), so GPU offload works there as well. Otherwise build llama.cpp yourself with `-DGGML_CUDA=ON` (or `-DGGML_VULKAN=ON`) and set **Custom Llama Path** to the build folder.
5. Place custom `.gguf` models in models/gguf.
- Or use preferences to set a custom path.
6. Restart ComfyUI.
6. Restart ComfyUI
**Checking that your llama.cpp can use the GPU** — run this in a terminal, using the same path the Prompt Generator resolves (it is printed as `llama-server:` in the console):
## Usage
```bash
llama-server --list-devices
```
### Prompt Manager
If it prints `Available devices:` followed by `CUDA0: ...` or `Vulkan0: ...`, GPU offload works. If it prints `(none)`, that build (or its driver) cannot use your GPU — Prompt Generator will then run the model on CPU and say so at startup.
1. **Add the Node**: Add Node → Prompt Manager
2. **Select a Category**: Use the dropdown to choose from your categories
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
**Using the CLIP/text encoder backend**: No additional setup is needed. Connect any ComfyUI `CLIP` output to the Prompt Generator node's `clip` input. When `clip` is connected, the node bypasses llama.cpp/Ollama and generates prompts directly through the text encoder.
### Prompt Manager Advanced
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
7. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
8. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
### Apply LoRA Stack
1. **Add the Node**: Add Node → Prompt Manager → Apply LoRA Stack
2. **Connect Model**: Connect your model (e.g., from Load Checkpoint) to the `model` input
3. **Connect LoRA Stack**: Connect a `LORA_STACK` output (from Prompt Manager Advanced or LoRA Manager's stacker)
4. **Optional CLIP**: Connect CLIP if your workflow needs it (some video workflows don't)
5. **Use Outputs**: Connect the modified model/clip to your sampler or other nodes
### Prompt Extractor
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
2. **Load Media**: Select an image or video from your input folder or use the upload button to access file from anywhere.
3. **JSON Workflows**: Support extracting from JSON, by importing workflow files directly using the upload button.
4. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
5. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
6. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
### Prompt Generator
**Basic Usage** (assuming a model is present in models\gguf):
1. **Add the Node**: Add Node → Prompt Generator
2. **Select Mode**: Choose from:
- "Enhance User Prompt" - Improve text prompts with LLM
- "Analyze Image" - Generate detailed image descriptions
- "Analyze Image with Prompt" - Analyze images with custom instructions
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
5. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
**Advanced Usage**:
1. **Add the Options Node**: Add Node → Prompt Generator Options
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
**Qwen models found in options**
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
**Model Management**:
- Place gguf files in models/gguf folder
- Downloaded models are also placed in this folder.
**Preferences**:
Preference settings can be found in ComfyUI Settings → Prompt Manager
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
- **Set Default Port** You can set the port used by Llama.cpp
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
### Save Video H264/H265
1. **Add the Node**: Add Node → Prompt Manager → Save Video H264/H265
2. **Connect VIDEO**: Connect a VIDEO output (e.g., from VAE Decode for video models)
3. **Choose Codec**: Select h264 for compatibility or h265 for better quality/compression
4. **Set Quality**: Adjust CRF (18-23 recommended for high quality, lower = better quality but larger files)
5. **Chroma Options**: Use yuv420 for maximum compatibility, yuv444 for best color preservation
6. **Save Latent**: Connect a LATENT input and enable "save_latent" to save the latent alongside your video
7. **Preview Mode**: Set "save" to false for quick preview encoding without saving to output folder
### Animated Latent Preview
1. **Enable in Settings**: Go to ComfyUI Settings → Prompt Manager → 5. Video Sampling
2. **Toggle On**: Enable "Display animated previews when sampling"
3. **Optional Rate**: Set "Playback rate override" to force a specific FPS (0 = auto-detect from model)
4. **Run Video Workflow**: During KSampler execution, you'll see an animated preview of the video being generated
5. **Works with TAESD**: Enable TAESD in ComfyUI preview settings for higher quality previews
**Note**: If VideoHelperSuite is installed and enabled, its latent preview takes priority to avoid conflicts.
**Data Location**
All data generated by the nodes is saved under user/default folder. The data is saved in JSON format and the thumbnail data is also included, saved as base64 data URL. The node creates a backup folder that keeps 5 daily copies in the hope of preventing any mishap. As the node supports exporting the JSON, be safe and make backups from time to time.
## Requirements
- ComfyUI
- Python 3.8+
- requests
- huggingface_hub
- psutil
- tqdm
- Pillow
- colorama
- llama-server (from llama.cpp)
## Troubleshooting
**Problem**: Prompts don't appear in the dropdown
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
**Problem**: Changes aren't saved
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
**Problem**: Can't see LLM output in the node
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
**Problem**: "llama-server command not found"
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
**Problem**: "No models found"
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Option node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
**Problem**: Server won't start
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
**Problem**: Model download fails
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
**Problem**: Generation is slow
- **Solution**: Either, Use a smaller quantized model (Q4 instead of Q8) or toggle 'stop_server_after' to quit llama.cpp after generating prompt.
**Problem**: Default Model used is not what I want
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
## Changelog
### version 1.17.5
- **Browser Context Menu Enhancements**
- Added "Delete Prompt" option to prompt right-click menu in the thumbnail browser
- Added "Delete Category", "Rename Category" options to category right-click menu
- Added "+" button at the end of the category list to create new categories directly from the browser
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
- **Streamlined More Dropdown**
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
### version 1.17.0
- **NSFW Tagging & Filtering**
- Mark entire categories or individual prompts as NSFW
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
- Category buttons show red border for NSFW categories in the thumbnail browser
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
- **List View Mode**
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
- Toggle between grid and list view with a button in the browser controls bar
- View mode preference is session-persistent
- Default view mode configurable in ComfyUI settings
- **UI Improvements**
- Search input moved into the controls bar with a clear (×) button
- Separator line between category buttons and prompt content
### version 1.16.0
- **Ollama Support**
- Added Ollama as an alternative LLM backend alongside llama.cpp
- Auto-discovers available Ollama models when no model is explicitly configured
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
- **Upgraded to Qwen3.5 Models**
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
- Thinking mode is now a runtime toggle — no separate model variant needed
- **mmproj-Based Vision Detection**
- Vision model detection no longer relies on "VL" in the filename
- Models are identified as vision-capable based on the presence of an mmproj file
- Heuristic matching supports user-provided models outside the predefined registry
- Backward compatible with existing Qwen3VL models and their mmproj files
- **Bug Fixes**
- Fixed seed control_after_generate not working (increment/decrement/randomize)
- Improved Prompt Extractor detection logic
### version 1.15.9
- **Bug Fixes**
- Improved Prompt Extractor, enhanced detection logic
### version 1.15.7
- **Added Rename Category Option**
- **Bug Fixes**
### version 1.15.6
- **Video Metadata Reader - VHS Compatible**
- Added capability to read metadata from VideoHelperSuite generated videos.
### version 1.15.5
- **Added get video components+ node**
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
- **Video Preview in Prompt Extractor**
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
### version 1.15.0
- **Added Animated Latent Preview**
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
- Check for VideoHelperSuite node, so not to conflict with it. (Will do nothing if installed)
### version 1.14.5
- **Added Save Latent support to Save Video node**
- allows to save the full data of a generation to then experiment without the need to regenerate.
- added some very quick workflow examples.
-A simplified version of my Wan workflow
-A basic Z-Image base workflow with Prompt Generator.
- Small bug fixes
### version 1.14.0
- **Addition of a "Save Video H264/H265" node, that replicates ComfyUI's Video Node**
- Adds choice between H264/H265
- Choice of Chroma Subsampling between yuv420, yuv422, yuv444
- Can set Constant Rate Factor (compression level)
- Generates a quick proxy video if chosen format could not play in browser (H265 + yuv422 or H265 + yuv444)
- Unlike VideoHelperSuite, clip with Audio also include Metadata. Which can then be used with Prompt Extractor.
### version 1.13.5
- Added browse window with thumbnails in Extractor, with cache system for speedup.
- Bug fix for issue caused by new additions.
### version 1.12.7
- Quality of life improvements and added option to change the Strenght of any Lora in Manager, so we can tweak Extracted Workflows Live.
### version 1.12.6
- Tweak to caching behavior for prompt extractor and prompt manager advanced
### version 1.12.5
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
### version 1.12.0
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
- Prompt Extractor: Improved logic for determining Positive prompts in Worfklow.
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
### Version 1.11.5
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
### Version 1.11.2
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
### Version 1.11.0
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
- Browse and load JSON workflow files directly
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
- Filters inactive LoRAs - only extracts LoRAs marked as active
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
- Visual identification of prompts in the dropdown selector
- Thumbnails stored alongside prompt data for easy management
- **Simplified "New Prompt" button**
- Now clears fields immediately without asking for a name
- Enter the name when saving instead of when creating
- Keeps you in the current category for faster workflow
- **Bug fixes and improvements**
- Fixed JSON workflow file path resolution
- Improved LoRA extraction for complex workflows
### Version 1.10.0
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
- Save Prompt opens a modal with category selection (create new or select existing)
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
- **Import/Export JSON functionality**
- Export all prompts to a JSON file
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
- Proper cancel handling without false success messages
- **Multi-tab synchronization**
- Changing category or prompt reloads data from server
- Prevents conflicts when editing prompts in multiple browser tabs
- **Prompt Manager now preserves LoRA data**
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
- **Trigger Words support in Prompt Manager Advanced**
- Save and restore trigger words alongside prompts and LoRAs
- Trigger words display as editable text when loading saved prompts
- **Improved unsaved changes detection**
- Warning when switching away from newly created (unsaved) prompts
- Cancel button properly reverts dropdown to previous selection
### Version 1.9.0
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
- Visual LoRA tags showing name and editable strength values
- Toggle LoRAs on/off by clicking tags
- Save LoRA configurations alongside prompts
- Override mode to ignore connected inputs and use saved presets
- Merge mode combines connected LoRAs with saved presets
- Missing LoRA detection with visual warnings
- Integration with LoRA Manager for hover previews
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
- Categories and prompts now display in alphabetical order
- Fixed dropdown refresh after saving prompts
### Version 1.8.3
- Added option to leave Llama server running when closing ComfyUI.
### Version 1.8.2
- Added custom model path preference and enhance model management
### Version 1.8.1
- Added option to set a custom Llama path in preferences, for those that have specific installs.
### Version 1.8.0
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
- Detailed console output options (debug logging)
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
- Options node now accepts multiple images for analysis.
- Better Llama shutdown behavior to force-close the server when Comfy exits.
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
### Version 1.7.0
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
- Enhanced vision model workflow with dedicated image analysis modes
- Added custom image analysis with user-provided instructions (e.g., "describe the lighting", "identify objects")
- Added model preferences system integrated with ComfyUI Settings
- Added automatic model preference management (separate settings for base and vision models)
- Improved model selection with preference fallback to smallest model
- Filtered mmproj files from model selection dropdowns
- Model preferences stored in ComfyUI settings for persistence across updates
### Version 1.6.0
- Added Qwen3VL vision model support for image analysis
- Added JSON output format option with structured scene breakdown
- Added adjustable context size parameter (512-32768 tokens)
- Added automatic mmproj file download for vision models
- Added image resizing to ~2MP to optimize token usage
- Added token usage logging for monitoring context consumption
- Improved model selection logic with automatic VL/non-VL detection
- Fixed multiple directory support for model search (gguf + LLM folders)
### Version 1.5.1
- LLM output remains available when use_llm is off, so it can be edited.
- Improved caching detection: any change to options will be detected and force a new output.
- Improved some UI quirks
### Version 1.5.0
- Added Prompt Generator node with automatic llama.cpp server management
- Added Prompt Generator Options node for model selection and parameters
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
- VRAM management with optional server shutdown
### Version 1.1.0
- Added LLM input toggle for switching between internal and external text
- Made text fields scrollable even when disabled
- Fixed reload bugs with toggle state
### Version 1.0.0
- Initial release
- Category and prompt management
- LLM output integration
- llama-server, Ollama or Comfy's text encoders (Much Slower)
+81 -39
View File
@@ -1,53 +1,95 @@
"""
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
"""
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
A prompt management system for ComfyUI with LLM input support
"""
__version__ = "1.17.5"
__version__ = "3.0.0"
__author__ = "François Beaudry"
__license__ = "MIT"
from .prompt_manager import PromptManager
from .prompt_manager_advanced import PromptManagerAdvanced
from .prompt_generator import PromptGenerator
from .prompt_generator_options import PromptGenOptions
from .prompt_apply_lora import PromptApplyLora
from .prompt_extractor import PromptExtractor
from .model_manager import get_local_models
from .save_video_h26x import SaveVideoH26x, LoadLatentFile, MonoToStereo, GetVideoComponentsPlus
from server import PromptServer
# Initialize latent preview hook (with VHS conflict detection)
from .latent_preview import install_latent_preview_hook
install_latent_preview_hook()
from .py.backup_manager import check_backup
from .py.prompt_store import prompts_path
from .py.prompt_composer_store import PromptComposerStore
from .nodes.prompt_manager_adv import PromptManagerAdvanced
from .nodes.prompt_manager_basic import PromptManager
from .nodes.prompt_manager_v2 import PromptManagerV2
from .nodes import prompt_library_routes # the routes on the shared prompt library
from .nodes.prompt_composer import PromptComposer
from .nodes.library_manager import LibraryManager
from .nodes.prompt_generator import PromptGenerator, PromptGeneratorDataStore
from .nodes.prompt_generator_options import PromptGenOptions
from .nodes.prompt_generator_kill_switch import PromptGeneratorKillSwitch
from .nodes.prompt_extractor import PromptExtractor
from .nodes.prompt_layout_builder import PromptLayoutBuilder, BboxConverter
from .nodes.prompt_extractor import WorkflowExtractor as RecipeExtractor
from .nodes.recipe_builder import RecipeBuilder
from .nodes.recipe_renderer import WorkflowRenderer as RecipeRenderer
from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
from .nodes.recipe_model_picker import RecipeModelPicker
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine, MultiLoraSplitter, MultiLoraRelay, LoraStackCombine
NODE_CLASS_MAPPINGS = {
"PromptManager": PromptManager,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptApplyLora": PromptApplyLora,
"PromptExtractor": PromptExtractor,
"SaveVideoH26x": SaveVideoH26x,
"LoadLatentFile": LoadLatentFile,
"AudioMonoToStereo": MonoToStereo,
"GetVideoComponentsPlus": GetVideoComponentsPlus,
"PromptManagerV2": PromptManagerV2,
"PromptManagerAdvanced": PromptManagerAdvanced,
"PromptManager": PromptManager,
"PromptComposer": PromptComposer,
"LibraryManager": LibraryManager,
"PromptGenerator": PromptGenerator,
"PromptGenOptions": PromptGenOptions,
"PromptGeneratorKillSwitch": PromptGeneratorKillSwitch,
"PromptExtractor": PromptExtractor,
"PromptLayoutBuilder": PromptLayoutBuilder,
"BboxConverter": BboxConverter,
"RecipeExtractor": RecipeExtractor,
"RecipeBuilder": RecipeBuilder,
"RecipeRenderer": RecipeRenderer,
"RecipeRelay": RecipeRelay,
"RecipeModelLoader": RecipeModelLoader,
"RecipeModelPicker": RecipeModelPicker,
"RecipeBuilderMultiPrompts": RecipeBuilderMultiPrompts,
"MultiLoraStackerLM": MultiLoraStackerLM,
"MultiLoraCombine": MultiLoraCombine,
"MultiLoraSplitter": MultiLoraSplitter,
"MultiLoraRelay": MultiLoraRelay,
"LoraStackCombine": LoraStackCombine,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptManager": "Prompt Manager",
"PromptManagerAdvanced": "Prompt Manager Advanced",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptApplyLora": "Prompt Apply LoRA",
"PromptExtractor": "Prompt Extractor",
"SaveVideoH26x": "Save Video H264/H265",
"LoadLatentFile": "Load Latent File",
"AudioMonoToStereo": "Audio Mono to Stereo",
"GetVideoComponentsPlus": "Get Video Components+",
"PromptManagerV2": "Prompt Manager",
"PromptManagerAdvanced": "Prompt Manager (legacy)",
"PromptManager": "Prompt Manager (Basic, legacy)",
"PromptComposer": "Prompt Composer",
"LibraryManager": "Library Manager",
"PromptGenerator": "Prompt Generator",
"PromptGenOptions": "Prompt Generator Options",
"PromptGeneratorKillSwitch": "Prompt Generator Kill Switch",
"PromptExtractor": "Prompt Extractor",
"PromptLayoutBuilder": "Prompt Layout Builder",
"BboxConverter": "Bbox Converter",
"RecipeExtractor": "Recipe Extractor",
"RecipeBuilder": "Recipe Builder",
"RecipeRenderer": "Recipe Renderer",
"RecipeRelay": "Recipe Relay",
"RecipeModelLoader": "Recipe Model Loader",
"RecipeModelPicker": "Recipe Model Picker",
"RecipeBuilderMultiPrompts": "Multi Prompts",
"MultiLoraStackerLM": "Multi LoRA Stack",
"MultiLoraCombine": "Multi LoRA Combine (legacy)",
"MultiLoraSplitter": "Multi LoRA Splitter (legacy)",
"MultiLoraRelay": "Multi LoRA Relay",
"LoraStackCombine": "LoRA Stack Combine",
}
WEB_DIRECTORY = "./js"
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
print("[PromptManager] Node registered successfully")
# Ensure rotating backups exist for all prompt data files on ComfyUI startup.
try:
check_backup(prompts_path())
check_backup(PromptComposerStore.get_data_path())
check_backup(PromptGeneratorDataStore.get_data_path())
except Exception as e:
print(f"[PromptManager] Backup initialization skipped: {e}")
print("[PromptManager] Nodes registered: Prompt Manager, Prompt Composer, Prompt Generator, Prompt Generator Kill Switch, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Library Manager")
-60
View File
@@ -1,60 +0,0 @@
{
"Composition": {
"Aerial Bird's Eye View": {
"prompt": "Dramatic overhead composition shot from directly above subject, unique bird's eye perspective offering unusual and striking viewpoint, flattened perspective creating abstract qualities and geometric patterns, symmetry and patterns visible from above, sense of scale with subject appearing small against larger environment, drone photography aesthetic with perfect stability, organized chaos of urban patterns or natural formations, top-down view revealing hidden relationships and structures, professional aerial photography with exceptional detail, sharp focus across entire frame, innovative perspective creating wow factor, cinematic quality, 8k ultra high resolution, perfect exposure and color balance"
},
"Dynamic Action Scene": {
"prompt": "Extreme dynamic composition capturing peak moment of action, subject frozen mid-motion with sense of kinetic energy and movement, dramatic diagonal lines and angles creating visual tension, motion blur on background elements while keeping subject sharp, debris and particles flying through air, forced perspective emphasizing speed and impact, rule of thirds with subject positioned at power point, leading lines directing eye to focal point, sense of chaos controlled through thoughtful composition, high shutter speed photography aesthetic, dramatic depth of field separating subject from background, cinematic framing worthy of movie poster, professional action photography, 8k ultra sharp detail"
},
"Epic Landscape Vista": {
"prompt": "Sweeping panoramic landscape composition showcasing vast scale and grandeur of nature, foreground with detailed elements leading eye into scene, middle ground with points of interest, distant background with atmospheric perspective fading to horizon, dramatic sky occupying upper third of composition, sense of depth created through layering and scale relationships, golden ratio spiral guiding viewer's journey through image, professional landscape photography aesthetic, perfect balance of earth and sky, sense of awe and sublime beauty, Ansel Adams inspired tonal range, 21:9 ultra-wide aspect ratio, maximum dynamic range, 8k ultra high resolution"
},
"Frame Within Frame": {
"prompt": "Creative composition using natural or architectural elements to create frame within the photograph's frame, doorways, windows, arches, or overhanging branches framing main subject, layered composition adding depth and visual interest, vignetting effect drawing attention to central subject, sense of discovery as if viewer is peeking into scene, strategic use of foreground elements to add context and depth, professional composition technique adding sophistication, balance between frame elements and main subject, enhanced three-dimensional quality, painterly aesthetic with careful attention to spatial relationships, selective focus with frame slightly softened, artistic photography style, 4k quality with rich detail"
},
"Leading Lines Perspective": {
"prompt": "Strong compositional technique using leading lines to draw viewer's eye deep into scene, converging lines creating powerful sense of depth and three-dimensional space, linear perspective with prominent vanishing point, roads, pathways, rivers, or architectural elements creating directional flow toward focal point, exaggerated perspective emphasizing distance and scale, wide-angle lens characteristics with slight distortion at edges, journey-like quality inviting exploration, strategic placement of subject at convergence point, professional architectural photography aesthetic, sharp detail from foreground to background, enhanced depth of field, dramatic sense of scale and distance, cinematic composition, 8k ultra detailed"
},
"Low Angle Power Shot": {
"prompt": "Dramatic low angle composition shot from ground level looking upward, subject towering above camera creating sense of power, dominance, and monumentality, exaggerated perspective with converging vertical lines, hero shot aesthetic emphasizing strength and importance, sky or ceiling as background creating clean backdrop, forced perspective making subject appear larger than life, cinematic quality reminiscent of superhero movie posters, dynamic tension from unusual viewpoint, professional photography technique for impactful imagery, wide-angle lens characteristics, dramatic clouds or architectural details in background, epic scale and presence, 8k ultra sharp detail"
},
"Minimalist Zen Composition": {
"prompt": "Clean minimalist composition with abundant negative space, single focal point following principle of ma (negative space) from Japanese aesthetics, careful balance and harmony, limited color palette with subtle variations, geometric simplicity, breathing room around subject, sense of calm and contemplation, influenced by Scandinavian design principles and Japanese wabi-sabi, thoughtful placement following golden ratio, asymmetrical balance, every element serving purpose, no clutter or unnecessary details, modern contemporary art aesthetic, museum-quality presentation, pristine clarity, 4k resolution"
},
"Rule of Thirds Mastery": {
"prompt": "Expert application of rule of thirds compositional technique, subject positioned at intersection points of imaginary grid dividing frame into nine equal parts, horizon line carefully placed along upper or lower third line, key elements strategically positioned along grid lines, negative space balanced across frame, dynamic tension created by off-center placement, professional photography composition creating visual interest, golden ratio principles subtly integrated, perfect balance between subject and environment, sense of movement and energy from asymmetrical placement, cinematic quality worthy of film frame, natural eye flow through image, masterful composition, 8k resolution with exceptional clarity"
},
"Spiral Composition": {
"prompt": "Elegant spiral composition with elements arranged in curved flowing pattern leading eye in circular journey through image, fibonacci spiral or golden spiral guiding placement of key elements, sense of movement and natural flow, dynamic yet harmonious arrangement, organic curved lines contrasting with or complementing subject, shell-like or galaxy-like compositional structure, baroque painting influence with sweeping curves, professional fine art composition creating visual rhythm, balanced yet energetic, eye travels continuously through frame, painterly quality with masterful arrangement, depth created through overlapping curved elements, sophisticated artistic composition, museum quality, 4k resolution"
},
"Symmetrical Balance Portrait": {
"prompt": "Perfectly symmetrical composition with subject centered in frame, bilateral symmetry creating sense of stability and formality, architectural elements framing subject on both sides, mirrored elements balanced left and right, frontal perspective with direct eye contact, classical portrait composition reminiscent of renaissance paintings, vertical orientation emphasizing height and dignity, careful attention to equal weight distribution across frame, geometric precision in placement, formal aesthetic with authoritative presence, balanced color distribution, professional studio portrait photography, sharp focus throughout, medium format camera quality, 4k resolution with exceptional detail"
}
},
"Environment": {
"Alien Planet Landscape": {
"prompt": "A vast alien planetary landscape featuring bizarre otherworldly geology with towering crystalline formations jutting from the ground, purple and teal-colored soil and rock formations created by exotic mineral compositions, strange alien vegetation with bioluminescent properties growing in unusual fractal patterns, multiple moons of different sizes visible in the sky along with a nearby gas giant planet, alien atmosphere creating unusual light diffraction effects and colorful aurora-like phenomena, exotic weather patterns with unusual cloud formations, distant alien ruins suggesting ancient civilization, sense of wonder and cosmic scale, scientifically plausible exobiology, volumetric atmosphere with unique lighting, photorealistic rendering of fantastical elements, inspired by speculative xenobiology, cinematic composition, 8k ultra high resolution"
},
"Desert Oasis Settlement": {
"prompt": "A thriving desert oasis settlement surrounded by endless golden sand dunes, cluster of traditional mud-brick buildings with flat roofs and decorative arches clustered around a pristine blue pool of water fed by underground springs, palm trees providing shade and greenery, colorful market stalls with fabric awnings selling spices and goods, people in flowing desert robes and head wraps, camels resting near water, mountains visible in distant heat haze, dramatic sunset lighting casting long shadows and painting sky in oranges and purples, sense of refuge and life in harsh environment, Middle Eastern and North African architectural influences, warm earth tone color palette, atmospheric perspective with heat shimmer, highly detailed textures on adobe buildings and desert landscape, photorealistic rendering, 8k resolution"
},
"Enchanted Ancient Forest": {
"prompt": "A mystical ancient forest with towering thousand-year-old trees whose massive trunks are covered in luminescent moss and glowing mushrooms, thick canopy overhead filtering ethereal beams of golden sunlight that illuminate swirling magical particles and floating motes of light, forest floor carpeted with colorful wildflowers and bioluminescent plants that pulse with soft light, weathered stone ruins of an ancient civilization partially reclaimed by nature with intricate carvings still visible, gentle mist rolling through the undergrowth creating atmospheric depth, crystal-clear stream winding through the scene with small waterfalls, fireflies dancing in the air, sense of timeless magic and natural wonder, fantasy illustration style with rich saturated colors, highly detailed vegetation and atmospheric lighting effects, 8k resolution"
},
"Gothic Cathedral Grand Hall": {
"prompt": "Interior of a magnificent Gothic cathedral with soaring vaulted ceilings reaching into darkness, massive stone pillars with intricate carved details and gargoyles, enormous stained glass windows depicting biblical scenes in rich jewel tones casting colorful light patterns across the stone floor, rows of wooden pews leading to ornate altar, burning candles and hanging chandeliers providing warm ambient lighting, morning sunlight streaming through rose window creating dramatic god rays through dust motes in air, sense of awe-inspiring scale and sacred atmosphere, weathered stone showing centuries of history, architectural details including flying buttresses visible through windows, rich tapestries hanging from walls, incense smoke adding atmospheric haze, historical accuracy in medieval architecture, painterly lighting, highly detailed stonework and decorative elements, 4k quality"
},
"Neon-Lit Cyberpunk Metropolis": {
"prompt": "A sprawling cyberpunk megacity at night viewed from an elevated position, endless skyscrapers stretching to the horizon covered in massive holographic advertisements displaying animated corporate logos and products, streets far below bustling with hovering vehicles leaving light trails, neon signs in multiple Asian languages creating a vibrant glow, heavy rain creating reflections on every surface and adding atmospheric moisture, steam venting from industrial grates, layered city architecture showing wealth disparity from gleaming corporate towers to cramped lower-level slums, drone traffic weaving between buildings, atmospheric fog and smog creating volumetric lighting effects, dominant color palette of cyan, magenta, and purple neons contrasted with warm orange street lights, Blade Runner and Ghost in the Shell aesthetic, highly detailed urban environment, photorealistic rendering, 8k resolution"
},
"Orbital Space Station Interior": {
"prompt": "Interior of a massive rotating space station with curved corridors and large observation windows showing breathtaking views of Earth and stars, high-tech modular architecture with clean white and gray surfaces, holographic control panels and floating displays, artificial gravity section with hydroponics gardens growing food, astronauts in modern space suits working on equipment, sense of scale with multiple levels visible, soft blue accent lighting along corridors, scientific equipment and research stations, glimpse of space through massive reinforced windows showing auroras on Earth below, futuristic yet functional design, hard science fiction realism, attention to zero-g engineering details, photorealistic rendering with accurate lighting and materials, inspired by NASA concepts and modern space station design, 8k ultra detailed"
},
"Steampunk Victorian London": {
"prompt": "A Victorian-era London reimagined with steampunk technology, cobblestone streets with brass street lamps emitting warm gas light, elaborate clockwork mechanisms and steam-powered machinery integrated into Gothic architecture, gentlemen in top hats and ladies in corsets walking past shops with copper and brass storefronts, massive airships floating above buildings with visible propellers and steam vents, intricate gear-work visible in building facades, smog and steam creating atmospheric haze, newspaper boys selling penny dreadfuls, horse-drawn carriages sharing streets with steam-powered vehicles, warm amber and bronze color palette, attention to Victorian-era details combined with fantastical brass technology, oil painting aesthetic with rich textures, highly detailed architectural elements, 4k quality"
},
"Underwater Lost City": {
"prompt": "An ancient sunken city deep beneath the ocean surface, classical Greek or Roman architecture colonized by colorful coral and marine life, crumbling marble columns and statues covered in barnacles and swaying sea kelp, schools of tropical fish swimming through broken archways, rays of sunlight penetrating from surface creating dramatic volumetric lighting through the water, particles of sediment floating in currents, giant sea turtles and manta rays gliding past ruins, preserved mosaics and frescoes still visible on walls, sense of lost grandeur and the passage of time, turquoise and deep blue water with caustic light patterns on surfaces, highly detailed underwater environment with accurate water physics and light scattering, photorealistic quality, 8k resolution"
}
}
}
+68
View File
@@ -0,0 +1,68 @@
# FB UI rules
These rules apply to FBnodes, Prompt Manager and H3RefModPicker. Each pack ships an identical copy of `js/fbui/`; the canonical copy is in FBnodes, and `tools/sync_fbui.py` copies it into the other packs. Every pack still works on its own.
## Node faces
- A converted node shows **one card** (`mountCard` in `fbui/card.js`). No stock widget rows stay visible on it.
- Do not push plain-object widgets into `node.widgets`, do not draw UI in `onDrawForeground`/`onDrawBackground`, and do not override `widget.draw`. These do not render under Nodes 2.0.
- Previews, players and editors are card `panel` rows. A panel that should take the node's spare height uses `grow: true`, and media sits `position:absolute` inside a `.fbui-stage`.
## Look
- Every colour, radius and size comes from `fbui/theme.js`. Node files contain no hex literals.
- Only `fbui/appearance.js` sets a node's colour. Individual nodes never set `color`/`bgcolor`.
- Controls:
- INT/FLOAT values use `scrub`, with any unit inside the box.
- Booleans use an off | on pill.
- Up to 4 short choices use a segmented pill; longer lists use a select.
- Buttons use `button()` from `fbui/controls.js`.
- A field that takes tokens or a syntax gets an (i) beside its label (`info:` on the card row) listing what it understands, instead of a long tooltip.
- Toolbars over a preview go in `.fbui-stage-tools`.
- **Media frame.** Pictures and videos sit in a `.fbui-stage`:
- a neutral slate plate (`T.plate`) with a 1px trim (`T.plateEdge`) and rounded corners;
- the media is fitted edge to edge, with the plate showing around it.
- No dark well, no backdrop pattern.
- **Footnote bar.** Every node that shows a picture or video ends its preview with a footnote bar: a card `panel` row of height `CAPTION_HEIGHT` holding a `.fbui-caption`. It uses the same plate and trim as the media frame. This covers Load Image+, Load Video+, Save Image+ and Save Video+.
- It is always the **last row** of the card, below any frame picker or fold-out section.
- It states the one size the node outputs: the cropped size when a crop is on, not "before → after".
- It shows `—` when there is nothing loaded.
- Never draw these numbers on the picture itself.
- **Frame picker.** Choosing a video frame uses a rail with a white playhead (`rail()` in `fbui/controls.js`) above a line holding a `FRAME` tag, a frame-number scrub, and a readout (`6.88 s · of 240 frames`).
- **Spacing.** Keep the kit's spacing; don't squeeze rows. Buttons in a row with a label use icon-only squares (Browse, flips) so the main control keeps its width.
- Overlays drawn on a picture (crop outline, guides) are dotted while their tool is active.
## Review screens
A run that pauses for a choice (Save Image+ review; Video Review next) uses the same screen:
- It is full screen. The media fill the space as large as possible (`bestGrid` in `js/common/grid_math.js`).
- A small floating panel holds the node's name, the pick count, the timer pill with its bar, and two buttons: **Send** (the picked ones; none picked sends none) and **Skip**.
- A click picks. Space shows one item at full size (←/→ to step, Space or Esc back), and Enter sends.
- Picking pauses the timer. A queue cancel ends the wait at once.
## Workflow compatibility
- Never rename, reorder or remove Python inputs. Append new inputs at the end.
- Widgets added in JS must have `serialize = false`. The frontend skips them when saving `widgets_values`, so adding or removing them never shifts saved values.
- Hide widgets with `hideWidget`; never splice them out of `node.widgets`.
- Prove each conversion with a fixture in `test/` that asserts `widgets_values` survives configure and serialize unchanged. Real saved workflows are checked by the maintainer; tools and agents never read ComfyUI's `user/` folder.
- If a node's Python inputs really must change:
- Keep the old class under its old key, with `DEPRECATED = True` and the display name `"… (legacy)"`.
- Register the new class under a new key (such as `LoadImagePlusV2`), using the original display name.
## Nodes 2.0
- Build UI from DOM only.
- Growing panels use `fillNodeHeight`, and fixed panels use `pinHeight` (both in `fbui/layout.js`).
- Set `node.hideOutputImages = true` when the node draws its own preview.
- Do not reach into `app.canvas._*` internals.
- Check every change in both the Classic and Nodes 2.0 renderers.
## Code
- Shared modules (`js/fbui/`, `js/common/`) are `.js`, never `.mjs`. ComfyUI serves `.js` with `Cache-Control: no-store`, but sends `.mjs` with no cache header. The browser then keeps an old copy after an update, and a new module can import a name the stale one lacks, so the whole pack fails to load.
- ComfyUI imports every `.js` in the web folder, so shared modules must do nothing at import time: only exports, with no registration and no DOM work.
- Hook callbacks with `chainCallback`/`chainHandler`; never assign over an existing callback.
- Show messages with `toast()` from `fbui/comfy.js`, never `alert()`. After a user edit, call `notifyChange()` so undo and the dirty flag see it.
- Call server routes with `api.fetchApi`, never raw `fetch`.
- Naming:
- kit classes start with `fbui-`;
- kit widget names start with `fbui_`;
- extension names start with the pack (`FBnodes.*`, `PromptManager.*`, `H3RefModPicker.*`);
- routes stay prefixed with their pack.
- A call into another pack's routes must handle a 404 and hide the feature.
- Bump `KIT_VERSION` in `fbui/theme.js` whenever the kit CSS changes, then sync the kit to every pack.
+214
View File
@@ -0,0 +1,214 @@
# Changelog
## Unreleased
- **New node: Multi LoRA Relay**
- Combines and splits LoRA stacks in one node, passing through on both ends like Recipe Relay: `lora_stacks` (a multi stack, or a plain stack as slot A) and `lora_stack_a`..`d` in; the same out. A stack wired to a slot is appended to it.
- Multi LoRA Combine and Multi LoRA Splitter are now legacy; old workflows keep working.
- **Fixes**
- Saving a prompt in Prompt Manager (Basic) no longer wipes the LoRAs C/D, recipe data and negative prompt saved by the full Prompt Manager.
- Importing a library keeps every field of a prompt (recipe data, negative prompt, extra fields) and the category base prompt / prefix.
- Prompt Manager no longer resets its LoRA and trigger-word toggles on every run when no LoRAs are connected to its inputs.
- Prompt Manager (Basic): the unsaved-changes warning works, and switching to an empty category no longer fails.
- The prompt library is read once per load instead of about four times, and an unreadable library is never overwritten with the default prompts.
- Library files can only be opened as JSON.
## version 3.0.1
- **Prompt Generator: GPU detection fix for Windows (and recent llama.cpp builds)**
- `--n-gpu-layers 0` is no longer forced just because GPU support could not be detected. On Windows the old check always failed (`ldd` does not exist there, `--version` no longer names the backend, and `-h` lists `--n-gpu-layers` on every build), which pushed CUDA users into CPU inference and printed a misleading "CPU-only build" error.
- Detection now asks llama.cpp itself with `--list-devices`, and falls back to the GPU backend libraries next to the binary (`ggml-cuda.dll` etc.) or `ldd` on Linux.
- Console output now distinguishes "no GPU device in this build" (warning, CPU is correct) from "unknown" (offload is requested and llama.cpp decides).
- README: corrected install notes (winget `ggml.llamacpp` ships the official **Vulkan** build, Homebrew builds ggml with Vulkan/OpenBLAS on Linux and Metal on Apple Silicon) and added a `llama-server --list-devices` check.
## version 3.0.0
- **Breaking: one `MANAGER_DATA` type**
- Prompt Manager, Prompt Composer, Prompt Layout Builder and the Recipe nodes now share `manager_data` (replaces `RECIPE_DATA` and `COMPOSE_DATA`). Older workflows need these links reconnected.
- Recipe Renderer outputs `output_image`, `output_latent`, `manager_data`; Recipe Extractor outputs `image`, `manager_data`.
- **New Library Manager** (replaces Composition Manager and Recipe Manager)
- Saves and reloads the `manager_data` of Prompt Manager, the Recipe nodes, Prompt Composer and Prompt Layout Builder, with thumbnails.
- Filters for All / Prompt / Recipe / Compose / Layout.
- **New Prompt Library Hub** (sidebar **Prompts** button, can be hidden in Settings)
- Replaces the Prompt Browser node, which has been removed.
- Browse & Edit, Import and Export for Saved Prompts (Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe), Saved Snippets and Saved System Prompts.
- Per-category export; Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults.
- **New Prompt Layout Builder**
- Draw Object, Character, Text and Panel boxes over a scene prompt, or load them from an LLM.
- Outputs MOSS-Image layout JSON, Ideogram 4 JSON captions or Krea 2 grounding lines (needs [krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox)).
- `import_json` reads all three formats, Create Bounding Boxes elements, and layouts saved with Library Manager.
- Box descriptions can come from Prompt Composer snippets.
- **New Bbox Converter**: converts a layout JSON to bounding boxes and elements, or bounding boxes back to a layout JSON.
- **Prompt Generator**
- The system prompt dropdown is replaced by a selector: arrows cycle through prompts, the name opens the Prompt Browser.
- New **Bbox** category with **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** system prompts (Create and From Image).
- Fixed: the selected system prompt was reset to Enhance Prompt when reopening a workflow or switching tabs if the prompt was added or moved after the page loaded. Prompts moved to another category are now found by name.
- **Prompt Manager and editor**
- Export only selected categories.
- Preferred model settings, draft handling and clearer save/rename buttons in the prompt editor.
- Improved NSFW handling in the browser.
- **Prompt Composer**
- Prompt text tooltips, clear muted parts, RefMod rows.
- Picker renamed to "Select Prompt Snippet".
- Customizable thumbnail generation steps.
- Nodes 2.0 compatibility.
- Larger text across the node UIs.
- New Krea layout example workflow.
## version 2.8.0
- **Prompt Composer v2**
- New library format built around prompt groups, with a dialog to create groups and pick their category.
- Output as text or JSON, before or after the selected prompt, or on its own.
- Image and video generation modes.
- Subject numbers and subject types, mute for prompt parts.
- Export and import of composer libraries; new Generate Bulk Snippets system prompt.
- **Prompt Composer Manager** to save and reload Composer setups with thumbnails.
- Input prompt and LoRA modes on Prompt Composer and Prompt Manager, so compose data passing through Prompt Manager can add LoRAs and be saved for reuse.
- **Prompt Browser**: double-click to select, Home button, more responsive dialogs.
- Anima family support for thumbnail rendering.
- Preference to hide the downloadable built-in models in Prompt Generator.
- llama-server GPU support detection.
- Trigger word fixes: only connected words are pruned, words saved with the prompt are kept.
- Fixed LoRA stack cards collapsing or stretching to viewport height (thanks Martlet-Tech).
- Prompt Composer example workflows.
## version 2.7.2
- LoRA blacklist keywords for MiniMax and distilled LoRAs.
- Prompt Generator code moved to its own `prompt_generator.js`.
- Converter for the older system prompt storage format.
- README and feature reference updates.
## version 2.7.1
- Prompt text widgets become read-only while an external prompt input is connected; the received prompt is shown after execution.
- Prompt Extractor accepts a video input.
- Video prompt writing guides for MiniMax.
- Prompt Generator input prompt handling and model management improvements.
## version 2.7.0
- **New Prompt Composer** (started as Prompt Mixer): build prompts from multiple reusable parts.
- **System prompts are now user data**
- Stored in `prompt_generator_data.json` and editable in the Prompt Browser, grouped by category.
- New default system prompts for image and video models.
- **Prompt Browser**: multi-select, category type filter, scrolling category bar, view modes, unsaved-changes confirmation, bulk prompt builder.
- **llama.cpp** (thanks sophosympatheia)
- GPU device selection for multi-GPU systems.
- Fixed the server port ignoring the saved setting.
- Models and mmproj files are found in subfolders.
- Rotating backups for prompt data files.
- VRAM flush fixes when using a CLIP/text encoder.
## version 2.6.0
- Prompt Generator can use a connected CLIP/text encoder directly.
- Expression Selector: arrow navigation and strength slider.
- Multi LoRA Stacker: configurable stack count.
- Krea2 example workflow.
## version 2.5.4
- **Prompt Manager Advanced browser overhaul**
- Larger non-compact prompt browser with bigger 3:4 thumbnails.
- New browser view modes: Grid, Icon (small grid), and List.
- View mode is persisted in the browser and no longer controlled by a preference default.
- Compact browser size can still be restored via Preferences.
- **Krea2 thumbnail generation support**
- Recipe Renderer now supports the Krea2 family for thumbnail renders.
- **New Expression Selector node**
- Appends a saved Expression-category prompt to an input prompt.
- Supports gender-aware pronoun substitution.
- Add new expressions directly through Prompt Manager Advanced.
- Select `(none)` to pass the input prompt through unchanged.
## version 2.5.3
- **Improved Prompt Extractor to better match FBNodes image loader+**
- Can now browse any folder and can view in detail, normal and large Thumbnails.
## version 2.5.2
- **Improved LLM prompts in Prompt Generator**
- New System prompts for Video and Audio Generation
## version 2.5.0
- **Recipe Builder is now Multi-model Only**
- Expanded Builder authoring around `recipe_data` with slot-aware model blocks (`model_a`/`model_b`/`model_c`/`model_d`).
- Improved cross-slot behavior for prompts, LoRAs, sampler settings, and resolution handling in multi-model workflows.
- **Authoritative Builder extraction flow**
- Extraction now preserves Builder-authored v2 model data as the source of truth when embedded Builder v2 metadata is present.
- Added compatibility safeguards so legacy/non-v2 workflows continue to use fallback extraction logic.
- **Builder lock/reset and execution consistency**
- Improved update and execute behavior so incoming recipe values, lock states, and current UI values resolve more predictably.
- Strength/reset handling was tightened for better consistency across slot updates and reruns.
- **New LoRA utility node: MultiLoraCombine**
- Added `MultiLoraCombine` to merge optional multi-stack input with optional stack A/B/C/D inputs into a single `MULTI_LORA_STACK` output.
- Helps consolidate mixed LoRA sources for multi-model Builder and downstream recipe flows.
- **New feature: Multi LoRA Stacker with Lora-Manager compatibility**
- Added a new Multi LoRA Stacker for slot-aware and multi-stack recipe flows.
- Compatible with [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager), including interoperability with managed LoRA selections and previews.
## version 2.2.0
- **Recipe_data v2 expansion and slot-aware workflows**
- Expanded v2 compatibility across Builder, Relay, Renderer, Manager, and extraction utilities.
- Improved model slot behavior for `model_a`/`model_b`/`model_c`/`model_d`, including WAN pair handling.
- **Recipe Builder Update flow and persistence improvements**
- Update Recipe now respects Pull From selection consistently and supports expected clear behavior for empty/none selections.
- Pull From / Send To state persistence improved across tab switches and workflow reloads.
- Update Recipe visibility refined to avoid incomplete Builder-to-Builder pull paths.
- **LoRA synchronization and execution-order fixes**
- Fixed connected LoRA add/remove timing so `recipe_data` reflects changes on first execute.
- Improved LoRA state authority between connected inputs and persisted UI overrides.
- **Renderer validation hardening**
- Renderer now fails fast with a clear error when the selected model slot is undefined.
- Prevents silent renders from empty/non-existent selected model slots.
- **Prompt Generator GPU utilization and VRAM prep**
- Ensured llama.cpp server launch uses `-ngl 100` so generation is pushed to GPU as much as possible.
- Added more aggressive cache/VRAM flushing before generation to reduce memory pressure and improve run reliability.
## version 2.1.1
- Updated Documentation
- Bug fixes
## version 2.1.0
- **Naming Migration: Workflow -> Recipe**
- Renamed node/toolset terminology to Recipe naming across the addon UI and docs.
- Bug fixes.
## version 2.0.2
- Added Ernie family support in Workflow Builder/Renderer.
- Bug fixes.
## version 2.0.1
- **Added Denoise options to Workflow Pipeline**
- Workflow data now contains denoise value (Extractor returns 1 by default).
- Allows mid-run model handoff using KSampler denoise.
- Bug fixes.
## version 2.0.0
- **Prompt Manager becomes Prompt + Workflow Manager**
- Workflow Manager allows saving workflow and integrates with Prompt Manager save/reuse behavior.
- Extractor/Builder/Manager workflow loop focused on simplified reusable workflow cores.
- recipe_data-first persistence improvements.
- Documentation updates.
## version 1.25.0
- **Workflow Tools Release Milestone**
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader form a complete editable workflow pipeline.
- Improved extractor-to-builder update flow.
- Improved Builder dropdown stability and persistence.
- Improved tab-switch persistence for Builder UI state.
- Improved compatibility with Builder persistence extraction.
- **Wan i2v workflow quality and UX improvements**
- **Prompt Manager Advanced save + thumbnail improvements**
## version 1.22.6
- Prompt Extractor now embeds extracted data in workflow so it can extract itself.
## version 1.22.5
- Thumbnail generation in Prompt Manager Advanced.
- Improved model high/low detection.
## version 1.22.1
- Prompt Model Loader improvements, including GGUF support and persistence improvements.
## version 1.22.0
- New node: Prompt Model Loader.
- Expanded model/checkpoint extraction in Prompt Extractor.
- A1111/Forge image support improvements.
- WebP metadata support improvements.
- Video metadata parsing improvements.
## version 1.21.x to 1.0.0
Older historical entries were previously listed in README and can still be recovered from repository history.
+178
View File
@@ -0,0 +1,178 @@
**This documentation is ongoing and will continue to improve**
### Prompt Manager
Allows for Saving and Loading prompts quickly using the Prompt Browser UI.
- Clicking the Blue Prompt Name button, under the text area, will open the Prompt Browser.
- Pressing the < > on each side of the button will quickly switch to the next prompt.
- **In Prompt Browser mode:**
- Click the + to create new Categories.
- Generate Thumbnails for Prompts or Categories (Right Click)
- If not set, a Pop Up will ask you to select the model to use for generation.
- Enable Edit mode to enable writing Prompts directly in the Browser.
- Be sure to save the prompt before generating its thumbnail
- Right click provides other options such as:
- Tagging as NSFW (filtering by default can be enabled in prefs)
- Moving or Renaming
- Pasting an image in as a Prompt
- Generating a thumbnail for a Prompt
- It is also possible to simply drag an image over a prompt to replace its Thumbnail.
- **On the node's Main UI:**
- Use Prompt input toggle to display incoming prompt (from Prompt Generator for example).
- Toggling off allows editing that new prompt.
- Use LoRA input allows choosing which LoRAs are used:
- Prompt LoRAs Only: This turns off any LoRAs connected to our node.
- Combine LoRAs: This uses both the prompt and incoming LoRAs, but will remove duplicates.
- Input LoRAs Only: For those times when you want just the Prompt but use your own new recipe.
- **Do note: If a prompt is saved again, this can change the LoRAs assigned to the Prompt**
- LoRA Support:
- Supports the Add-On LoRA Manager to display LoRA Thumbnails on Hover.
- LoRA input supports either Traditional LoRA Stackers or the new included Multi LoRA Stack.
- Using normal LoRA Stackers, two stacks of LoRAs can be used and will be displayed in our UI.
- Connecting Multi LoRA Stack instead allows up to four stacks to be displayed.
- Multi LoRA Stack uses the LoRA Manager add-on at its core and is needed for it to work.
- When LoRAs are used, the UI will display them as tags, allowing strength editing or toggling On or Off.
- A list of Trigger words can be connected and will be displayed as Tags that can be toggled On or Off.
- LoRAs are saved with prompt entries; this includes their state (On or Off) as well as their Strength.
- Missing LoRAs will be displayed as Red.
- The Save Button opens up the Prompt Browser, allowing saving under any category.
- The New Prompt Button is practical when you want to clear everything, including LoRAs, and start fresh.
- The More button allows access to Exporting your Saved Prompt, but also merging another JSON. Be careful.
### Prompt Manager (Basic)
A simpler no frills version that supports only Prompts. (This is the OG node)
- Select category and prompt using a purely comfy UI.
- If saving over an existing prompt, LoRAs and Thumbnails will be preserved.
- If NSFW filtering is enabled, NSFW Prompts will be hidden.
- LLM input toggle works similar to full node.
### Prompt Generator
Generates prompts using a local LLM. Supports either Llama.cpp or Ollama, but can also be used directly with Comfy's Text encoders.
Allows downloading of 3 different sizes of Unsloth's Qwen 3.5, but users are free to add more models in models/gguf. If found, the add-on will list them. (Refresh when adding new ones)
- Comes with a bundle of pre-made System Prompts.
- Use the arrows beside the system prompt name to cycle through saved prompts across categories, or click the name to open Prompt Browser on System Prompts. When loading workflows, legacy names such as `Enhance Prompt (Image)` are matched to current entries. Missing prompts fall back to `Image / Enhance Prompt` (or the first available entry if that default was removed), without changing other widget values.
- Create your own system prompts with the **Prompt Library Hub** (sidebar) or by clicking the system prompt name
- I highly recommend using the **rgthree add-on** and enable *"Auto Nest Subdirectories in Menus"*. This will display categories as submenus.
- Options to output in JSON format and enable Thinking mode.
- The stop_server_after toggle:
- Kills Llama.cpp after generating the prompt
- Tries to force Ollama to unload the current model
- The clear_vram_on_run toggle:
- Unloads Comfy's model from memory before generating the prompt
- Clears Vram again once the prompt is generated.
- It is recommended to leave on, unless you are using small models
- Both Stop_server and clear_vram are ignored when using Text encoders, as we instead let Comfy manage the VRAM.
- Expected llama.cpp startup failures log one actionable summary without a console traceback. Enable **Show everything in Console** in Prompt Generator Options and retry to see the traceback, full launch command, and server stderr. The workflow still fails normally, and unexpected errors retain their tracebacks.
- Lastly, the **Model Selection**:
- (Use Default): Uses the default model set in preferences, or the first found, if not set.
- Missing saved model selections fall back to the default selection with a console warning. If no suitable model is available, generation still reports an error.
- 3 Different Quant size of Qwen 3.5 can be automatically downloaded.
- Any models you add in models/gguf, or any custom folder if set in preferences.
- If you no longer want to see the built-in download entries, enable the `Hide downloadable built-in models` preference under Prompt Manager settings.
- For Multi-image support, connect the Generator Option node.
- Use the Prompt Generator Options node for controlling model parameters.
### Prompt Generator Options
This node provides extra control to **Prompt Generator** and is NOT mandatory.
- Modify the selected system prompt, by either appending extra instructions or replacing it entirely.
- Provides extra images input for a Total of 5.
- Change the System settings for the model
- Change the GPU used by the LLM
### Prompt Library Hub
The **Prompts** button in ComfyUI's left sidebar opens the Prompt Library Hub (hide it with Settings > Prompt Manager > 4. Advanced Preferences > Show Prompts Sidebar Button): one place to browse, edit, import and export every Prompt Manager library. It has three sections:
- **Saved Prompts**: everything saved through Prompt Manager or Library Manager (prompts, recipes, Composer setups and layouts); the Prompt Browser's **Type** button filters them.
- **Saved Snippets**: the snippets used by Prompt Composer.
- **Saved System Prompts**: the system prompts used by Prompt Generator.
Every section has the same three buttons:
- **Browse & Edit**: opens the Prompt Browser on that library with the Edit tab on.
- **Import**: merge a file; when entries already exist you choose to keep or overwrite them. Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults (adds back missing built-in prompts without touching yours). Saved Prompt types share one file, so they only merge.
- **Export**: pick the categories to export as one JSON file (Snippets export selected prompt groups as a ZIP).
The Prompt Generator's system prompts are stored in *prompt_generator_data.json*, so you can author your own. Built-in prompts added by updates can be brought into your saved system prompts with **Restore defaults**.
### Prompt Extractor
Extract prompt, model, and LoRA info out of images, videos, and JSON workflow files.
- Supports ComfyUI, A1111/Forge, and WebP metadata formats.
- Grabs the frame of your choice from videos using a time slider.
- Dual LoRA stack extraction for compatible workflows.
- Can browse from either the input or output folders directly.
- Can also be used as an advanced media loader with metadata awareness
### Prompt Layout Builder
Draw a layout of boxes over a scene prompt, or load one from an LLM, and output it as a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
- The canvas follows the aspect ratio and megapixels, or a connected image's ratio with **Use Reference Ratio**. A connected image is also shown behind the boxes.
- Draw, move and resize boxes on the canvas, or type exact x/y/width/height values. Each box is an **Object**, **Character**, **Text** (with the exact words to render) or **Panel** (shown in Krea 2 mode), with a description and an optional color palette.
- The thumbnail button beside a description picks a Prompt Composer snippet for the box.
- Full screen editor, grid overlay, canvas text size, undo/redo (Ctrl/Cmd+Z), duplicate (Ctrl/Cmd+D) and delete (Del).
- A hint lists what is missing, such as a box without a description.
- **Output** formats:
- **MOSS**: MOSS-Image layout JSON (the same format as the core MOSS-Image Layout Prompt), with meta tags, canvas type and palettes.
- **Ideogram**: Ideogram 4 JSON caption (the same format as Build JSON Prompt (Ideogram)), with background, photo or art style, aesthetics, lighting, medium and a style palette.
- **Krea 2**: Krea 2 grounding lines: a one-sentence summary, `@style; medium`, `~background`, then one line per box (panels first). Character boxes get a Person / Anime character / Furry tag and an optional ID; reuse the ID to keep the same character across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). See its PROMPTING.md for the prompt format and sampler settings.
- **Use import_json** reads the layout from `import_json` and locks the editor. It accepts layout JSON (percent, 0-1000 or MOSS-native boxes), Ideogram 4 captions, Krea 2 grounding lines, Create Bounding Boxes elements, or a saved layout's `manager_data` from Library Manager. Turn it off to keep editing the imported boxes.
- Prompt Generator system prompts for layouts (**Bbox** category): **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout**, each with **Create** and **From Image** versions. If they are missing, use **Restore defaults** for System Prompts in the Prompt Library Hub.
- Outputs: prompt, preview (the boxes drawn over the canvas), width, height and `manager_data` (save it with Library Manager).
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types, so the builder can be chained with other box nodes. Connect a `layout_json` (any format the builder imports) or `bboxes` (bounding boxes, Create Bounding Boxes elements or their JSON); with both connected, a toggle picks the source. It outputs `layout_json` (passed through, or a percent layout when converting bboxes, without a prompt), pixel `bboxes` and `elements`.
## Recipe Toolset (Experimental)
The Recipe Toolset are a set of experimental nodes to lets you build, manage, and rerun reusable pipelines. You can write recipes from scratch in Builder, combine them with Prompt Manager / Prompt Manager Advanced to reuse saved prompts, or import existing metadata through Extractor when you want to bootstrap from something you already made. Then saved them as complete Recipes.
As Stated these were an experiment into improving Manager, but as been put aside a bit. The technology behind it is what allowed for Thumbnail Generation in Prompt Browser. The Recipe Relay node is great when creating slick workflows with a single link between subgraph, as it can stack 4 workflows of data in a single connection.
### Recipe Builder
The main place to create or tweak recipes.
- Build or modify recipes from scratch in one central spot.
- Inspect and adjust recipe fields without wiring every parameter by hand.
- Use it standalone, or connect it with other recipe/prompt nodes.
- Works well with Prompt Manager so saved prompts can be slotted into recipe-driven pipelines.
- Great for iterative tuning: extract once, keep tweaking values and rerendering until the pipeline feels right.
- Helps standardize presets so repeated jobs start from the same known-good setup.
### Recipe Extractor
Reads and normalizes workflow metadata into reusable recipe data.
- Converts raw generation metadata into a cleaner recipe format that's easier to edit and pass between nodes.
- Keeps important settings intact when moving from one-off runs to reusable setups.
- Useful when you want to recreate a look/style from an existing output and iterate from there.
### Recipe Renderer
Runs recipe-driven generation so you can rerun pipelines quickly.
- Interprets recipe data during execution to reproduce prior results or batch variants with minimal manual work.
- Cuts down setup time for repeated jobs by moving configuration into reusable recipe data.
- Especially handy when testing different prompts or inputs while keeping the same core recipe.
### Recipe Relay
A clean handoff point for recipe data between nodes.
- Passes recipe data and compatible context across the graph.
- Keeps larger graphs modular and easier to follow.
- Preserves context through the pipeline, so you don't lose recipe continuity when splitting graphs into stages.
### Recipe Model Loader
Loads models/checkpoints based on recipe data.
- Resolves model selections encoded in recipes so execution follows the intended model path automatically.
- Supports model slot selection and loader-specific behavior.
- Makes recipe playback more reliable across sessions by tying loader behavior to the saved recipe, not memory.
- Useful for multi-model pipelines where model choice is part of the recipe itself.
### Saving Recipes (Library Manager)
Recipe nodes pass their data as `manager_data`, the same type used by Prompt Manager, Prompt Composer and Prompt Layout Builder. Save, browse, and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
- Persistent recipe storage so successful setups can be cataloged and recalled quickly.
- Works with Builder for quick review and updates.
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects.
- Good for keeping repeatable production presets while still allowing safe edits over time.
## Model Family Support
Built-in support includes:
- Flux 1
- Flux 2
- Ernie
- SDXL
- Wan
- Qwen
- Z-Image
- Wan Image
- Wan Video (I2V and T2V)
Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 KiB

Before

Width:  |  Height:  |  Size: 766 KiB

After

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 670 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 450 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 359 KiB

After

Width:  |  Height:  |  Size: 87 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 433 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 538 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 668 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 267 KiB

After

Width:  |  Height:  |  Size: 40 KiB

File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

+119
View File
@@ -0,0 +1,119 @@
// Solid node colours for every node of the pack that installs this, the one
// thing that makes the packs read as one family on the canvas. Nodes without
// any JS of their own get the colours too.
//
// A node follows the setting while it carries no colours or exactly one
// scheme's pair; a colour picked in ComfyUI's own colour menu is the user's
// and wins.
import { app } from "../../../scripts/app.js";
import { chainCallback } from "./dom.js";
export const NODE_COLOR_SCHEMES = [
{ name: "FB Blue", colors: { title: "#1b3350", body: "#161b22" } },
{ name: "Theme default", colors: null },
{ name: "Graphite", colors: { title: "#242424", body: "#2f2f2f" } },
{ name: "Slate", colors: { title: "#1f2c38", body: "#2a3b4a" } },
{ name: "Teal", colors: { title: "#14332f", body: "#1c453f" } },
{ name: "Plum", colors: { title: "#2e1f38", body: "#3d2a4a" } },
{ name: "Rust", colors: { title: "#3a2317", body: "#4c2f20" } },
];
const NAMES = NODE_COLOR_SCHEMES.map((scheme) => scheme.name);
const norm = (value) => (typeof value === "string" ? value.trim().toLowerCase() : "");
const schemeColors = (name) => NODE_COLOR_SCHEMES.find((scheme) => scheme.name === name)?.colors ?? null;
const SCHEME_TITLES = new Set(NODE_COLOR_SCHEMES.flatMap((scheme) => (scheme.colors ? [scheme.colors.title] : [])));
// Our scheme titles are dark: the classic renderer's grey title text gets
// lost on them. Marked on the node by nodeCreated (never saved).
const MARK = Symbol.for("fbui.packNode");
function followsSetting(node) {
const color = norm(node.color);
const bgcolor = norm(node.bgcolor);
if (!color && !bgcolor) return true;
return NODE_COLOR_SCHEMES.some((scheme) => scheme.colors && color === scheme.colors.title && bgcolor === scheme.colors.body);
}
function apply(node, colors) {
// Assigning undefined (never `delete`) keeps Nodes 2.0 reactive.
node.color = colors ? colors.title : undefined;
node.bgcolor = colors ? colors.body : undefined;
}
function allNodes(graph, seen = new Set()) {
if (!graph || seen.has(graph)) return [];
seen.add(graph);
const out = [];
for (const node of graph._nodes ?? graph.nodes ?? []) {
out.push(node);
if (node.subgraph) out.push(...allNodes(node.subgraph, seen));
}
return out;
}
// Wrapping drawTitleText is the one place a prototype is patched directly: a
// draw method must return through the original. Shared by every pack.
function installTitleInk() {
const proto = globalThis.LiteGraph?.LGraphNode?.prototype;
if (typeof proto?.drawTitleText !== "function" || proto.drawTitleText[MARK]) return;
const original = proto.drawTitleText;
function drawTitleText(ctx, options, ...rest) {
if (options && this?.[MARK] && SCHEME_TITLES.has(norm(this.color))) options = { ...options, default_title_color: "#ffffff" };
return original.call(this, ctx, options, ...rest);
}
drawTitleText[MARK] = true;
proto.drawTitleText = drawTitleText;
}
// installAppearance({ settingsPrefix: "FBnodes", category: "FBnodes" }) from
// the pack's fbui_setup.js. The pack is found from this file's own URL
// (/extensions/<folder>/fbui/...), which matches the nodes' python_module
// whatever the install folder is called.
export function installAppearance({ settingsPrefix, category }) {
const folder = decodeURIComponent(new URL(import.meta.url).pathname.split("/extensions/")[1]?.split("/")[0] ?? "");
const module = `custom_nodes.${folder}`;
const settingId = `${settingsPrefix}.Appearance.NodeColor`;
const ours = (node) => node?.constructor?.nodeData?.python_module === module;
let active = NAMES[0];
app.registerExtension({
name: `${settingsPrefix}.Appearance`,
settings: [
{
id: settingId,
category: [category, "Appearance", "Node color"],
name: "Node color",
type: "combo",
defaultValue: NAMES[0],
options: NAMES,
tooltip: "Colour scheme for this pack's nodes. Nodes you coloured by hand keep their own colours.",
onChange(value) {
active = NAMES.includes(value) ? value : NAMES[0];
for (const node of allNodes(app.graph)) if (ours(node) && followsSetting(node)) apply(node, schemeColors(active));
app.graph?.setDirtyCanvas?.(true, true);
},
},
],
setup() {
const stored = app.ui?.settings?.getSettingValue?.(settingId);
if (NAMES.includes(stored)) active = stored;
installTitleInk();
},
nodeCreated(node) {
if (!ours(node)) return;
node[MARK] = true;
if (followsSetting(node)) apply(node, schemeColors(active));
// Native text boxes wear the kit's text-area colour: Classic draws the
// widget's own textarea, Nodes 2.0 one carrying the widget's options.
for (const widget of node.widgets ?? []) {
if (widget.element?.tagName !== "TEXTAREA") continue;
widget.element.classList.add("fbui-native-text");
widget.options = { ...widget.options, "data-fbui-text": "true" };
}
// Saved colours arrive after construction: a workflow saved before the
// pack had colours, or with another scheme, follows the setting now.
chainCallback(node, "onConfigure", function () {
if (followsSetting(this)) apply(this, schemeColors(active));
});
},
});
}
+435
View File
@@ -0,0 +1,435 @@
// The card: one DOM panel standing in for a node's stock widgets. Every row
// mirrors a hidden widget (or a pair of them), so the widgets stay the source
// of truth: save/load, undo, API format and links all keep working through
// them. The card writes widget.value, runs the widget's callback, and re-reads
// everything on configure, on connection changes and after any callback.
//
// Rows:
// { widget, label?, kind?, suffix?, labels?, title?, info?, when?, group?, button? }
// info: help lines shown from an (i) beside the label (see controls.info)
// kind: scrub | segment | select | switch | text (default: from the widget)
// labels: { value: text } or (value, values, node) => text
// button: { text, icon?, title?, onClick(node, card) } (or a list) after the control
// groups: (value, values, node) => heading, for a select's <optgroup>s
// { pair: [a, b], label, sep?, when?, group? }
// { section: "Caption", when? }
// { label, control: (node, card) => ({ element, label?, sync?(values) }), widgets?, when?, group? }
// a labelled row holding the node's own control; `widgets` names the
// hidden widgets it drives; a returned `label` element replaces the text
// { panel: (node, card) => ({ element, sync?(values) }), height, grow?, when? }
// grow takes the node's spare height; a height function is read again
// on every refresh (a panel whose content wraps)
// { group: "more", label: "More", tools? } later rows with group: "more" fold under it
// tools: (node, card) => ({ element, sync?(values) }) at the header's right
// Options: minWidth, first (place before the node's other DOM widgets).
import { chainCallback, el, keepDomWidgetWidthAuto, keepKeyInField } from "./dom.js";
import { notifyChange } from "./comfy.js";
import { button as makeButton, info as infoIcon, segmented } from "./controls.js";
import { cardHeight, choiceLabel, isGroupHeader, rowHeight, rowKind, rowTops, socketWidgetY, visibleRows } from "./card_math.js";
import { ensureNodeMinHeight, fillNodeHeight, pinHeight, WIDGET_FRAME } from "./layout.js";
import { makeScrub, scrubSteps } from "./scrub.js";
import { ensureKitCss, GROUP_HEIGHT, ROW_HEIGHT, UNIT_SLOT_WIDTH } from "./theme.js";
import { comboValues, commitWidgetValue, findWidget, hideWidget, widgetLinked, widgetSlot, widgetTooltip } from "./widgets.js";
export const CARD_WIDGET = "fbui_card";
const WRAPPER_TOP = 10;
function isFloatWidget(widget) {
const precision = widget?.options?.precision;
if (precision !== undefined) return Number(precision) > 0;
const step = widget?.options?.step2 ?? widget?.options?.round;
return step !== undefined ? !Number.isInteger(Number(step)) : !Number.isInteger(Number(widget?.value));
}
export function mountCard(node, { rows, minWidth = 280, first = false } = {}) {
ensureKitCss();
const root = el("div", "fbui-card");
const card = { node, root, entries: [], height: 0, widget: null, rowTop: new Map(), rowSpan: new Map(), disposed: false };
const managed = new Set();
const values = () => Object.fromEntries((node.widgets ?? []).map((widget) => [widget.name, widget.value]));
const groupKey = (name) => `fbui_open_${name}`;
const groupOpen = (name) => Boolean(node.properties?.[groupKey(name)]);
const setWidget = (name, value, { settle = true } = {}) => {
const widget = findWidget(node, name);
if (!widget || widget.value === value) return;
card.byHand = true;
try {
commitWidgetValue(node, widget, value);
} finally {
card.byHand = false;
}
node.graph?.setDirtyCanvas?.(true, true);
if (settle) notifyChange();
};
card.setWidget = setWidget;
const builders = {
scrub(name, row, into) {
const widget = findWidget(node, name);
const isFloat = isFloatWidget(widget);
const steps = scrubSteps(widget?.options, isFloat, row.suffix === "px");
const control = makeScrub({
value: Number(widget?.value) || 0,
min: Number(widget?.options?.min ?? -Infinity),
max: Number(widget?.options?.max ?? Infinity),
step: row.step ?? steps.step,
fineStep: steps.fineStep,
decimals: row.decimals ?? steps.decimals,
unit: row.suffix ?? "",
unitWidth: row.pair ? 0 : UNIT_SLOT_WIDTH,
title: row.title ?? widgetTooltip(node, name),
onChange: (next) => setWidget(name, isFloat ? next : Math.round(next), { settle: false }),
onSettle: notifyChange,
});
into.append(control.root);
return (vals) => control.set(Number(vals[name]) || 0);
},
segment(name, row, into) {
const widget = findWidget(node, name);
// The choices can change (one widget's list following another's value):
// the pill is rebuilt whenever they do.
let shown = null;
let seg = null;
return (vals) => {
const options = comboValues(widget);
const key = options.join("\n");
if (key !== shown) {
shown = key;
const next = segmented(options.map((value) => ({ value, label: choiceLabel(row, value, options, node), title: row.titles?.[value] })), { onPick: (value) => setWidget(name, value) });
if (seg) seg.root.replaceWith(next.root);
else into.append(next.root);
seg = next;
}
seg.set(vals[name]);
};
},
switch(name, row, into) {
const seg = segmented([{ value: false, label: row.offText ?? "off" }, { value: true, label: row.onText ?? "on" }], { bool: true, onPick: (value) => setWidget(name, value) });
seg.root.title = row.title ?? widgetTooltip(node, name);
into.append(seg.root);
return (vals) => seg.set(Boolean(vals[name]));
},
select(name, row, into) {
const widget = findWidget(node, name);
const select = el("select", "fbui-select");
select.title = row.title ?? widgetTooltip(node, name);
let shown = null;
const fill = (current) => {
const options = comboValues(widget);
const list = options.includes(current) || current === undefined || current === "" ? options : [...options, current];
const key = list.join("\n");
if (key !== shown) {
shown = key;
select.textContent = "";
// row.groups(value) names a value's group: runs of one group sit
// under an <optgroup> heading.
let group = null;
for (const value of list) {
const option = el("option", "", choiceLabel(row, value, options, node));
option.value = String(value);
const name = row.groups?.(value, options, node) ?? null;
if (name && name !== group?.label) {
group = el("optgroup");
group.label = name;
select.append(group);
} else if (!name) group = null;
(group ?? select).append(option);
}
}
select.value = String(current ?? "");
select.title = String(current ?? "") || widgetTooltip(node, name);
};
select.addEventListener("change", () => setWidget(name, select.value));
// The list may change between refreshes (an upload, a folder change).
select.addEventListener("pointerdown", () => fill(findWidget(node, name)?.value));
into.append(select);
return (vals) => fill(vals[name]);
},
text(name, row, into) {
const input = el("input", "fbui-text");
input.type = "text";
input.spellcheck = false;
input.placeholder = row.placeholder ?? "";
input.title = row.title ?? widgetTooltip(node, name);
const commit = () => {
if (input.value !== String(findWidget(node, name)?.value ?? "")) setWidget(name, input.value);
};
input.addEventListener("change", commit);
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.blur();
if (event.key === "Escape") {
input.value = String(findWidget(node, name)?.value ?? "");
input.blur();
}
});
into.append(input);
return (vals) => {
if (document.activeElement !== input) input.value = String(vals[name] ?? "");
};
},
};
let currentGroup = null;
for (const row of rows) {
if (row.section !== undefined) {
const caption = el("div", "fbui-section", row.section);
card.entries.push({ row: { ...row, inGroup: currentGroup }, element: caption, syncs: [] });
root.append(caption);
continue;
}
if (row.panel) {
const line = el("div", "fbui-row panel");
if (row.grow) {
line.classList.add("grow");
line.style.minHeight = `${rowHeight(row)}px`;
} else {
line.style.height = `${rowHeight(row)}px`;
}
const panel = row.panel(node, card);
line.append(panel.element);
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, syncs: panel.sync ? [panel.sync] : [] });
root.append(line);
continue;
}
if (row.control) {
// `widgets` names the hidden widgets the control drives: their sockets
// sit on this row and a link dims it, as for a widget row.
const names = row.widgets ?? [];
for (const name of names) {
const widget = findWidget(node, name);
if (widget) {
hideWidget(widget);
managed.add(name);
}
}
const line = el("div", "fbui-row");
const control = el("div", "fbui-control");
const built = row.control(node, card);
control.append(built.element);
line.append(built.label ?? el("span", "fbui-label", row.label ?? ""), control);
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, names, syncs: built.sync ? [built.sync] : [] });
root.append(line);
continue;
}
if (isGroupHeader(row)) {
currentGroup = row.group;
const header = el("div", "fbui-group");
const toggle = el("button", "toggle");
toggle.type = "button";
toggle.append(el("span", "glyph", "▸"), el("span", "", row.label ?? row.group));
const tools = row.tools?.(node, card);
header.append(toggle, ...(tools ? [tools.element] : []));
toggle.addEventListener("click", () => {
node.properties ??= {};
node.properties[groupKey(row.group)] = !groupOpen(row.group);
card.byHand = true;
try {
refresh();
} finally {
card.byHand = false;
}
});
card.entries.push({ row, element: header, header: true, syncs: tools?.sync ? [tools.sync] : [] });
root.append(header);
continue;
}
const names = row.pair ?? [row.widget];
for (const name of names) {
const widget = findWidget(node, name);
if (widget) {
hideWidget(widget);
managed.add(name);
}
}
const line = el("div", "fbui-row");
const label = el("span", "fbui-label");
label.title = row.title ?? widgetTooltip(node, names[0]);
if (row.info) {
label.classList.add("has-info");
label.append(el("span", "", row.label ?? names[0]), infoIcon(row.info));
} else {
label.textContent = row.label ?? names[0];
}
const control = el("div", "fbui-control");
const syncs = [];
const fields = new Map();
names.forEach((name, index) => {
const widget = findWidget(node, name);
if (!widget) return;
if (index > 0) control.append(el("span", "fbui-sep", row.sep ?? "·"));
if (row.prefixes?.[index]) control.append(el("span", "fbui-sep", row.prefixes[index]));
const field = el("div", "fbui-field");
const kind = rowKind(row, widget, comboValues(widget));
syncs.push(builders[kind](name, row, field));
control.append(field);
fields.set(name, field);
});
for (const { text, onClick, ...rest } of [row.button ?? []].flat()) {
control.append(makeButton(text, { ...rest, onClick: () => onClick?.(node, card) }));
}
line.append(label, control);
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, names, syncs, fields });
root.append(line);
}
// Clicks on controls stay out of the graph's drag; empty card space falls
// through. A stage stops the events it consumes itself.
root.addEventListener("pointerdown", (event) => {
if (event.target.closest("button,input,select,textarea,.fbui-scrub")) event.stopPropagation();
});
const widget = node.addDOMWidget(CARD_WIDGET, CARD_WIDGET, root, { serialize: false, hideOnZoom: false });
keepDomWidgetWidthAuto(widget);
// options.serialize only keeps it out of the prompt; saves skip a widget
// whose own serialize is false.
widget.serialize = false;
card.widget = widget;
const declared = () => card.height + WIDGET_FRAME;
if (rows.some((row) => row.grow)) fillNodeHeight(widget, { minWidth, minHeight: declared });
else pinHeight(widget, declared, minWidth);
if (first && Array.isArray(node.widgets)) {
const index = node.widgets.indexOf(widget);
const firstDom = node.widgets.findIndex((item) => item !== widget && item.element);
if (index >= 0 && firstDom >= 0 && firstDom < index) {
node.widgets.splice(index, 1);
node.widgets.splice(firstDom, 0, widget);
}
}
// Each hidden widget with an input slot reports the y of its row, so the
// frontend draws and hit-tests its socket there. A folded row hands its
// socket to its group header, or to the card's top edge.
const socketY = (name) => {
const cardY = Number(card.widget?.y);
if (card.disposed || !Number.isFinite(cardY)) return null;
const top = card.rowTop.get(name);
if (top === undefined) return cardY + WRAPPER_TOP;
return socketWidgetY(cardY, WRAPPER_TOP, top, card.rowSpan.get(name) ?? ROW_HEIGHT);
};
const socketed = [];
for (const name of managed) {
const target = findWidget(node, name);
if (!target || !widgetSlot(node, name) || Object.getOwnPropertyDescriptor(target, "y")?.get) continue;
let stored = target.y;
try {
Object.defineProperty(target, "y", { configurable: true, enumerable: true, get: () => socketY(name) ?? stored, set: (value) => { stored = value; } });
socketed.push(() => { delete target.y; target.y = stored; });
} catch {
// A sealed widget keeps its socket where the frontend puts it.
}
}
// While a link is dragged, the row under the pointer stands in for its
// widget, so a drop anywhere on the row lands on that widget's input.
const originalGetWidgetOnPos = node.getWidgetOnPos;
if (typeof originalGetWidgetOnPos === "function") {
node.getWidgetOnPos = function (canvasX, canvasY, includeDisabled) {
const found = originalGetWidgetOnPos.call(this, canvasX, canvasY, includeDisabled);
if (card.disposed || found !== card.widget || !globalThis.app?.canvas?.linkConnector?.isConnecting) return found;
const localY = canvasY - this.pos[1] - Number(card.widget.y) - WRAPPER_TOP;
for (const entry of card.entries) {
const name = entry.names?.[0];
const top = card.rowTop.get(name);
if (top !== undefined && localY >= top && localY <= top + (card.rowSpan.get(name) ?? ROW_HEIGHT)) return findWidget(this, name) ?? found;
}
return found;
};
}
function refresh() {
if (card.disposed) return;
const vals = values();
const open = {};
for (const entry of card.entries) if (entry.header) open[entry.row.group] = groupOpen(entry.row.group);
const shown = visibleRows(card.entries.map((entry) => entry.row), vals, open, node);
const shownSet = new Set(shown);
const tops = rowTops(shown);
card.rowTop = new Map();
card.rowSpan = new Map();
shown.forEach((row, index) => {
const entry = card.entries.find((item) => item.row === row);
for (const name of entry.names ?? []) {
card.rowTop.set(name, tops[index]);
card.rowSpan.set(name, rowHeight(row));
}
if (entry.header) card.rowTop.set(`group:${row.group}`, tops[index]);
});
for (const entry of card.entries) {
if (!entry.names || shownSet.has(entry.row) || !entry.row.inGroup) continue;
const headerTop = card.rowTop.get(`group:${entry.row.inGroup}`);
if (headerTop === undefined) continue;
for (const name of entry.names) {
card.rowTop.set(name, headerTop);
card.rowSpan.set(name, GROUP_HEIGHT);
}
}
for (const entry of card.entries) {
const show = shownSet.has(entry.row);
entry.element.classList.toggle("hidden", !show);
if (entry.header) entry.element.classList.toggle("open", open[entry.row.group]);
if (!show) continue;
if (entry.row.panel && !entry.row.grow && typeof entry.row.height === "function") entry.element.style.height = `${rowHeight(entry.row)}px`;
const linkedNames = (entry.names ?? []).filter((name) => widgetLinked(node, name));
const linked = linkedNames.length > 0 && linkedNames.length === entry.names.length;
entry.element.classList.toggle("linked", linked);
for (const [name, field] of entry.fields ?? []) field.classList.toggle("linked", linkedNames.includes(name));
for (const sync of entry.syncs) sync(vals, linked);
}
const height = cardHeight(shown);
if (height !== card.height) {
const change = card.height ? height - card.height : 0;
card.height = height;
// A row opened by hand moves the node's height with it, so a preview
// under the card keeps its size; anything else keeps the node's height,
// lifted to the floor.
const current = Number(node.size?.[1]) || 0;
const target = card.byHand && !card.restoring ? current + change : current;
const floor = Number(node.computeSize?.()?.[1]) || 0;
node.setSize?.([Math.max(minWidth, node.size?.[0] || minWidth), Math.max(floor, target)]);
node.graph?.setDirtyCanvas?.(true, true);
}
node._widgetSlotsDirty = true;
}
card.refresh = refresh;
// For a node that changes which rows show from its own controls (a tool
// switch): the node's height follows the card, as for a group opened by hand.
card.refreshByHand = () => {
card.byHand = true;
try {
refresh();
} finally {
card.byHand = false;
}
};
for (const name of managed) {
const target = findWidget(node, name);
if (target) chainCallback(target, "callback", () => refresh());
}
chainCallback(node, "onConfigure", () => {
card.restoring = true;
queueMicrotask(() => {
try {
for (const name of managed) hideWidget(findWidget(node, name));
refresh();
} finally {
card.restoring = false;
}
// A workflow saved before the card existed sized the node for the
// stock widgets; give the card and its panels their floors.
ensureNodeMinHeight(node);
});
});
chainCallback(node, "onConnectionsChange", () => queueMicrotask(refresh));
chainCallback(node, "onRemoved", () => {
card.disposed = true;
for (const restore of socketed) restore();
if (typeof originalGetWidgetOnPos === "function") delete node.getWidgetOnPos;
});
refresh();
return card;
}
+65
View File
@@ -0,0 +1,65 @@
// Pure decisions behind card.js: which rows show, how tall the card is,
// where each row sits and what control a widget gets. No DOM, for node:test.
import { CARD_PADDING, GROUP_HEIGHT, ROW_GAP, ROW_HEIGHT, SECTION_HEIGHT } from "./theme.js";
// A widget input socket is drawn at the widget's y plus half a slot.
export const SLOT_OFFSET = 10;
const SEGMENT_MAX_OPTIONS = 4;
const SEGMENT_MAX_CHARS = 26;
export const isGroupHeader = (row) => row.group !== undefined && row.widget === undefined && row.pair === undefined && !row.panel && !row.control && row.section === undefined;
// Rows the current values leave visible. `open` maps a group to its state.
export function visibleRows(rows, values, open = {}, node = null) {
return rows.filter((row) => {
if (row.when && row.when(values, node) === false) return false;
if (isGroupHeader(row)) return true;
return !(row.inGroup && !open[row.inGroup]);
});
}
export function rowHeight(row) {
if (row.section !== undefined) return SECTION_HEIGHT;
if (row.panel) return Number(typeof row.height === "function" ? row.height() : row.height) || ROW_HEIGHT;
if (isGroupHeader(row)) return GROUP_HEIGHT;
return ROW_HEIGHT;
}
export function cardHeight(rows) {
if (!rows.length) return CARD_PADDING * 2;
return CARD_PADDING * 2 + rows.reduce((sum, row) => sum + rowHeight(row), 0) + ROW_GAP * (rows.length - 1);
}
export function rowTops(rows) {
let y = CARD_PADDING;
return rows.map((row) => {
const top = y;
y += rowHeight(row) + ROW_GAP;
return top;
});
}
// The y a hidden widget reports so its socket sits level with its row.
export function socketWidgetY(cardY, insetTop, rowTop, height) {
return cardY + insetTop + rowTop + Math.min(height / 2, 13) - SLOT_OFFSET;
}
export function segmentFits(labels) {
if (labels.length < 2 || labels.length > SEGMENT_MAX_OPTIONS) return false;
return labels.reduce((sum, label) => sum + String(label).length, 0) <= SEGMENT_MAX_CHARS;
}
export function choiceLabel(row, value, values = [], node = null) {
const own = typeof row?.labels === "function" ? row.labels(value, values, node) : row?.labels?.[value];
return own ?? String(value);
}
// Row kind from the widget it mirrors, unless the row names one.
export function rowKind(row, widget, values = []) {
if (row.kind) return row.kind;
const type = String(widget?.type ?? "");
if (type === "number" || type === "slider" || type === "INT" || type === "FLOAT") return "scrub";
if (type === "combo" || type === "COMBO") return segmentFits(values.map((value) => choiceLabel(row, value, values))) ? "segment" : "select";
if (type === "toggle" || type === "BOOLEAN") return "switch";
return "text";
}
+40
View File
@@ -0,0 +1,40 @@
// Helpers that need the ComfyUI app.
import { app } from "../../../scripts/app.js";
export function isVueNodes() {
return globalThis.LiteGraph?.vueNodesMode === true;
}
// One toast for every message; never alert(). Falls back to the console and
// never throws, so a message cannot break the action that raised it.
export function toast(detail, { severity = "info", summary = "", life = 5000 } = {}) {
try {
const store = app?.extensionManager?.toast;
if (typeof store?.add === "function") {
store.add({ severity, summary, detail, life });
return;
}
} catch {
// Fall through to the console.
}
(severity === "error" || severity === "warn" ? console.warn : console.log)(`${summary ? `${summary}: ` : ""}${detail}`);
}
// The undo/dirty tracker snapshots on canvas mouse-up, but our DOM panels
// commit values a phase later. Call once per user gesture, after the write,
// and never from a workflow-load path.
let changeTimer = null;
export function notifyChange() {
clearTimeout(changeTimer);
changeTimer = setTimeout(() => {
changeTimer = null;
try {
const workflow = app?.extensionManager?.workflow?.activeWorkflow;
const tracker = workflow?.changeTracker;
if (typeof tracker?.captureCanvasState === "function") tracker.captureCanvasState();
else tracker?.checkState?.();
} catch {
// The write itself already succeeded.
}
}, 120);
}
+337
View File
@@ -0,0 +1,337 @@
// Stand-alone controls for panels that are not card rows (a toolbar over a
// preview, a modal footer). Card rows build on the same classes.
import { chainCallback, chainHandler, el } from "./dom.js";
// button("Browse", { icon, title, primary, soft, danger, small, grow, onClick })
// soft: the suite's blue action button (Save, New, More).
export function button(label, { icon = "", title = "", primary = false, soft = false, danger = false, small = false, grow = false, onClick = null } = {}) {
const node = el("button", "fbui-btn");
node.type = "button";
node.classList.toggle("primary", primary);
node.classList.toggle("soft", soft);
node.classList.toggle("danger", danger);
node.classList.toggle("small", small);
node.classList.toggle("grow", grow);
// An icon alone is a square button the height of a row.
node.classList.toggle("icon", Boolean(icon) && !label);
if (icon) node.insertAdjacentHTML("beforeend", icon);
if (label) node.append(el("span", "", label));
if (title) node.title = title;
if (onClick) node.addEventListener("click", (event) => onClick(event));
return node;
}
// The help popover: `lines` under (or over) `anchor`, a client-pixel box
// { left, top, bottom }. It stays until a click outside it (or Esc), so the
// text can be selected and copied; a click on a token copies that token.
// `lines` are strings, or [code, text] pairs shown as a two-column list
// (tokens and what they do). Returns close().
export function openHelp(lines, anchor, { keep = null, onClose = null } = {}) {
const pop = el("div", "fbui-pop");
pop.tabIndex = -1;
for (const line of lines) {
if (Array.isArray(line)) {
const row = el("div", "pair");
const code = el("code", "", line[0]);
code.title = "Click to copy";
code.addEventListener("click", () => {
navigator.clipboard?.writeText(line[0]).then(() => {
code.classList.add("copied");
setTimeout(() => code.classList.remove("copied"), 900);
});
});
row.append(code, el("span", "", line[1]));
pop.append(row);
} else {
pop.append(el("div", "", line));
}
}
const close = () => {
pop.remove();
document.removeEventListener("pointerdown", outside, true);
document.removeEventListener("keydown", onEscape, true);
onClose?.();
};
// A press on `keep` (the control that opened it) is that control's to handle.
const outside = (event) => {
if (!pop.contains(event.target) && !keep?.contains(event.target)) close();
};
const onEscape = (event) => {
if (event.key === "Escape") close();
};
// Keys typed here (Ctrl+C on a selection) are the popover's, not the canvas's.
pop.addEventListener("keydown", (event) => event.stopPropagation());
document.body.append(pop);
pop.style.left = `${Math.max(8, Math.min(window.innerWidth - pop.offsetWidth - 8, anchor.left))}px`;
const below = anchor.bottom + 6;
pop.style.top = `${below + pop.offsetHeight > window.innerHeight - 8 ? Math.max(8, anchor.top - pop.offsetHeight - 6) : below}px`;
pop.focus({ preventScroll: true });
document.addEventListener("pointerdown", outside, true);
document.addEventListener("keydown", onEscape, true);
return close;
}
// A small (i) beside a label; a click opens `lines` (see openHelp).
export function info(lines) {
const icon = el("span", "fbui-info");
icon.innerHTML = ICONS.info;
icon.title = "Help";
let close = null;
icon.addEventListener("click", (event) => {
event.stopPropagation();
if (close) return close();
icon.classList.add("on");
close = openHelp(lines, icon.getBoundingClientRect(), {
keep: icon,
onClose: () => {
close = null;
icon.classList.remove("on");
},
});
});
return icon;
}
// The node's help as a "?" at the right of its title bar, where most packs
// put it; a click opens `lines` (see openHelp). Nodes 2.0 draws no title
// badges, so there it is "About this node" in the node's menu.
const BADGE_INSET = 16;
const BADGE_MIN_WIDTH = 140;
function badgeShown(node) {
return !node.flags?.collapsed && (node.size?.[0] ?? 0) >= BADGE_MIN_WIDTH;
}
export function helpBadge(node, lines) {
const centerY = -(globalThis.LiteGraph?.NODE_TITLE_HEIGHT ?? 30) / 2;
chainCallback(node, "onDrawForeground", function (ctx) {
if (!badgeShown(this)) return;
ctx.save();
ctx.fillStyle = "rgba(255,255,255,0.9)";
ctx.font = "bold 19px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("?", this.size[0] - BADGE_INSET, centerY + 1);
ctx.restore();
});
chainHandler(node, "onMouseDown", function (event, pos) {
if (!badgeShown(this) || !pos) return false;
if (Math.abs(pos[0] - (this.size[0] - BADGE_INSET)) > 10 || Math.abs(pos[1] - centerY) > 11) return false;
openHelp(lines, { left: event.clientX - 150, top: event.clientY, bottom: event.clientY + 6 });
// Consumed, so the click does not start a drag.
return true;
});
chainCallback(node, "getExtraMenuOptions", function (_canvas, options) {
if (!globalThis.LiteGraph?.vueNodesMode) return;
options.unshift({ content: "About this node", callback: () => openHelp(lines, { left: window.innerWidth / 2 - 150, top: 80, bottom: 80 }) });
});
}
// A row of pill choices: segmented([{ value, label, title }], { onPick, bool })
// -> { root, set(value) }.
export function segmented(choices, { onPick, bool = false } = {}) {
const root = el("div", bool ? "fbui-seg fbui-bool" : "fbui-seg");
const buttons = new Map();
for (const choice of choices) {
const item = el("button", "", choice.label ?? String(choice.value));
item.type = "button";
item.title = choice.title ?? String(choice.label ?? choice.value);
item.addEventListener("click", () => onPick?.(choice.value));
root.append(item);
buttons.set(choice.value, item);
}
return {
root,
set(value) {
for (const [key, item] of buttons) item.classList.toggle("on", key === value);
},
};
}
// A slide handle (↔ or ↕) at the start of a row's fields: dragging it
// reports the pointer's sideways travel for either axis, as every slider
// here moves sideways (right is right, or down).
export function slideHandle({ axis = "x", title = "", onStart, onSlide, onEnd } = {}) {
const handle = el("span", "fbui-slide");
handle.insertAdjacentHTML("beforeend", axis === "x" ? ICONS.slideX : ICONS.slideY);
handle.title = title;
handle.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
handle.setPointerCapture(event.pointerId);
handle.classList.add("on");
const zoom = handle.getBoundingClientRect().width / Math.max(1, handle.offsetWidth) || 1;
const start = event.clientX;
const move = (e) => onSlide?.((e.clientX - start) / zoom);
const end = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
handle.classList.remove("on");
onEnd?.();
};
onStart?.();
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
});
return handle;
}
// A timeline rail with a playhead, for picking a frame: press or drag
// anywhere on it. rail({ onSeek(fraction, settled) }) -> { root, set(fraction), setEnabled(on) }.
// `fraction` is 0..1 along the rail; the caller maps it to its own frames.
export function rail({ onSeek, title = "" } = {}) {
const root = el("div", "fbui-rail");
const fill = el("div", "fbui-rail-fill");
const head = el("div", "fbui-rail-head");
root.append(fill, head);
if (title) root.title = title;
let enabled = true;
const at = (event) => {
const box = root.getBoundingClientRect();
return Math.max(0, Math.min(1, (event.clientX - box.left) / Math.max(1, box.width)));
};
root.addEventListener("pointerdown", (event) => {
if (!enabled || event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
root.setPointerCapture(event.pointerId);
onSeek?.(at(event), false);
});
root.addEventListener("pointermove", (event) => {
if (root.hasPointerCapture(event.pointerId)) onSeek?.(at(event), false);
});
const end = (event) => {
if (!root.hasPointerCapture(event.pointerId)) return;
root.releasePointerCapture(event.pointerId);
onSeek?.(at(event), true);
};
root.addEventListener("pointerup", end);
root.addEventListener("pointercancel", end);
return {
root,
set(fraction) {
const pct = `${Math.max(0, Math.min(1, fraction)) * 100}%`;
head.style.left = pct;
fill.style.width = pct;
},
setEnabled(on) {
enabled = on;
root.classList.toggle("disabled", !on);
},
};
}
// A rail with in and out edges and a playhead, for trimming: press near an
// edge to move it, anywhere else to move the playhead.
// rangeRail({ onEdge(edge, fraction, settled), onSeek(fraction, settled) })
// -> { root, set({ start, stop, head }) } with edge "in" | "out", all 0..1.
export function rangeRail({ onEdge, onSeek, title = "" } = {}) {
const root = el("div", "fbui-rail fbui-range");
const fill = el("div", "fbui-range-fill");
const edgeIn = el("div", "fbui-range-edge");
const edgeOut = el("div", "fbui-range-edge");
const head = el("div", "fbui-rail-head");
root.append(fill, edgeIn, edgeOut, head);
if (title) root.title = title;
let shown = { start: 0, stop: 1, head: 0 };
let drag = null;
const at = (event) => {
const box = root.getBoundingClientRect();
return Math.max(0, Math.min(1, (event.clientX - box.left) / Math.max(1, box.width)));
};
const send = (event, settled) => {
if (drag === "head") onSeek?.(at(event), settled);
else onEdge?.(drag, at(event), settled);
};
root.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
root.setPointerCapture(event.pointerId);
// The nearer edge within 8px; on top of each other, the side pressed.
const width = root.getBoundingClientRect().width;
const x = at(event);
const toIn = Math.abs(x - shown.start) * width;
const toOut = Math.abs(x - shown.stop) * width;
drag = Math.min(toIn, toOut) > 8 ? "head" : toIn < toOut || (toIn === toOut && x < shown.start) ? "in" : "out";
send(event, false);
});
root.addEventListener("pointermove", (event) => {
if (drag && root.hasPointerCapture(event.pointerId)) send(event, false);
});
const end = (event) => {
if (!drag || !root.hasPointerCapture(event.pointerId)) return;
root.releasePointerCapture(event.pointerId);
send(event, true);
drag = null;
};
root.addEventListener("pointerup", end);
root.addEventListener("pointercancel", end);
const pct = (fraction) => `${Math.max(0, Math.min(1, fraction)) * 100}%`;
return {
root,
set(next) {
shown = { ...shown, ...next };
fill.style.left = pct(shown.start);
fill.style.width = pct(shown.stop - shown.start);
edgeIn.style.left = pct(shown.start);
edgeOut.style.left = pct(shown.stop);
head.style.left = pct(shown.head);
},
};
}
// Small stroke icons, drawn in currentColor so they follow the button state.
const svg = (body) => `<svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
export const ICONS = {
folder: svg('<path d="M1.5 4.5v8a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-6a1 1 0 0 0-1-1H8L6.5 3.5h-4a1 1 0 0 0-1 1z"/>'),
play: svg('<path d="M5 3.5v9l7-4.5z" fill="currentColor"/>'),
pause: svg('<path d="M5 3.5v9M11 3.5v9"/>'),
expand: svg('<path d="M10 2.5h3.5V6M6 13.5H2.5V10M13.5 2.5 9 7M2.5 13.5 7 9"/>'),
brush: svg('<path d="M10.5 2.5l3 3-6 6-3-3zM4.5 8.5l-2 5 5-2"/>'),
crop: svg('<path d="M4 1.5V12h10.5M1.5 4H12v10.5"/>'),
feather: svg('<path d="M13.5 2.5C8 2.5 4.5 6 4.5 11.5h2c5.5 0 7-4 7-9z"/><path d="M2.5 13.5l7-7"/>'),
ratio: svg('<rect x="1.5" y="3.5" width="13" height="9" rx="1"/><path d="M4.5 8.5v-2H7M11.5 7.5v2H9"/>'),
slideX: svg('<path d="M1.5 8h13M4.5 5 1.5 8l3 3M11.5 5l3 3-3 3"/>'),
slideY: svg('<path d="M8 1.5v13M5 4.5 8 1.5l3 3M5 11.5l3 3 3-3"/>'),
centerX: svg('<path d="M2 3v10M14 3v10M8 5v6M5 8H4M12 8h-1"/>'),
centerY: svg('<path d="M3 2h10M3 14h10M5 8h6M8 5V4M8 12v-1"/>'),
pad: svg('<rect x="5.5" y="5.5" width="5" height="5" rx=".5"/><path d="M1.5 5V1.5H5M11 1.5h3.5V5M14.5 11v3.5H11M5 14.5H1.5V11"/>'),
rotate: svg('<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3"/><rect x="6" y="6" width="4" height="4" rx=".5"/>'),
rotateLeft: svg('<path d="M2.5 5.5h7a4 4 0 0 1 0 8h-2M5 3 2.5 5.5 5 8"/>'),
rotateRight: svg('<path d="M13.5 5.5h-7a4 4 0 0 0 0 8h2M11 3l2.5 2.5L11 8"/>'),
cropTurn: svg('<path d="M4 1.5V10h6M1.5 4H10v2"/><path d="M14.5 11a3.5 3.5 0 1 1-1-2.5M14.5 7v2h-2"/>'),
scale: svg('<rect x="1.5" y="8.5" width="6" height="6" rx=".5"/><path d="M9.5 1.5h5v5M14.5 1.5 8.5 7.5"/>'),
eraser: svg('<path d="M6 13.5h7.5M2.5 10l6-6.5 5 5-5 5h-3z"/>'),
undo: svg('<path d="M4.5 6.5h6a3 3 0 0 1 0 6h-3M6.5 4l-2.5 2.5L6.5 9"/>'),
redo: svg('<path d="M11.5 6.5h-6a3 3 0 0 0 0 6h3M9.5 4l2.5 2.5L9.5 9"/>'),
trash: svg('<path d="M2.5 4.5h11M6 4.5V3h4v1.5M4 4.5l.7 9h6.6l.7-9"/>'),
flipX: svg('<path d="M8 1.5v13M6 4 2 12h4zM10 4l4 8h-4z"/>'),
flipY: svg('<path d="M1.5 8h13M4 6 12 2v4zM4 10l8 4v-4z"/>'),
reset: svg('<path d="M2.5 8a5.5 5.5 0 1 0 1.6-3.9M2.5 2.5v3h3"/>'),
close: svg('<path d="M3.5 3.5l9 9M12.5 3.5l-9 9"/>'),
invert: svg('<circle cx="8" cy="8" r="5.5"/><path d="M8 2.5v11a5.5 5.5 0 0 0 0-11z" fill="currentColor"/>'),
eye: svg('<path d="M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>'),
info: svg('<circle cx="8" cy="8" r="6.5"/><path d="M8 7.2V11.5M8 4.6v.1"/>'),
open: svg('<path d="M9.5 2.5h4v4M13.5 2.5 8 8M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>'),
up: svg('<path d="M8 13.5v-11M3.5 7 8 2.5 12.5 7"/>'),
refresh: svg('<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3"/>'),
chevronUp: svg('<path d="M3.5 10 8 5.5l4.5 4.5"/>'),
chevronLeft: svg('<path d="M10 3.5 5.5 8l4.5 4.5"/>'),
chevronRight: svg('<path d="M6 3.5 10.5 8 6 12.5"/>'),
check: svg('<path d="M3 8.5 6.5 12 13 4.5"/>'),
grip: svg('<g fill="currentColor" stroke="none"><circle cx="6" cy="4" r="1.1"/><circle cx="10" cy="4" r="1.1"/><circle cx="6" cy="8" r="1.1"/><circle cx="10" cy="8" r="1.1"/><circle cx="6" cy="12" r="1.1"/><circle cx="10" cy="12" r="1.1"/></g>'),
scissors: svg('<circle cx="4" cy="4.5" r="2"/><circle cx="4" cy="11.5" r="2"/><path d="M5.7 5.6 13.5 12M5.7 10.4 13.5 4"/>'),
timer: svg('<circle cx="8" cy="9" r="5.5"/><path d="M8 6v3l2 1.5M6.5 1.5h3"/>'),
chevronDown: svg('<path d="M3.5 6 8 10.5 12.5 6"/>'),
grid: svg('<rect x="2" y="2" width="5" height="5" rx="1"/><rect x="9" y="2" width="5" height="5" rx="1"/><rect x="2" y="9" width="5" height="5" rx="1"/><rect x="9" y="9" width="5" height="5" rx="1"/>'),
tiles: svg('<path d="M2 2h3v3H2zM6.5 2h3v3h-3zM11 2h3v3h-3zM2 6.5h3v3H2zM6.5 6.5h3v3h-3zM11 6.5h3v3h-3zM2 11h3v3H2zM6.5 11h3v3h-3zM11 11h3v3h-3z"/>'),
list: svg('<path d="M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.5M2.5 8h.5M2.5 12h.5"/>'),
search: svg('<circle cx="7" cy="7" r="4.5"/><path d="M10.5 10.5 14 14"/>'),
film: svg('<rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M5 3v10M11 3v10M2 6h3M2 10h3M11 6h3M11 10h3"/>'),
music: svg('<path d="M6 12V3.5l7.5-1.5V10.5"/><circle cx="4.5" cy="12" r="1.8"/><circle cx="12" cy="10.5" r="1.8"/>'),
file: svg('<path d="M4 1.5h5.5L13 5v9.5H4zM9.5 1.5V5H13"/>'),
};
+52
View File
@@ -0,0 +1,52 @@
// Plain DOM and LiteGraph-object helpers. No imports, so node:test can load
// everything that builds on them.
export function el(tag, className = "", text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
// Wrap a callback without clobbering whoever hooked it first. Other packs
// patch the same objects, so never assign `obj[name] = fn` directly.
export function chainCallback(obj, name, fn) {
const prior = obj[name];
obj[name] = function (...args) {
const result = prior?.apply(this, args);
fn.apply(this, args);
return result;
};
}
// chainCallback for handlers whose truthy return means "consumed".
export function chainHandler(obj, name, fn) {
const prior = obj[name];
obj[name] = function (...args) {
const result = prior?.apply(this, args);
const handled = fn.apply(this, args);
return result || handled;
};
}
// The frontend sizes a DOM widget's wrapper as `widget.width ?? node.width`,
// and LiteGraph plants widget.width during draws, after which the wrapper no
// longer follows the node when it is resized narrower. Discard those writes.
export function keepDomWidgetWidthAuto(widget) {
if (!widget) return widget;
try {
Object.defineProperty(widget, "width", { get: () => undefined, set: () => {}, configurable: true });
} catch {
// A frozen widget keeps the frontend's behaviour.
}
return widget;
}
// App shortcuts (Ctrl+Enter, Ctrl+S) go on to ComfyUI; every other key typed
// in one of our fields stays in the field so the canvas never acts on it.
const FIELD_EDIT_KEYS = new Set(["a", "c", "v", "x", "z", "y", "backspace", "delete", "arrowleft", "arrowright", "arrowup", "arrowdown", "home", "end"]);
export function keepKeyInField(event) {
const appShortcut = (event.ctrlKey || event.metaKey) && !FIELD_EDIT_KEYS.has(String(event.key ?? "").toLowerCase());
if (!appShortcut) event.stopPropagation();
}
+136
View File
@@ -0,0 +1,136 @@
// How a DOM panel claims its share of a node's height, in both renderers.
// No imports, so node:test can load it.
//
// The classic frontend arranges widgets in one pass:
// if (w.computeSize) -> fixed height, kept out of the split
// else if (w.computeLayoutSize) -> shares the node's free height
// so a growing panel must not carry a computeSize, and a fixed one should.
//
// DomWidgets insets an element by options.margin per side (default 10), so
// the element gets this much less height than the layout hands the widget.
export const WIDGET_FRAME = 20;
const resolve = (value) => {
const number = Number(typeof value === "function" ? value() : value);
return Number.isFinite(number) ? Math.max(0, number) : 0;
};
// The frontend pads a DOM widget's minWidth before it becomes the node's
// floor (the room a number widget's value box takes). Measure that padding
// once from the frontend itself instead of copying its constants.
const PROBE_WIDTH = 100000;
let probing = false;
let widthPadding = null;
function measureWidthPadding(node, widget) {
if (probing || typeof node?.computeSize !== "function") return null;
const own = widget.computeLayoutSize;
probing = true;
widget.computeLayoutSize = () => ({ minWidth: PROBE_WIDTH, minHeight: 0 });
let width = NaN;
try {
width = Number(node.computeSize()?.[0]);
} catch {
// Measured next time.
} finally {
widget.computeLayoutSize = own;
probing = false;
}
return Number.isFinite(width) && width >= PROBE_WIDTH ? width - PROBE_WIDTH : null;
}
// A node can carry several panels; its width floor is the widest of them.
const FLOORS = Symbol.for("fbui.widthFloors");
function nodeWidthFloor(node) {
let floor = 0;
for (const value of node?.[FLOORS]?.values() ?? []) floor = Math.max(floor, resolve(value));
return floor;
}
// Nodes 2.0 lays a node out by its content and has no layout API for
// minimums: lend it the floors as inline CSS on the node element and panel.
function holdVueMinWidth(panel, width) {
const host = panel?.closest?.("[data-node-id]");
if (!host?.style || !(width > 0)) return;
const css = `${Math.round(width)}px`;
if (host.style.minWidth !== css) host.style.minWidth = css;
}
function holdVueMinHeight(panel, height) {
if (!panel?.style) return;
const inside = Boolean(panel.closest?.("[data-node-id]"));
const css = inside && height > 0 ? `${Math.round(height)}px` : "";
if ((panel.style.minHeight || "") !== css) panel.style.minHeight = css;
}
// One ResizeObserver per panel; the Vue node element only exists around a
// panel once it has been laid out inside it.
const WATCHED = Symbol.for("fbui.layoutWatch");
function whenLaidOut(panel, name, task) {
if (!panel || typeof ResizeObserver !== "function") return;
if (!panel[WATCHED]) {
const tasks = new Map();
panel[WATCHED] = tasks;
new ResizeObserver(() => { for (const run of tasks.values()) run(); }).observe(panel);
}
panel[WATCHED].set(name, task);
}
// Make `minWidth` a real floor for the node in both renderers: the classic
// corner drag stops at node.computeSize(), Nodes 2.0 at the host's min-width.
export function holdNodeMinWidth(widget, minWidth) {
const node = widget?.node;
if (!node) return widget;
if (!node[FLOORS]) {
node[FLOORS] = new Map();
const inherited = node.computeSize;
node.computeSize = function (out) {
const size = inherited.call(this, out);
const floor = nodeWidthFloor(this);
if (size && size[0] < floor) size[0] = floor;
return size;
};
}
node[FLOORS].set(widget, minWidth);
whenLaidOut(widget.element, "width", () => holdVueMinWidth(widget.element, nodeWidthFloor(node)));
return widget;
}
// A panel that takes whatever height the node has left over (a preview).
export function fillNodeHeight(widget, { minWidth = 0, minHeight = 0 } = {}) {
if (!widget) return widget;
const panel = widget.element;
const holdHeight = (height) => holdVueMinHeight(panel, height - WIDGET_FRAME);
delete widget.computeSize;
widget.computeLayoutSize = (node) => {
const height = resolve(minHeight);
holdHeight(height);
if (widthPadding === null) widthPadding = measureWidthPadding(node ?? widget.node, widget);
return { minWidth: Math.max(0, resolve(minWidth) - (widthPadding ?? 0)), minHeight: height };
};
holdNodeMinWidth(widget, minWidth);
whenLaidOut(panel, "height", () => holdHeight(resolve(minHeight)));
return widget;
}
// A panel that keeps its own height (a card whose height is its rows).
// Nodes 2.0 gives any widget with a computeLayoutSize a share of the spare
// height, and every DOM widget inherits one, so shadow it.
export function pinHeight(widget, height, minWidth = 0) {
if (!widget) return widget;
widget.computeSize = (width) => [Math.max(minWidth, Number(width) || 0), resolve(height)];
widget.computeLayoutSize = undefined;
if (minWidth) holdNodeMinWidth(widget, minWidth);
return widget;
}
// Grow a node to the height its widgets ask for: a workflow saved before a
// panel existed carries the node's old, smaller size.
export function ensureNodeMinHeight(node) {
const min = Number(node?.computeSize?.()?.[1]);
const current = Number(node?.size?.[1]);
if (!Number.isFinite(min) || !Number.isFinite(current) || current >= min) return false;
node.setSize?.([node.size[0], min]);
return true;
}
+233
View File
@@ -0,0 +1,233 @@
// Modals and context menus in the kit's look. One backdrop, one z-index
// scale, Escape and a click outside close, and keys typed inside stay out of
// the canvas.
import { el } from "./dom.js";
import { button, ICONS } from "./controls.js";
import { ensureKitCss, T, Z_MODAL } from "./theme.js";
// Open modals, newest last: Escape closes only the top one.
const stack = [];
// Whether a kit modal, menu or viewer is open: node shortcuts stand aside.
export const modalOpen = () => stack.length > 0;
// openModal({ title, body, footer, width, height, closable, onClose }) -> { overlay, modal, body, close, isTop }.
// `body` and `footer` are elements (or arrays of elements). closable: false
// takes away the close button, Escape and the backdrop click, for a dialog
// that must end with one of its own buttons.
export function openModal({ title = "", body = null, footer = null, width = null, height = null, closable = true, onClose = null } = {}) {
ensureKitCss();
const overlay = el("div", "fbui-overlay");
const modal = el("div", "fbui-modal");
const size = (value) => (typeof value === "number" ? `${value}px` : value);
if (width) modal.style.width = size(width);
if (height) modal.style.height = size(height);
const head = el("div", "fbui-modal-head");
head.append(el("span", "title", title));
const close = () => {
if (!overlay.isConnected) return;
overlay.remove();
stack.splice(stack.indexOf(close), 1);
document.removeEventListener("keydown", onKey, true);
onClose?.();
};
if (closable) head.append(button("", { icon: ICONS.close, small: true, title: "Close (Esc)", onClick: close }));
modal.append(head);
const content = el("div", "fbui-modal-body");
for (const item of [body].flat()) if (item) content.append(item);
modal.append(content);
if (footer) {
const foot = el("div", "fbui-modal-foot");
for (const item of [footer].flat()) if (item) foot.append(item);
modal.append(foot);
}
overlay.append(modal);
const onKey = (event) => {
if (!closable || event.key !== "Escape" || stack[stack.length - 1] !== close) return;
event.stopPropagation();
close();
};
overlay.addEventListener("pointerdown", (event) => {
if (closable && event.target === overlay) close();
});
overlay.addEventListener("keydown", (event) => event.stopPropagation());
document.addEventListener("keydown", onKey, true);
document.body.append(overlay);
stack.push(close);
return { overlay, modal, body: content, close, isTop: () => stack[stack.length - 1] === close };
}
// prompt({ title, message, value, placeholder, confirmText }) -> Promise<string | null>:
// the trimmed text on OK or Enter, null on Cancel or Escape.
export function prompt({ title = "", message = "", value = "", placeholder = "", confirmText = "OK" } = {}) {
return new Promise((resolve) => {
let answer = null;
const field = el("input", "fbui-text");
field.type = "text";
field.spellcheck = false;
field.value = value;
field.placeholder = placeholder;
field.style.width = "min(520px, 70vw)";
const text = el("div", "", message);
text.style.cssText = "margin-bottom:8px;max-width:520px;line-height:1.45;color:" + T.label;
const accept = () => {
answer = field.value.trim() || null;
dialog.close();
};
field.addEventListener("keydown", (event) => {
if (event.key === "Enter") accept();
});
const dialog = openModal({
title,
body: [message ? text : null, field],
footer: [button("Cancel", { onClick: () => dialog.close() }), button(confirmText, { primary: true, onClick: accept })],
onClose: () => resolve(answer),
});
dialog.overlay.style.zIndex = String(Z_MODAL + stack.length);
field.focus();
field.select();
});
}
// confirm({ title, message, confirmText, danger }) -> Promise<boolean>.
export function confirm({ title = "Are you sure?", message = "", confirmText = "OK", danger = false } = {}) {
return new Promise((resolve) => {
let answer = false;
const text = el("div", "", message);
text.style.cssText = "max-width:420px;line-height:1.45";
const cancel = button("Cancel", { onClick: () => dialog.close() });
const ok = button(confirmText, { primary: !danger, danger, onClick: () => { answer = true; dialog.close(); } });
if (danger) ok.style.background = T.danger;
const dialog = openModal({ title, body: text, footer: [cancel, ok], onClose: () => resolve(answer) });
dialog.overlay.style.zIndex = String(Z_MODAL + stack.length);
ok.focus();
});
}
// openMenu(clientX, clientY, [{ label, action, disabled, danger } | null]) at
// the pointer (null: a separator), kept inside the viewport; closes on pick
// or any outside press.
export function openMenu(x, y, items) {
ensureKitCss();
document.querySelector(".fbui-menu")?.remove();
const menu = el("div", "fbui-menu");
const close = () => {
menu.remove();
document.removeEventListener("pointerdown", outside, true);
};
const outside = (event) => {
if (menu.contains(event.target)) return;
close();
// The press that closes the menu must not also click what is under it.
const swallow = (click) => {
click.stopPropagation();
click.preventDefault();
};
document.addEventListener("click", swallow, { capture: true, once: true });
setTimeout(() => document.removeEventListener("click", swallow, true), 400);
};
for (const item of items) {
// null: a separator between groups of items.
if (!item) {
menu.append(el("div", "sep"));
continue;
}
const entry = el("button", item.danger ? "danger" : "", item.label);
entry.type = "button";
entry.disabled = Boolean(item.disabled);
if (item.disabled) entry.style.opacity = ".45";
entry.addEventListener("click", () => {
close();
item.action?.();
});
menu.append(entry);
}
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
document.body.append(menu);
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) menu.style.left = `${Math.max(0, x - rect.width)}px`;
if (rect.bottom > window.innerHeight) menu.style.top = `${Math.max(0, y - rect.height)}px`;
setTimeout(() => document.addEventListener("pointerdown", outside, true), 0);
return { menu, close };
}
// openViewer([{ url, title, video?, fallback?, where? }], index, { step? }):
// the picture (or video) as large as the screen allows over a darkened
// ComfyUI. ←/→ and the ‹ › buttons step through several (while a video
// plays the keys seek it instead), Esc or a click on the dark closes. `fallback` is an image URL shown when the browser cannot
// play a video. With `step(direction)` the caller does the stepping instead
// and returns the item to show (null to stay); `where` labels its position.
export function openViewer(items, index = 0, { step = null } = {}) {
ensureKitCss();
if (!items.length) return;
const root = el("div", "fbui-viewer");
const stage = el("div", "stage");
const name = el("div", "name");
const where = el("div", "where");
const close = () => {
root.remove();
stack.splice(stack.indexOf(close), 1);
document.removeEventListener("keydown", onKey, true);
};
const prev = button("", { icon: ICONS.chevronLeft, title: "Previous (←)", onClick: () => move(-1) });
const next = button("", { icon: ICONS.chevronRight, title: "Next (→)", onClick: () => move(1) });
prev.classList.add("nav", "prev");
next.classList.add("nav", "next");
const shut = button("", { icon: ICONS.close, title: "Close (Esc)", onClick: close });
shut.classList.add("shut");
let at = 0;
function show(next) {
at = (next + items.length) % items.length;
const item = items[at];
let media;
if (item.video) {
media = el("video");
Object.assign(media, { controls: true, autoplay: true, loop: true, playsInline: true, src: item.url });
if (item.fallback) {
media.addEventListener("error", () => {
const still = el("img");
still.src = item.fallback;
media.replaceWith(still);
});
}
} else {
media = el("img");
media.src = item.url;
media.draggable = false;
}
stage.replaceChildren(media);
// Focused, a video takes ← / → itself (seeking) and Space.
if (item.video) media.focus({ preventScroll: true });
name.textContent = item.title ?? "";
name.title = item.title ?? "";
where.textContent = item.where ?? `${at + 1} / ${items.length}`;
where.hidden = !where.textContent || (!step && items.length < 2);
}
function move(direction) {
if (!step) return show(at + direction);
const item = step(direction);
if (!item) return;
items = [item];
show(0);
}
const onKey = (event) => {
if (stack[stack.length - 1] !== close) return;
if (event.key === "Escape") close();
else if (stage.firstChild?.tagName === "VIDEO" && (event.key === "ArrowLeft" || event.key === "ArrowRight")) return;
else if ((step || items.length > 1) && (event.key === "ArrowLeft" || event.key === "ArrowRight")) move(event.key === "ArrowRight" ? 1 : -1);
else return;
event.preventDefault();
event.stopPropagation();
};
root.addEventListener("pointerdown", (event) => {
if (event.target === root || event.target === stage) close();
});
prev.hidden = next.hidden = !step && items.length < 2;
root.append(stage, name, where, shut, prev, next);
document.body.append(root);
document.addEventListener("keydown", onKey, true);
stack.push(close);
show(index);
return { close };
}
+108
View File
@@ -0,0 +1,108 @@
// Graph zoom and pan over our panels, and files dropped on them.
//
// A panel that takes the mouse also swallows the wheel, so the graph stopped
// zooming the moment the pointer crossed a card or preview. One listener hands
// those gestures back to the canvas, unless the element under the pointer can
// still scroll that way. In the classic renderer a file dropped on a panel
// missed its node; the drop listeners hand it to the node under the pointer.
//
// Every pack carrying the kit calls installPassthrough(); the first one wins,
// and it serves the `fbui-` panels of all of them.
import { app } from "../../../scripts/app.js";
const INSTALLED = Symbol.for("fbui.passthrough");
const WRAPPERS = ".dom-widget, .lg-node-widgets";
const isOurs = (element) => typeof element?.className === "string" && element.className.includes("fbui-");
function panelRoot(target) {
const host = target?.closest?.(WRAPPERS);
if (!host) return null;
let root = null;
for (let element = target; element && element !== host; element = element.parentElement) if (isOurs(element)) root = element;
if (!root && target === host && host.matches(".dom-widget")) root = Array.from(host.children).find(isOurs) ?? null;
return root;
}
function canScroll(element, delta, horizontal) {
if (!delta) return false;
const size = horizontal ? element.scrollWidth : element.scrollHeight;
const visible = horizontal ? element.clientWidth : element.clientHeight;
const start = horizontal ? element.scrollLeft : element.scrollTop;
if (size - visible <= 1) return false;
return delta > 0 ? start + visible < size - 1 : start > 0;
}
function panelKeepsWheel(target, event, root) {
if (event.ctrlKey || event.metaKey) return false;
for (let element = target; element && element !== root.parentElement; element = element.parentElement) {
const style = getComputedStyle(element);
if (/(auto|scroll)/.test(style.overflowY) && canScroll(element, event.deltaY, false)) return true;
if (/(auto|scroll)/.test(style.overflowX) && canScroll(element, event.deltaX, true)) return true;
}
return false;
}
let forwardedPointer = null;
function onWheel(event) {
const root = panelRoot(event.target);
if (!root || !app.canvas || event.defaultPrevented || panelKeepsWheel(event.target, event, root)) return;
event.preventDefault();
app.canvas.processMouseWheel(event);
}
// Middle-button pan starts over a panel too.
function onPointerDown(event) {
if (!app.canvas || event.button !== 1 || !panelRoot(event.target)) return;
forwardedPointer = event.pointerId;
event.preventDefault();
event.stopPropagation();
app.canvas.processMouseDown(event);
}
function onPointerMove(event) {
if (forwardedPointer === event.pointerId) app.canvas?.processMouseMove(event);
}
function onPointerEnd(event) {
if (forwardedPointer !== event.pointerId) return;
forwardedPointer = null;
app.canvas?.processMouseUp(event);
}
function dropTaker(event) {
const types = Array.from(event.dataTransfer?.types ?? []);
if (!types.includes("Files") || !event.target?.closest?.(".dom-widget") || !panelRoot(event.target)) return null;
const canvas = app.canvas;
if (typeof canvas?.adjustMouseEvent !== "function") return null;
canvas.adjustMouseEvent(event);
const node = canvas.graph?.getNodeOnPos?.(event.canvasX, event.canvasY);
return typeof node?.onDragDrop === "function" && node.onDragOver?.(event) ? node : null;
}
function onDragOver(event) {
if (!dropTaker(event)) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
}
async function onDrop(event) {
const node = dropTaker(event);
if (!node) return;
// The node takes the file; ComfyUI's own handler would add a new node.
event.preventDefault();
event.stopPropagation();
await node.onDragDrop(event);
}
export function installPassthrough() {
if (globalThis[INSTALLED]) return;
globalThis[INSTALLED] = true;
window.addEventListener("wheel", onWheel, { passive: false });
window.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("pointermove", onPointerMove, true);
window.addEventListener("pointerup", onPointerEnd, true);
window.addEventListener("pointercancel", onPointerEnd, true);
window.addEventListener("dragover", onDragOver, true);
window.addEventListener("drop", onDrop, true);
}
+245
View File
@@ -0,0 +1,245 @@
// The kit's number control: drag left/right to scrub, click to type a value
// or a sum (1024*1.5), chevrons or ArrowUp/Down to step, Shift for the fine
// step. Pure math first (node:test), DOM factory below.
import { keepKeyInField } from "./dom.js";
export const SCRUB_DEAD_ZONE = 3;
export const SCRUB_PIXELS_PER_STEP = 4;
// Shift on a box with no finer step slows the drag by this much instead.
export const SCRUB_SLOW_FACTOR = 4;
export function quantize(value, { min = -Infinity, max = Infinity, decimals = 2 } = {}) {
const number = Number(value);
if (!Number.isFinite(number)) return quantize(min === -Infinity ? 0 : min, { min, max, decimals });
const factor = 10 ** Math.max(0, decimals);
return Math.round(Math.max(min, Math.min(max, number)) * factor) / factor;
}
// A sum typed into a number box: + - * / %, brackets and signs. Returns the
// answer, or null when the text is not a sum that comes to a finite number.
const SUM_NUMBER = /(?:\d+\.?\d*|\.\d+)/y;
export function sumValue(text) {
const source = String(text ?? "");
if (source.length > 200) return null;
let at = 0;
const skip = () => { while (source[at] === " ") at += 1; };
const atom = () => {
skip();
const mark = source[at];
if (mark === "+" || mark === "-") {
at += 1;
const value = atom();
return value === null ? null : mark === "-" ? -value : value;
}
if (mark === "(") {
at += 1;
const value = sum();
skip();
if (value === null || source[at] !== ")") return null;
at += 1;
return value;
}
SUM_NUMBER.lastIndex = at;
const match = SUM_NUMBER.exec(source);
if (!match) return null;
at += match[0].length;
return Number(match[0]);
};
const product = () => {
let value = atom();
while (value !== null) {
skip();
const mark = source[at];
if (mark !== "*" && mark !== "/" && mark !== "%") break;
at += 1;
const next = atom();
if (next === null) return null;
value = mark === "*" ? value * next : mark === "/" ? value / next : value % next;
}
return value;
};
function sum() {
let value = product();
while (value !== null) {
skip();
const mark = source[at];
if (mark !== "+" && mark !== "-") break;
at += 1;
const next = product();
if (next === null) return null;
value = mark === "+" ? value + next : value - next;
}
return value;
}
const value = sum();
skip();
return value === null || at !== source.length || !Number.isFinite(value) ? null : value;
}
// Steps from a widget's options: the fine step is the widget's own
// increment; a 0..1 float moves by 0.05, a wide float by ten increments, a
// whole number by its increment (a wide pixel size by 8).
export function scrubSteps(options = {}, isFloat = true, pixels = false) {
const fine = Number(options.step2 ?? (options.step ? options.step / 10 : null) ?? (isFloat ? 0.01 : 1)) || (isFloat ? 0.01 : 1);
const range = Number(options.max ?? Infinity) - Number(options.min ?? -Infinity);
let step;
if (!isFloat) step = pixels && Number.isFinite(range) && range > 2048 ? 8 : Math.max(1, fine);
else if (Number.isFinite(range) && range <= 2) step = Math.max(fine, 0.05);
else step = fine * 10;
const decimals = isFloat ? Number(options.precision ?? Math.max(0, -Math.floor(Math.log10(fine)))) : 0;
return { step, fineStep: fine, decimals };
}
export function scrubbedValue(start, deltaX, fine, { step = 1, fineStep = null, ...range } = {}) {
if (Math.abs(deltaX) <= SCRUB_DEAD_ZONE) return quantize(start, range);
const finer = fineStep != null && fineStep < step;
const size = fine && finer ? fineStep : step;
const pixels = fine && !finer ? SCRUB_PIXELS_PER_STEP * SCRUB_SLOW_FACTOR : SCRUB_PIXELS_PER_STEP;
const steps = Math.round((deltaX - Math.sign(deltaX) * SCRUB_DEAD_ZONE) / pixels);
return quantize(start + steps * size, range);
}
function chevron(up) {
const points = up ? "1.5,4 4.5,1 7.5,4" : "1.5,1 4.5,4 7.5,1";
return `<svg width="9" height="5" viewBox="0 0 9 5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="${points}"/></svg>`;
}
// makeScrub({ value, min, max, step, fineStep, decimals, unit, unitWidth, title, onChange, onSettle })
// -> { root, get, set, setRange }. onChange fires on every committed change,
// onSettle once a gesture finishes (the undo point).
export function makeScrub(options = {}) {
const opts = { value: 0, min: -Infinity, max: Infinity, step: 1, fineStep: null, decimals: 2, unit: "", unitWidth: 0, title: "", ...options };
let current = quantize(opts.value, opts);
const format = (value) => Number(value).toFixed(Math.max(0, opts.decimals));
const stepped = (direction, fine) => current + direction * (fine ? (opts.fineStep ?? opts.step) : opts.step);
const box = document.createElement("div");
box.className = "fbui-scrub";
const input = document.createElement("input");
input.className = "fbui-scrub-input";
input.type = "text";
input.inputMode = "decimal";
input.readOnly = true;
input.value = format(current);
input.title = `${opts.title ? `${opts.title} ` : ""}Hold and drag right/up to raise, left/down to lower; click to type; Shift = fine.`;
const commit = (value) => {
const next = quantize(value, opts);
const changed = next !== current;
current = next;
input.value = format(current);
if (changed) opts.onChange?.(current);
};
const settle = () => opts.onSettle?.();
// Press and drag either way: right or up raises the value, left or down
// lowers it. The axis is the one the drag starts along.
let drag = null;
const travel = (event) => (drag.axis === "y" ? drag.y - event.clientY : event.clientX - drag.x);
input.addEventListener("pointerdown", (event) => {
if (event.button !== 0 || !input.readOnly) return;
drag = { x: event.clientX, y: event.clientY, start: current, scrubbed: false, fine: event.shiftKey, axis: "x" };
input.setPointerCapture(event.pointerId);
event.preventDefault();
});
input.addEventListener("pointermove", (event) => {
if (!drag) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
if (!drag.scrubbed && Math.max(Math.abs(dx), Math.abs(dy)) > SCRUB_DEAD_ZONE) {
drag.scrubbed = true;
drag.axis = Math.abs(dy) > Math.abs(dx) ? "y" : "x";
drag.fine = event.shiftKey;
}
if (!drag.scrubbed) return;
if (event.shiftKey !== drag.fine) {
// Pressing or releasing Shift carries on from here at the other speed.
const moved = travel(event);
const offset = Math.sign(moved || 1) * (SCRUB_DEAD_ZONE + 1);
drag.start = current;
if (drag.axis === "y") drag.y = event.clientY + offset;
else drag.x = event.clientX - offset;
drag.fine = event.shiftKey;
}
commit(scrubbedValue(drag.start, travel(event), event.shiftKey, opts));
});
const endDrag = (event) => {
if (!drag) return;
try { input.releasePointerCapture(event.pointerId); } catch { /* mouse fallback */ }
const scrubbed = drag.scrubbed;
drag = null;
if (scrubbed) {
settle();
return;
}
input.readOnly = false;
input.focus();
input.select();
// The canvas can grab focus during the click sequence; win that race once.
requestAnimationFrame(() => {
if (document.activeElement === input) return;
input.readOnly = false;
input.focus();
input.select();
});
};
input.addEventListener("pointerup", endDrag);
input.addEventListener("pointercancel", endDrag);
input.addEventListener("keydown", (event) => {
keepKeyInField(event);
if (event.key === "Enter") input.blur();
else if (event.key === "Escape") { input.value = format(current); input.blur(); }
else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault();
commit(stepped(event.key === "ArrowUp" ? 1 : -1, event.shiftKey));
input.select();
settle();
}
});
input.addEventListener("blur", () => {
if (!input.readOnly) {
const number = Number(input.value);
const typed = Number.isFinite(number) && input.value.trim() !== "" ? number : sumValue(input.value);
if (typed !== null) { commit(typed); settle(); }
input.readOnly = true;
}
input.value = format(current);
});
const steppers = document.createElement("div");
steppers.className = "fbui-scrub-step";
for (const direction of [1, -1]) {
const button = document.createElement("button");
button.type = "button";
button.tabIndex = -1;
button.innerHTML = chevron(direction > 0);
button.addEventListener("click", (event) => { commit(stepped(direction, event.shiftKey)); settle(); });
steppers.append(button);
}
box.append(input);
if (opts.unit || opts.unitWidth) {
// A fixed unit slot keeps every number in a column on one centre line.
const unit = document.createElement("span");
unit.className = "fbui-scrub-unit";
unit.textContent = opts.unit;
if (opts.unitWidth) unit.style.width = `${opts.unitWidth}px`;
else unit.style.padding = "0 3px 0 1px";
box.append(unit);
}
box.append(steppers);
return {
root: box,
get: () => current,
set: (value) => {
current = quantize(value, opts);
if (input.readOnly) input.value = format(current);
},
setRange: (range = {}) => {
for (const key of ["min", "max", "step", "fineStep", "decimals"]) if (range[key] !== undefined) opts[key] = range[key];
current = quantize(current, opts);
if (input.readOnly) input.value = format(current);
},
};
}
+199
View File
@@ -0,0 +1,199 @@
// FB UI kit: the shared look of FBnodes, Prompt Manager and H3RefModPicker.
// Every pack ships an identical copy of js/fbui/ (tools/sync_fbui.py), so each
// pack works alone and all of them look the same when installed together.
// Layout and controls adapted from ComfyUI-AusBoss (MIT, (c) 2026 ausboss).
//
// No imports: the node:test suites load this file without the ComfyUI app.
// Bump once per release that changes the CSS below (against the last pushed
// value, not per local edit). Two packs shipping the same version inject one
// stylesheet; different versions both inject and the later wins.
export const KIT_VERSION = 13;
export const T = Object.freeze({
brand: "#4299e1", // the one accent: picked segment, switch on, focus ring
onBrand: "#08182a", // text on a brand fill
brandSoft: "rgba(66,153,225,.16)",
brandSoftHover: "rgba(66,153,225,.28)",
brandInk: "#8cc4f2", // chip text on brandSoft
card: "#101317", // card ground
fill: "#2b3036", // every control: solid, no border
fillHover: "#363c43",
rule: "#2a2f35", // hairline after a section label
switchOff: "#5f666e", // the "off" half of a boolean pill when picked
ink: "#f5f7f9", // values
inkSoft: "#dfe3e7", // default card text
inkHover: "#ffffff",
label: "#b2b9c0", // row labels, unselected segments
faint: "#959ca4", // units, captions, placeholders
danger: "#e0605a",
dangerInk: "#ffd9d6",
dangerSoft: "#3a1c1b",
warn: "#e0a040",
warnInk: "#ffdca8",
warnSoft: "#3a2a10",
latent: "#c840c0", // a lossless .latent file beside a clip
overlay: "rgba(0,0,0,.72)", // modal backdrop
panel: "#171b20", // modal surface
shade: "rgba(8,10,12,.62)", // outside a crop
maskInk: "#ff3b3b", // painted mask, drawn at half strength
plate: "#1d232b", // media frame and footnote bar: neutral slate
plateEdge: "#323a45", // their 1px trim
});
export const FONT = `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`;
export const MONO = `ui-monospace,"Cascadia Mono",Menlo,Consolas,monospace`;
export const ROW_HEIGHT = 26;
// The footnote bar under a picture or video (card panel row height).
export const CAPTION_HEIGHT = 24;
export const ROW_GAP = 8;
export const SECTION_HEIGHT = 17;
export const GROUP_HEIGHT = 22;
export const CARD_PADDING = 10;
export const UNIT_SLOT_WIDTH = 22;
export const RADIUS_XS = 4;
export const RADIUS = 6;
export const RADIUS_CARD = 10;
// Modals stack above ComfyUI's own dialogs; menus above modals.
export const Z_MODAL = 10000;
export const Z_MENU = 10010;
const CHEVRON = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23b2b9c0' stroke-width='1.5'/%3E%3C/svg%3E")`;
export function kitCss() {
return `
.fbui-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 12px;overflow:hidden;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
.fbui-row{display:grid;grid-template-columns:minmax(52px,24%) 1fr;align-items:center;gap:10px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
.fbui-row.wide{grid-template-columns:1fr}
.fbui-card .hidden{display:none!important}
.fbui-row.linked{opacity:.5}
.fbui-row.linked .fbui-control{pointer-events:none}
.fbui-row.panel{display:block}
.fbui-row.panel.grow{flex:1 1 auto;height:auto}
.fbui-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
.fbui-label.has-info{display:flex;align-items:center;gap:4px}
.fbui-label.has-info>span{overflow:hidden;text-overflow:ellipsis}
.fbui-info{flex:none;display:inline-flex;color:${T.faint};cursor:pointer}
.fbui-info:hover,.fbui-info.on{color:${T.brandInk}}
.fbui-info svg{width:13px;height:13px}
.fbui-pop{position:fixed;z-index:${Z_MENU};max-width:460px;padding:14px 16px;border:1px solid ${T.plateEdge};border-radius:${RADIUS_CARD}px;background:${T.panel};box-shadow:0 10px 32px rgba(0,0,0,.6);color:${T.inkSoft};font:13px/1.55 ${FONT};user-select:text;cursor:auto;outline:none}
.fbui-pop>div+div{margin-top:6px}
.fbui-pop .pair{display:grid;grid-template-columns:minmax(150px,auto) 1fr;gap:14px;align-items:baseline}
.fbui-pop code{justify-self:start;padding:1px 6px;border-radius:4px;background:${T.card};color:${T.brandInk};font:600 13px ${MONO};cursor:copy}
.fbui-pop code:hover{background:${T.fill}}
.fbui-pop code.copied{background:${T.brand};color:${T.onBrand}}
.fbui-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
.fbui-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
.fbui-field.linked{opacity:.5;pointer-events:none}
.fbui-sep{flex:none;color:${T.faint};font-size:11px}
.fbui-section{height:${SECTION_HEIGHT}px;flex:none;display:flex;align-items:flex-end;gap:8px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
.fbui-section::after{content:"";flex:1;height:1px;margin-bottom:4px;background:${T.rule}}
.fbui-group{height:${GROUP_HEIGHT}px;flex:none;display:flex;align-items:center;gap:6px;padding:0 0 0 4px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;pointer-events:auto}
.fbui-group .toggle{flex:1;min-width:0;height:100%;display:flex;align-items:center;gap:6px;padding:0;border:none;border-radius:${RADIUS}px;background:transparent;color:inherit;font:inherit;letter-spacing:inherit;text-transform:inherit;cursor:pointer;text-align:left}
.fbui-group .toggle:hover{color:${T.inkHover}}
.fbui-group .glyph{display:inline-block;width:10px;transition:transform .12s}
.fbui-group.open .glyph{transform:rotate(90deg)}
.fbui-seg{display:grid;grid-auto-flow:column;grid-auto-columns:1fr;width:100%;height:${ROW_HEIGHT}px;padding:2px;box-sizing:border-box;border-radius:${RADIUS}px;background:${T.fill}}
.fbui-seg button{min-width:0;border:none;border-radius:${RADIUS_XS}px;padding:0 2px;background:transparent;color:${T.label};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fbui-seg button:hover{color:${T.inkHover}}
.fbui-seg button.on{background:${T.brand};color:${T.onBrand}}
.fbui-bool button.on:first-child{background:${T.switchOff};color:${T.ink}}
.fbui-select{width:100%;height:${ROW_HEIGHT}px;padding:0 24px 0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill} ${CHEVRON} no-repeat right 9px center;color:${T.ink};font:500 12px ${FONT};appearance:none;-webkit-appearance:none;cursor:pointer;overflow:hidden;text-overflow:ellipsis;min-width:0}
.fbui-select:hover{background-color:${T.fillHover}}
.fbui-select:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
.fbui-select option{background:${T.panel};color:${T.ink}}
.fbui-text{width:100%;height:${ROW_HEIGHT}px;padding:0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};color:${T.ink};font:12px ${FONT};min-width:0}
.fbui-text:focus{outline:none;border-color:${T.brand}}
textarea.fbui-text{background:${T.card};border-color:${T.plateEdge};font-size:13px;line-height:1.45}
.fbui-text.entry{flex:none;height:30px;background:${T.card};border-color:${T.plateEdge};font-size:13px}
.comfy-multiline-input.fbui-native-text,.lg-node-widgets textarea[data-fbui-text]{background:${T.card};border:1px solid ${T.plateEdge};color:${T.ink}}
.fbui-text::placeholder{color:${T.faint}}
.fbui-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;gap:5px;height:${ROW_HEIGHT}px;padding:0 10px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap;pointer-events:auto}
.fbui-btn:hover{background:${T.fillHover};color:${T.inkHover}}
.fbui-btn:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
.fbui-btn:disabled{opacity:.45;cursor:default}
.fbui-card [hidden],.fbui-overlay [hidden],.fbui-btn[hidden]{display:none!important}
.fbui-btn.grow{flex:1 1 0;min-width:0}
/* soft: the suite's blue action button; on: a tool that is enabled but not the one in use. Same look. */
.fbui-btn.on,.fbui-btn.soft{background:${T.brandSoft};color:${T.brandInk}}
.fbui-btn.soft:hover{background:${T.brandSoftHover};color:${T.ink}}
.fbui-btn.primary{background:${T.brand};color:${T.onBrand}}
.fbui-btn.primary:hover{filter:brightness(1.1)}
.fbui-btn.danger:hover{background:${T.dangerSoft};color:${T.dangerInk}}
.fbui-btn.small{height:20px;padding:0 7px;font-size:10px}
.fbui-btn.icon{width:${ROW_HEIGHT}px;padding:0}
.fbui-btn.icon.small{width:20px}
/* A slide handle sits in a field's icon column: its padding hangs outside so the icon lines up. */
.fbui-slide{flex:none;display:flex;align-items:center;align-self:stretch;margin:2px -4px;padding:0 4px;border-radius:${RADIUS}px;cursor:ew-resize;touch-action:none}
.fbui-slide svg{flex:none;color:${T.label}}
.fbui-slide:hover,.fbui-slide.on{background:${T.fill};color:${T.ink}}
.fbui-slide:hover svg,.fbui-slide.on svg{color:${T.brand}}
.fbui-rail{position:relative;height:24px;margin:0 7px;touch-action:none;cursor:pointer;user-select:none;pointer-events:auto}
.fbui-rail::before{content:"";position:absolute;left:0;right:0;top:10px;height:5px;border-radius:3px;background:${T.fill}}
.fbui-rail.disabled{opacity:.45;cursor:default}
.fbui-rail-fill{position:absolute;left:0;top:10px;height:5px;border-radius:3px;background:${T.brandSoftHover};pointer-events:none}
.fbui-rail-head{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background:${T.ink};box-shadow:0 0 0 1px rgba(0,0,0,.55);pointer-events:none}
.fbui-rail-head::before{content:"";position:absolute;top:-1px;left:50%;transform:translateX(-50%);border:5px solid transparent;border-top:6px solid ${T.ink};filter:drop-shadow(0 0 1px rgba(0,0,0,.7))}
.fbui-range-fill{position:absolute;top:10px;height:5px;background:${T.brand};opacity:.6;pointer-events:none}
.fbui-range-edge{position:absolute;top:4px;width:7px;height:17px;margin-left:-3.5px;border-radius:3px;background:${T.brand};box-shadow:0 0 0 1px rgba(0,0,0,.5);pointer-events:none}
.fbui-readout{flex:1 1 0;min-width:0;color:${T.faint};font:11px ${FONT};font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fbui-readout b{color:${T.ink};font-weight:600}
.fbui-tag{flex:none;color:${T.brand};font:650 10px ${FONT};letter-spacing:.08em;text-transform:uppercase;user-select:none}
.fbui-btn svg{flex:none}
.fbui-chip{height:20px;flex:none;display:inline-flex;align-items:center;padding:0 9px;border:none;border-radius:999px;background:${T.brandSoft};color:${T.brandInk};font:600 10px/1 ${FONT};letter-spacing:.02em;font-variant-numeric:tabular-nums;white-space:nowrap}
.fbui-chip.warn{background:${T.warnSoft};color:${T.warnInk}}
.fbui-chip.danger{background:${T.dangerSoft};color:${T.dangerInk}}
.fbui-scrub{display:flex;width:100%;height:${ROW_HEIGHT}px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};overflow:hidden;flex:1 1 0;min-width:0;color:${T.ink};font:500 12px ${FONT};font-variant-numeric:tabular-nums}
.fbui-scrub:focus-within{border-color:${T.brand}}
.fbui-scrub>.fbui-scrub-input{flex:1 1 auto;min-width:0;width:100%;height:100%;border:none;padding:0;margin:0;background:transparent;color:inherit;text-align:center;cursor:ew-resize;user-select:none;font:inherit;outline:none;border-radius:0}
.fbui-scrub>.fbui-scrub-input:focus{cursor:text;user-select:text}
.fbui-scrub>.fbui-scrub-unit{flex:none;align-self:center;color:${T.faint};font:600 10px ${FONT};letter-spacing:.04em;text-transform:uppercase;text-align:center;user-select:none;pointer-events:none}
.fbui-scrub>.fbui-scrub-step{flex:none;width:14px;display:flex;flex-direction:column;background:${T.fillHover}}
.fbui-scrub>.fbui-scrub-step>button{flex:1 1 0;min-height:0;border:none;background:transparent;color:${T.label};cursor:pointer;padding:0;margin:0;display:grid;place-items:center;border-radius:0}
.fbui-scrub>.fbui-scrub-step>button:hover{color:${T.brand};background:rgba(255,255,255,.05)}
.fbui-stage{position:relative;width:100%;height:100%;min-height:0;box-sizing:border-box;border:1px solid ${T.plateEdge};border-radius:${RADIUS_CARD}px;background:${T.plate};overflow:hidden;pointer-events:auto}
.fbui-stage>img,.fbui-stage>video,.fbui-stage>canvas.fbui-fit{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;display:block}
.fbui-stage-empty{position:absolute;inset:0;display:grid;place-items:center;padding:12px;color:${T.faint};font:11px ${FONT};text-align:center;pointer-events:none}
.fbui-stage-tools{position:absolute;top:6px;right:6px;display:flex;gap:4px;z-index:2}
.fbui-stage-tools .fbui-btn{height:20px;padding:0 7px;font-size:10px;letter-spacing:.04em;background:rgba(16,19,23,.82)}
.fbui-stage-tools .fbui-btn:hover{background:${T.fillHover}}
.fbui-stage-tools .fbui-btn.on{background:${T.brand};color:${T.onBrand}}
.fbui-caption{box-sizing:border-box;width:100%;height:${CAPTION_HEIGHT}px;display:flex;align-items:center;justify-content:center;gap:6px;padding:0 10px;border:1px solid ${T.plateEdge};border-radius:${RADIUS + 2}px;background:${T.plate};color:${T.label};font:600 11px ${FONT};font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:auto}
.fbui-overlay{position:fixed;inset:0;z-index:${Z_MODAL};display:flex;align-items:center;justify-content:center;background:${T.overlay};font:12px/1.4 ${FONT};color:${T.inkSoft}}
.fbui-modal{display:flex;flex-direction:column;max-width:92vw;max-height:90vh;min-width:320px;border-radius:${RADIUS_CARD}px;background:${T.panel};box-shadow:0 18px 60px rgba(0,0,0,.6);overflow:hidden}
.fbui-modal-head{flex:none;display:flex;align-items:center;gap:8px;padding:10px 12px;color:${T.ink};font:600 13px ${FONT}}
.fbui-modal-head .title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.fbui-modal-body{flex:1 1 auto;min-height:0;overflow:auto;padding:0 12px 12px}
.fbui-modal-foot{flex:none;display:flex;justify-content:flex-end;gap:6px;padding:10px 12px;background:${T.card}}
.fbui-viewer{position:fixed;inset:0;z-index:${Z_MODAL};background:rgba(5,6,8,.94);font:12px ${FONT};color:${T.inkSoft}}
.fbui-viewer .stage{position:absolute;inset:48px 64px 24px;display:flex;align-items:center;justify-content:center}
.fbui-viewer .stage img,.fbui-viewer .stage video{max-width:100%;max-height:100%;object-fit:contain;border-radius:${RADIUS}px;box-shadow:0 12px 48px rgba(0,0,0,.6);display:block}
.fbui-viewer .name{position:absolute;left:20px;top:14px;max-width:60vw;padding:4px 10px;border-radius:999px;background:${T.panel};color:${T.ink};font:600 12px ${FONT};white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fbui-viewer .where{position:absolute;left:50%;top:14px;transform:translateX(-50%);padding:4px 10px;border-radius:999px;background:${T.panel};color:${T.label};font:600 12px ${FONT};font-variant-numeric:tabular-nums}
.fbui-viewer .shut{position:absolute;right:16px;top:10px}
.fbui-viewer .nav{position:absolute;top:50%;transform:translateY(-50%);width:44px;height:44px;border-radius:50%;background:rgba(16,19,23,.8)}
.fbui-viewer .nav svg{width:20px;height:20px}
.fbui-viewer .nav.prev{left:12px}
.fbui-viewer .nav.next{right:12px}
.fbui-menu{position:fixed;z-index:${Z_MENU};min-width:160px;padding:4px;border-radius:${RADIUS}px;background:${T.panel};box-shadow:0 8px 28px rgba(0,0,0,.55);font:12px ${FONT};color:${T.inkSoft}}
.fbui-menu button{display:block;width:100%;padding:6px 10px;border:none;border-radius:${RADIUS_XS}px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
.fbui-menu button:hover{background:${T.fillHover};color:${T.inkHover}}
.fbui-menu button.danger:hover{background:${T.dangerSoft};color:${T.dangerInk}}
.fbui-menu .sep{height:1px;margin:4px 6px;background:${T.rule}}
`;
}
export function ensureKitCss() {
const id = `fbui-css-v${KIT_VERSION}`;
if (document.getElementById(id)) return;
const style = document.createElement("style");
style.id = id;
style.textContent = kitCss();
document.head.append(style);
}
+159
View File
@@ -0,0 +1,159 @@
// Show and hide stock widgets in place. A hidden widget stays in
// node.widgets, so widgets_values keeps its order and saved workflows load
// unchanged; only its rendering collapses.
//
// The classic canvas lays widgets out by computeSize / computeLayoutSize and
// paints them with draw, so those are zeroed. Nodes 2.0 filters its widget
// list on `widget.options.hidden`, so that flag is set too.
const STASH = Symbol.for("fbui.hiddenWidget");
const PAINT_KEYS = ["computeSize", "computeLayoutSize", "draw"];
export function hideWidget(widget) {
if (!widget) return false;
if (widget[STASH]) {
if (widget.options) widget.options.hidden = true;
return false;
}
let options = widget.options ?? {};
widget[STASH] = {
own: Object.fromEntries(PAINT_KEYS.map((key) => [key, Object.hasOwn(widget, key)])),
paint: Object.fromEntries(PAINT_KEYS.map((key) => [key, widget[key]])),
hidden: widget.hidden,
optionsHidden: options.hidden,
};
widget.hidden = true;
options.hidden = true;
// The frontend swaps a widget's options object after creation (a workflow
// restore does), which would drop the flag; keep re-applying it.
try {
Object.defineProperty(widget, "options", {
configurable: true,
enumerable: true,
get: () => options,
set: (next) => {
options = next ?? {};
options.hidden = true;
},
});
} catch {
widget.options = options;
}
widget.computeSize = () => [0, -4];
widget.computeLayoutSize = () => ({ minWidth: 0, minHeight: 0 });
widget.draw = () => {};
if (widget.element) widget.element.style.display = "none";
return true;
}
export function showWidget(widget) {
const stash = widget?.[STASH];
if (!stash) return false;
for (const key of PAINT_KEYS) {
if (stash.own[key]) widget[key] = stash.paint[key];
else delete widget[key];
}
widget.hidden = stash.hidden;
const options = widget.options;
delete widget.options;
widget.options = options;
if (stash.optionsHidden === undefined) delete options.hidden;
else options.hidden = stash.optionsHidden;
if (widget.element) widget.element.style.display = "";
widget[STASH] = undefined;
return true;
}
export function isWidgetHidden(widget) {
return Boolean(widget?.[STASH]);
}
// Mark inputs hidden in the node definition, before any widget exists. The
// frontend rebuilds widget options from this spec on restore and on the
// Nodes 2.0 mount, so a flag on the live widget alone is not enough.
export function hideInputsInDef(nodeData, names) {
for (const name of names) {
for (const group of ["required", "optional"]) {
const spec = nodeData?.input?.[group]?.[name];
if (!Array.isArray(spec)) continue;
spec[1] = { ...(spec[1] ?? {}), hidden: true };
}
}
}
export function findWidget(node, name) {
return node?.widgets?.find((widget) => widget.name === name) ?? null;
}
export function comboValues(widget) {
let values = widget?.options?.values;
if (typeof values === "function") values = values(widget);
return Array.isArray(values) ? values : [];
}
// Write a value the way LiteGraph's own widgets do: set it, run the widget's
// callback, then tell the node.
export function commitWidgetValue(node, widget, value) {
const previous = widget.value;
widget.value = value;
widget.callback?.(value, globalThis.app?.canvas, node);
node.onWidgetChanged?.(widget.name, value, previous, widget);
}
export function widgetSlot(node, name) {
return node?.inputs?.find((input) => input?.widget?.name === name) ?? null;
}
export function widgetLinked(node, name) {
const slot = widgetSlot(node, name);
return slot?.link !== null && slot?.link !== undefined;
}
// A widget's hover text: its own tooltip, else the node definition's.
export function widgetTooltip(node, name) {
const widget = findWidget(node, name);
const own = widget?.options?.tooltip ?? widget?.tooltip;
if (typeof own === "string" && own) return own;
const inputs = node?.constructor?.nodeData?.input;
const spec = inputs?.required?.[name] ?? inputs?.optional?.[name];
return typeof spec?.[1]?.tooltip === "string" ? spec[1].tooltip : "";
}
// For a node that draws its own preview: keep the frontend's run-output
// picture off it in both renderers. Nodes 2.0 reads hideOutputImages; the
// classic canvas draws node.imgs through a "$$canvas-image-preview" widget,
// and an animated (video) output through a "video-preview" DOM widget, which
// it adds without looking at hideOutputImages.
const CORE_PREVIEW = "$$canvas-image-preview";
const CORE_VIDEO_PREVIEW = "video-preview";
export function suppressCorePreview(node) {
node.hideOutputImages = true;
const index = node.widgets?.findIndex((widget) => widget.name === CORE_PREVIEW) ?? -1;
if (index >= 0) {
node.widgets[index].onRemove?.();
node.widgets.splice(index, 1);
}
if (Object.getOwnPropertyDescriptor(node, "imgs")?.get) return;
const addDom = node.addDOMWidget;
if (typeof addDom === "function") {
node.addDOMWidget = function (name, type, element, options) {
const widget = addDom.call(this, name, type, element, options);
if (name === CORE_VIDEO_PREVIEW) {
hideWidget(widget);
element.style.display = "none";
// Nothing plays or stays loaded behind the node's own player.
element.removeAttribute?.("src");
element.load?.();
}
return widget;
};
}
const add = node.addCustomWidget;
if (typeof add === "function") {
node.addCustomWidget = function (widget) {
if (widget?.name === CORE_PREVIEW) hideWidget(widget);
return add.call(this, widget);
};
}
Object.defineProperty(node, "imgs", { configurable: true, enumerable: true, get: () => undefined, set: () => {} });
}
+9
View File
@@ -0,0 +1,9 @@
// Shared look for Prompt Manager: node colours, the kit stylesheet, and graph
// zoom/drop over our panels. See docs/UI_RULES.md.
import { installAppearance } from "./fbui/appearance.js";
import { installPassthrough } from "./fbui/passthrough.js";
import { ensureKitCss } from "./fbui/theme.js";
installAppearance({ settingsPrefix: "PromptManager", category: "Prompt Manager" });
ensureKitCss();
installPassthrough();
+987 -683
View File
File diff suppressed because it is too large Load Diff
-316
View File
@@ -1,316 +0,0 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
/**
* Latent Preview Extension for Prompt Manager
* Provides animated previews during video model sampling.
* Compatible with VideoHelperSuite - will defer to VHS if installed.
*/
// Track nodes that have latent preview widgets
let latentPreviewNodes = new Set();
// Store preview images per node
let previewImagesDict = {};
// Animation intervals for each node
let animateIntervals = {};
// Text decoder for binary messages
const textDecoder = new TextDecoder();
/**
* Get a node by ID, handling subgraphs
*/
function getNodeById(id) {
// Try main graph first
let node = app.graph.getNodeById(id);
if (node) return node;
// Try subgraphs if available
if (app.graph.subgraphs) {
for (const subgraph of app.graph.subgraphs.values()) {
node = subgraph.getNodeById(id);
if (node) return node;
}
}
return null;
}
/**
* Fit the node height to accommodate the preview widget
*/
function fitHeight(node) {
node.setSize([node.size[0], node.computeSize()[1]]);
node.graph?.setDirtyCanvas(true, true);
}
/**
* Allow drag from the preview widget
*/
function allowDragFromWidget(widget) {
widget.element.addEventListener('pointerdown', (e) => {
if (e.button === 0) {
// Prevent default to allow canvas interaction
e.stopPropagation();
}
});
}
/**
* Get or create the canvas context for latent preview
*/
function getLatentPreviewCtx(id, width, height) {
const node = getNodeById(id);
if (!node) {
return undefined;
}
let previewWidget = node.widgets?.find((w) => w.name === "pmlatentpreview");
if (!previewWidget) {
// Check for and remove any native preview
const nativePreview = node.widgets?.findIndex((w) => w.name === '$$canvas-image-preview');
if (nativePreview >= 0) {
node.imgs = [];
node.widgets.splice(nativePreview, 1);
}
// Create canvas element
const canvasEl = document.createElement("canvas");
canvasEl.style.width = "100%";
previewWidget = node.addDOMWidget("pmlatentpreview", "pmcanvas", canvasEl, {
serialize: false,
hideOnZoom: false,
});
previewWidget.serialize = false;
allowDragFromWidget(previewWidget);
// Forward mouse events to canvas for interaction
const forwardEvent = (eventName, handler) => {
canvasEl.addEventListener(eventName, (e) => {
e.preventDefault();
return handler(e);
}, true);
};
forwardEvent('contextmenu', (e) => app.canvas._mousedown_callback(e));
forwardEvent('pointerdown', (e) => app.canvas._mousedown_callback(e));
forwardEvent('mousewheel', (e) => app.canvas._mousewheel_callback(e));
forwardEvent('pointermove', (e) => app.canvas._mousemove_callback(e));
forwardEvent('pointerup', (e) => app.canvas._mouseup_callback(e));
previewWidget.computeSize = function(width) {
if (this.aspectRatio) {
let height = (node.size[0] - 20) / this.aspectRatio + 10;
if (!(height > 0)) {
height = 0;
}
this.computedHeight = height + 10;
return [width, height];
}
return [width, -4]; // No loaded src, widget should not display
};
}
const canvasEl = previewWidget.element;
if (!previewWidget.ctx || canvasEl.width !== width || canvasEl.height !== height) {
previewWidget.aspectRatio = width / height;
canvasEl.width = width;
canvasEl.height = height;
fitHeight(node);
}
return canvasEl.getContext("2d");
}
/**
* Begin animated latent preview for a node
*/
function beginLatentPreview(id, previewImages, rate) {
latentPreviewNodes.add(id);
if (animateIntervals[id]) {
clearInterval(animateIntervals[id]);
}
let displayIndex = 0;
const node = getNodeById(id);
// Initialize progress to avoid race condition
if (node) {
node.progress = 0;
}
animateIntervals[id] = setInterval(() => {
const currentNode = getNodeById(id);
if (!currentNode?.progress && currentNode?.progress !== 0) {
clearInterval(animateIntervals[id]);
delete animateIntervals[id];
return;
}
// Check if we're still on the right graph
if (app.canvas.graph.rootGraph !== currentNode.graph?.rootGraph) {
clearInterval(animateIntervals[id]);
delete animateIntervals[id];
return;
}
if (!previewImages[displayIndex]) {
return;
}
const ctx = getLatentPreviewCtx(
id,
previewImages[displayIndex].width,
previewImages[displayIndex].height
);
ctx?.drawImage?.(previewImages[displayIndex], 0, 0);
displayIndex = (displayIndex + 1) % previewImages.length;
}, 1000 / rate);
}
/**
* Check if VideoHelperSuite is providing latent preview
*/
function isVHSLatentPreviewActive() {
// Check if VHS extension is registered and has latent preview enabled
const vhsExtension = app.extensions.find(ext => ext.name === "VideoHelperSuite.Core");
if (vhsExtension) {
try {
const vhsSetting = app.ui.settings.getSettingValue("VHS.LatentPreview");
return vhsSetting === true;
} catch (e) {
// Setting doesn't exist or error
}
}
return false;
}
app.registerExtension({
name: "PromptManager.LatentPreview",
settings: [
{
id: "PromptManager.LatentPreview",
category: ["Prompt Manager", "5. Video Sampling", "1. Animated Latent Preview"],
name: "Display animated previews when sampling",
tooltip: "Enable animated preview during video model sampling (KSampler). Will be disabled if VideoHelperSuite provides this feature.",
type: "boolean",
defaultValue: false,
onChange(value) {
if (!value) {
// Remove any preview widgets when disabled
for (const id of latentPreviewNodes) {
const node = app.graph?.getNodeById(id);
const widgetIndex = node?.widgets?.findIndex((w) => w.name === 'pmlatentpreview');
if (widgetIndex >= 0) {
const widget = node.widgets.splice(widgetIndex, 1)[0];
widget.onRemove?.();
}
}
latentPreviewNodes = new Set();
}
},
},
{
id: "PromptManager.LatentPreviewRate",
category: ["Prompt Manager", "5. Video Sampling", "2. Playback Rate Override"],
name: "Playback rate override",
tooltip: "Force a specific frame rate for latent preview playback. Set to 0 for auto-detect based on video model. This is the preview FPS, not the output video FPS.",
type: "number",
attrs: {
min: 0,
step: 1,
max: 60,
},
defaultValue: 0,
},
],
async setup() {
// Hook into graphToPrompt to pass our settings to the backend
const originalGraphToPrompt = app.graphToPrompt;
app.graphToPrompt = async function() {
const res = await originalGraphToPrompt.apply(this, arguments);
// Check if VHS is handling latent preview
const vhsActive = isVHSLatentPreviewActive();
if (!vhsActive) {
// Add our settings to the workflow extra data
res.workflow.extra['PM_latentpreview'] = app.ui.settings.getSettingValue("PromptManager.LatentPreview");
res.workflow.extra['PM_latentpreviewrate'] = app.ui.settings.getSettingValue("PromptManager.LatentPreviewRate");
}
return res;
};
console.log("[PromptManager] Latent preview extension loaded");
},
async init() {
// Clear preview nodes on execution complete
api.addEventListener('executing', ({ detail }) => {
if (detail === null) {
// Execution complete - clean up progress indicators
for (const id of latentPreviewNodes) {
const node = getNodeById(id);
if (node) {
delete node.progress;
}
}
}
});
// Listen for latent preview initialization from backend
api.addEventListener('PM_latentpreview', ({ detail }) => {
if (detail.id == null) {
return;
}
// Skip if VHS is active
if (isVHSLatentPreviewActive()) {
return;
}
const previewImages = previewImagesDict[detail.id] = [];
previewImages.length = detail.length;
// Handle node ID parts (for subgraphs)
const idParts = detail.id.split(':');
for (let i = 1; i <= idParts.length; i++) {
const id = idParts.slice(0, i).join(':');
beginLatentPreview(id, previewImages, detail.rate);
}
});
// Listen for binary preview images
api.addEventListener('b_preview', async (e) => {
// Only handle if we have active animations and VHS isn't handling it
if (Object.keys(animateIntervals).length === 0 || isVHSLatentPreviewActive()) {
return;
}
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
const dv = new DataView(await e.detail.slice(0, 24).arrayBuffer());
const index = dv.getUint32(4);
const idlen = dv.getUint8(8);
const id = textDecoder.decode(dv.buffer.slice(9, 9 + idlen));
// Only process if this is our preview (PM_ prefix in the workflow extra)
if (previewImagesDict[id]) {
previewImagesDict[id][index] = await window.createImageBitmap(e.detail.slice(24));
}
return false;
}, true);
},
});
+950
View File
@@ -0,0 +1,950 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { PM_UI_PALETTE } from "./ui_palette.js";
const NODE_CLASS = "MultiLoraStackerLM";
const LM_PROVIDER_CLASS = "Lora Stacker (LoraManager)";
const STYLE_ID = "pm-multi-lm-style";
const MIN_NODE_WIDTH = 320;
const MIN_NODE_HEIGHT = 320;
const DEFAULT_NODE_WIDTH = 600;
const DEFAULT_NODE_HEIGHT = 430;
const MIN_STACK_COUNT = 1;
const MAX_STACK_COUNT = 4;
const DEFAULT_STACK_COUNT = 2;
// Height constants mirroring LM's loras_widget_utils.js
const LM_LORA_ENTRY_H = 40;
const LM_HEADER_H = 32;
const LM_CONTAINER_PAD = 12;
const LM_EMPTY_H = 100;
const FAST_PREVIEW_DELAY_MS = 20;
// Per-column chrome: title(22) + search textarea(50) + col padding(16)
const COL_CHROME_H = 88;
let loraCodeListenerAttached = false;
let promptSerializationPatched = false;
const SLOT_DEFS = [
{ key: "model_a", label: "Model A", short: "A", state: "loras_state_a" },
{ key: "model_b", label: "Model B", short: "B", state: "loras_state_b" },
{ key: "model_c", label: "Model C", short: "C", state: "loras_state_c" },
{ key: "model_d", label: "Model D", short: "D", state: "loras_state_d" },
];
let lmBridgePromise = null;
// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------
function ensureStyles() {
if (document.getElementById(STYLE_ID)) return;
const p = PM_UI_PALETTE || {};
const panel = p.panel || "hsl(216 11% 15%)";
const panelBorder = p.panelBorder || "hsl(216 20% 65% / 0.24)";
const inputBg = p.inputBg || "hsl(220 15% 10%)";
const inputBorder = p.inputBorder || "hsl(218 10% 41%)";
const textHeading = p.textHeading || "hsl(220 13% 85%)";
const textPrimary = p.textPrimary || "hsl(0 0% 87%)";
const textHint = p.textHint || "hsl(216 15% 65%)";
const cardBg = p.cardBg || "hsl(219 16% 18%)";
const accentBorder = "rgba(255,255,255,0.98)";
const accentSoft = "rgba(255,255,255,0.42)";
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = `
.pm-multi-lm-root {
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 6px 6px 6px 6px;
overflow: visible;
display: flex;
flex-direction: column;
position: relative;
}
.pm-multi-lm-root,
.pm-multi-lm-root * {
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-root::-webkit-scrollbar,
.pm-multi-lm-root *::-webkit-scrollbar {
width: 0;
height: 0;
display: none;
}
.pm-multi-lm-grid {
display: grid;
grid-template-columns: repeat(2, minmax(200px, 1fr));
gap: 8px;
flex: 1;
min-height: 0;
align-items: stretch;
margin-top: -16px;
}
.pm-multi-lm-topbar {
display: inline-flex;
align-items: center;
justify-content: flex-start;
position: absolute;
left: 8px;
top: -48px;
z-index: 2;
margin-top: 0;
margin-bottom: 0;
flex-shrink: 0;
}
.pm-multi-lm-stack-control {
display: inline-flex;
align-items: center;
gap: 8px;
border: 1px solid ${panelBorder};
border-radius: 8px;
background: ${panel};
padding: 5px 8px;
}
.pm-multi-lm-stack-label {
font-size: 14px;
font-weight: 700;
letter-spacing: 0.02em;
color: ${textHeading};
user-select: none;
}
.pm-multi-lm-stepper {
display: inline-flex;
align-items: center;
gap: 4px;
}
.pm-multi-lm-step-btn {
width: 24px;
height: 24px;
border: 1px solid ${inputBorder};
border-radius: 5px;
background: ${inputBg};
color: ${textPrimary};
font-size: 14px;
line-height: 1;
padding: 0;
cursor: pointer;
}
.pm-multi-lm-step-btn:hover {
border-color: ${textHeading};
}
.pm-multi-lm-step-btn:disabled {
opacity: 0.45;
cursor: default;
}
.pm-multi-lm-step-value {
min-width: 16px;
text-align: center;
font-size: 14px;
font-weight: 700;
line-height: 1.1;
color: hsl(0 0% 100%);
font-variant-numeric: tabular-nums;
user-select: none;
}
.pm-multi-lm-col {
border: 1px solid ${panelBorder};
border-radius: 8px;
background: ${panel};
padding: 8px;
min-width: 0;
display: flex;
flex-direction: column;
flex-shrink: 0;
min-height: 0;
height: 100%;
}
.pm-multi-lm-col.active-slot {
border-color: ${accentBorder};
box-shadow: inset 0 0 0 1px ${accentSoft};
}
.pm-multi-lm-col.active-slot .pm-multi-lm-title {
color: ${accentBorder};
}
.pm-multi-lm-title {
font-weight: 700;
font-size: 14px;
letter-spacing: 0.02em;
color: ${textHeading};
margin-bottom: 6px;
flex-shrink: 0;
}
.pm-multi-lm-search {
width: 100%;
min-height: 38px;
resize: vertical;
box-sizing: border-box;
border: 1px solid ${inputBorder};
border-radius: 6px;
padding: 6px 8px;
background: ${inputBg};
color: ${textPrimary};
margin-bottom: 6px;
font-size: 14px;
flex-shrink: 0;
}
.pm-multi-lm-search::placeholder {
color: ${textHint};
}
.pm-multi-lm-list-host {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-list-host .lm-loras-container {
height: 100%;
max-height: none;
background: ${cardBg};
scrollbar-width: none;
-ms-overflow-style: none;
}
.pm-multi-lm-list-host::-webkit-scrollbar,
.pm-multi-lm-list-host .lm-loras-container::-webkit-scrollbar {
width: 0;
height: 0;
display: none;
}
`;
document.head.appendChild(style);
}
// ---------------------------------------------------------------------------
// LM bridge loader
// ---------------------------------------------------------------------------
async function loadLmBridge() {
if (lmBridgePromise) return lmBridgePromise;
lmBridgePromise = Promise.all([
import("/extensions/ComfyUI-Lora-Manager/autocomplete.js"),
import("/extensions/ComfyUI-Lora-Manager/loras_widget.js"),
import("/extensions/ComfyUI-Lora-Manager/utils.js"),
import("/extensions/ComfyUI-Lora-Manager/lora_syntax_utils.js"),
import("/extensions/ComfyUI-Lora-Manager/preview_tooltip.js"),
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod, previewTooltipMod]) => ({
AutoComplete: autocompleteMod.AutoComplete,
addLorasWidget: lorasWidgetMod.addLorasWidget,
mergeLoras: utilsMod.mergeLoras,
applyLoraValuesToText: syntaxMod.applyLoraValuesToText,
PreviewTooltip: previewTooltipMod.PreviewTooltip,
})).catch((err) => {
console.warn("[PromptManager] Failed to load Lora-Manager bridge modules", err);
lmBridgePromise = null;
return null;
});
return lmBridgePromise;
}
// ---------------------------------------------------------------------------
// Widget helpers
// ---------------------------------------------------------------------------
function getWidgetByName(node, name) {
if (!node || !Array.isArray(node.widgets)) return null;
return node.widgets.find((w) => w && w.name === name) ?? null;
}
function ensureStateWidget(node, name) {
let widget = getWidgetByName(node, name);
if (widget) return widget;
if (!node || typeof node.addWidget !== "function") return null;
return node.addWidget("text", name, "[]", null, { multiline: true });
}
function hideWidget(widget) {
if (!widget || widget.__pm_hidden) return;
widget.__pm_hidden = true;
// Keep original widget type (STRING) so graphToPrompt includes state values.
widget.hidden = true;
widget.computeSize = () => [0, -4];
widget.draw = function () {};
if (widget.element) widget.element.style.display = "none";
}
function hideStateWidgets(node) {
if (!node || !Array.isArray(node.widgets)) return;
for (const widget of node.widgets) {
if (!widget || widget.name === "multi_lora_ui") continue;
hideWidget(widget);
}
}
function parseLorasState(value) {
if (Array.isArray(value)) return value;
if (value && typeof value === "object" && Array.isArray(value.__value__)) {
return value.__value__;
}
if (value && typeof value === "object" && typeof value.__value__ === "string") {
try {
const parsed = JSON.parse(value.__value__);
return Array.isArray(parsed) ? parsed : [];
} catch (_e) {
return [];
}
}
if (typeof value !== "string") return [];
const raw = value.trim();
if (!raw || raw === "[]") return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (_e) {
return [];
}
}
function writeLorasState(widget, listValue) {
if (!widget) return;
widget.value = JSON.stringify(Array.isArray(listValue) ? listValue : []);
}
function getSlotByKey(node, slotKey) {
if (!node || !Array.isArray(node.__pmMultiLmSlots)) return null;
return node.__pmMultiLmSlots.find((s) => s && s.key === slotKey) ?? null;
}
function clampStackCount(value) {
const n = Number(value);
if (!Number.isFinite(n)) return DEFAULT_STACK_COUNT;
return Math.max(MIN_STACK_COUNT, Math.min(MAX_STACK_COUNT, Math.round(n)));
}
function getStackCount(node) {
const raw = node?.properties?.pmLoraStackCount;
return clampStackCount(raw ?? DEFAULT_STACK_COUNT);
}
function getVisibleSlotKeys(node) {
const count = getStackCount(node);
return SLOT_DEFS.slice(0, count).map((s) => s.key);
}
function syncStackCountWidget(node, count) {
const widget = getWidgetByName(node, "stack_count");
if (widget) widget.value = count;
}
function ensureActiveSlotVisible(node) {
if (!node || !node.properties) return;
const visible = getVisibleSlotKeys(node);
if (visible.length === 0) return;
if (!visible.includes(node.properties.pmActiveSlot)) {
node.properties.pmActiveSlot = visible[0];
}
}
function updateStackControlUi(node) {
const refs = node?.__pmStackControl;
if (!refs) return;
const count = getStackCount(node);
refs.value.textContent = String(count);
refs.dec.disabled = count <= MIN_STACK_COUNT;
refs.inc.disabled = count >= MAX_STACK_COUNT;
}
function applyVisibleStackCount(node) {
const slots = node?.__pmMultiLmSlots;
const grid = node?.__pmMultiLmGrid;
if (!Array.isArray(slots) || !grid) return;
const visible = new Set(getVisibleSlotKeys(node));
const visibleCount = visible.size || DEFAULT_STACK_COUNT;
grid.style.gridTemplateColumns = `repeat(${visibleCount}, minmax(200px, 1fr))`;
for (const slot of slots) {
if (!slot?.col) continue;
slot.col.style.display = visible.has(slot.key) ? "flex" : "none";
}
}
function setStackCount(node, value) {
if (!node) return;
if (!node.properties) node.properties = {};
node.properties.pmLoraStackCount = clampStackCount(value);
ensureActiveSlotVisible(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
syncStackCountWidget(node, node.properties.pmLoraStackCount);
updateActiveColumnHighlight(node);
notifyHeightChange(node);
applyNodeSizeConstraints(node, false, true);
}
// ---------------------------------------------------------------------------
// Apply incoming lora code to a slot
// ---------------------------------------------------------------------------
function applyIncomingLoraCode(node, slotKey, code, mode) {
if (!node || typeof code !== "string") return;
const slot = getSlotByKey(node, slotKey);
if (!slot || !slot.searchInput) return;
const current = String(slot.searchInput.value || "");
slot.searchInput.value = (mode === "replace" || !current) ? code : `${current}\n${code}`;
slot.searchInput.dispatchEvent(new Event("input", { bubbles: true }));
}
// ---------------------------------------------------------------------------
// lora_code_update listener (attached once, synchronously)
// ---------------------------------------------------------------------------
function attachLoraCodeListener() {
if (loraCodeListenerAttached) return;
loraCodeListenerAttached = true;
api.addEventListener("lora_code_update", (event) => {
const detail = event?.detail;
if (!detail) return;
const nodeId = Number(detail.id);
if (!Number.isFinite(nodeId) || nodeId < 0) return;
const loraCode = typeof detail.lora_code === "string" ? detail.lora_code : "";
const mode = typeof detail.mode === "string" ? detail.mode : "append";
// Find our node by integer ID
const nodes = app.graph?._nodes;
if (!Array.isArray(nodes)) return;
const targetNode = nodes.find((n) => Number(n.id) === nodeId && n.type === NODE_CLASS);
if (!targetNode) return;
// Route to the currently-selected active slot
const activeSlot = targetNode.properties?.pmActiveSlot ?? "model_a";
applyIncomingLoraCode(targetNode, activeSlot, loraCode, mode);
});
}
// ---------------------------------------------------------------------------
// Prompt serialization shim:
// Keep LM comfyClass for manager integration, but serialize this node as its
// real backend class so ComfyUI validates against MultiLoraStackerLM inputs.
// ---------------------------------------------------------------------------
function attachPromptSerializationShim() {
if (promptSerializationPatched) return;
if (!app || typeof app.graphToPrompt !== "function") return;
promptSerializationPatched = true;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function (...args) {
const swapped = [];
const nodes = app.graph?._nodes;
if (Array.isArray(nodes)) {
for (const node of nodes) {
if (!node || node.type !== NODE_CLASS) continue;
if (node.comfyClass !== LM_PROVIDER_CLASS) continue;
swapped.push(node);
node.comfyClass = NODE_CLASS;
}
}
try {
return await originalGraphToPrompt(...args);
} finally {
for (const node of swapped) {
node.comfyClass = LM_PROVIDER_CLASS;
}
}
};
}
// ---------------------------------------------------------------------------
// Active-slot selection (click a section to target LM sends)
// ---------------------------------------------------------------------------
function setActiveSlot(node, slotKey) {
if (!node) return;
if (!node.properties) node.properties = {};
node.properties.pmActiveSlot = slotKey;
updateActiveColumnHighlight(node);
}
function updateActiveColumnHighlight(node) {
if (!Array.isArray(node.__pmMultiLmSlots)) return;
ensureActiveSlotVisible(node);
const activeSlot = node.properties?.pmActiveSlot ?? "model_a";
const visible = new Set(getVisibleSlotKeys(node));
for (const slot of node.__pmMultiLmSlots) {
if (slot?.col) {
const isActive = slot.key === activeSlot && visible.has(slot.key);
slot.col.classList.toggle("active-slot", isActive);
}
}
}
// ---------------------------------------------------------------------------
// Embedded loras widget via fakeNode pattern
// ---------------------------------------------------------------------------
function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange) {
const host = document.createElement("div");
host.className = "pm-multi-lm-list-host";
const fakeNode = {
addDOMWidget(name, type, container, options) {
return {
name,
type,
callback: null,
element: container,
get value() {
return typeof options?.getValue === "function" ? options.getValue() : [];
},
set value(v) {
if (typeof options?.setValue === "function") options.setValue(v);
},
};
},
setDirtyCanvas(fg, bg) { node?.setDirtyCanvas?.(fg, bg); },
};
const out = lm.addLorasWidget(fakeNode, widgetName, {}, onChange);
if (out?.widget?.element) host.appendChild(out.widget.element);
if (out?.widget && Array.isArray(initialValue) && initialValue.length > 0) {
out.widget.value = initialValue;
}
const fastPreviewCleanup = attachFastPreviewHandlers(host, lm);
return { host, widget: out?.widget ?? null, fastPreviewCleanup };
}
function attachFastPreviewHandlers(host, lm) {
if (!host || typeof lm?.PreviewTooltip !== "function") {
return () => {};
}
const tooltip = new lm.PreviewTooltip({ modelType: "loras" });
const processed = new WeakSet();
const bindNameEl = (nameEl) => {
if (!nameEl || processed.has(nameEl)) return;
processed.add(nameEl);
// Replace LM's delayed listeners on this element with a faster local one.
const replacement = nameEl.cloneNode(true);
const triggerEl = nameEl.closest(".lm-lora-entry") || nameEl.parentElement || replacement;
let previewTimer = null;
const clearPreviewTimer = () => {
if (previewTimer) {
clearTimeout(previewTimer);
previewTimer = null;
}
};
triggerEl.addEventListener("mouseenter", () => {
clearPreviewTimer();
previewTimer = setTimeout(async () => {
previewTimer = null;
const name = String(replacement.textContent || "").trim();
if (!name) return;
const rect = triggerEl.getBoundingClientRect();
try {
await tooltip.show(name, rect.right, rect.top);
} catch (_e) {
}
}, FAST_PREVIEW_DELAY_MS);
});
triggerEl.addEventListener("mouseleave", () => {
clearPreviewTimer();
tooltip.hide();
});
nameEl.replaceWith(replacement);
processed.add(replacement);
};
const bindAll = () => {
const nameEls = host.querySelectorAll(".lm-lora-name");
for (const nameEl of nameEls) bindNameEl(nameEl);
};
bindAll();
const observer = new MutationObserver(() => {
bindAll();
});
observer.observe(host, { childList: true, subtree: true });
return () => {
observer.disconnect();
tooltip.hide();
tooltip.cleanup();
};
}
// ---------------------------------------------------------------------------
// Height management — mirrors LM's updateWidgetHeight approach:
// set CSS vars on the root element so ComfyUI's layout system resizes the node,
// never calling node.setSize() (which would prevent user resize).
// ---------------------------------------------------------------------------
function computeContentHeight(node) {
let maxListH = LM_EMPTY_H;
const visible = new Set(getVisibleSlotKeys(node));
if (Array.isArray(node.__pmMultiLmSlots)) {
for (const slot of node.__pmMultiLmSlots) {
if (!visible.has(slot.key)) continue;
const count = Array.isArray(slot.lorasWidget?.value) ? slot.lorasWidget.value.length : 0;
const h = count === 0
? LM_EMPTY_H
: LM_CONTAINER_PAD + LM_HEADER_H + Math.min(count, 12) * LM_LORA_ENTRY_H;
if (h > maxListH) maxListH = h;
}
}
return COL_CHROME_H + maxListH + 56;
}
function notifyHeightChange(node) {
const root = node?.__pmMultiLmRoot;
if (!root) return;
const h = computeContentHeight(node);
root.style.setProperty('--comfy-widget-min-height', `${h}px`);
root.style.setProperty('--comfy-widget-height', `${h}px`);
applyNodeSizeConstraints(node);
setTimeout(() => { node?.setDirtyCanvas?.(true, true); }, 10);
}
function applyNodeSizeConstraints(node, useDefaultSize = false, forceWidth = false) {
if (!node || node.__pmApplyingSizeConstraint) return;
const currentW = Number(node?.size?.[0]) || 0;
const currentH = Number(node?.size?.[1]) || 0;
const minW = MIN_NODE_WIDTH * getStackCount(node);
const targetW = forceWidth
? minW
: (useDefaultSize
? Math.max(DEFAULT_NODE_WIDTH, minW, currentW)
: Math.max(minW, currentW));
const targetH = useDefaultSize
? Math.max(DEFAULT_NODE_HEIGHT, MIN_NODE_HEIGHT, currentH)
: Math.max(MIN_NODE_HEIGHT, currentH);
if (targetW === currentW && targetH === currentH) return;
node.__pmApplyingSizeConstraint = true;
try {
node.setSize([targetW, targetH]);
} finally {
node.__pmApplyingSizeConstraint = false;
}
}
// ---------------------------------------------------------------------------
// Per-slot column builder
// ---------------------------------------------------------------------------
function buildSlotColumn(node, lm, slotDef) {
const stateWidget = ensureStateWidget(node, slotDef.state);
hideWidget(stateWidget);
const col = document.createElement("div");
col.className = "pm-multi-lm-col";
col.title = `Click to make ${slotDef.label} the LoRA Manager target`;
col.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
const title = document.createElement("div");
title.className = "pm-multi-lm-title";
title.textContent = slotDef.label;
const searchInput = document.createElement("textarea");
searchInput.className = "pm-multi-lm-search";
searchInput.placeholder = "Search LoRAs to add\u2026";
searchInput.rows = 1;
searchInput.addEventListener("focus", () => setActiveSlot(node, slotDef.key));
// Attach LM autocomplete to the search textarea
new lm.AutoComplete(searchInput, "loras", { showPreview: false });
const initialState = parseLorasState(stateWidget?.value ?? "[]");
let isSyncing = false;
const embedded = createEmbeddedLorasWidget(
node, lm, `${slotDef.key}_loras`, initialState,
(value) => {
if (isSyncing) return;
isSyncing = true;
try {
const safe = Array.isArray(value) ? value : [];
writeLorasState(stateWidget, safe);
const nextText = lm.applyLoraValuesToText(searchInput.value || "", safe);
if (searchInput.value !== nextText) searchInput.value = nextText;
} finally {
isSyncing = false;
notifyHeightChange(node);
}
},
);
// When user types or autocomplete fires, merge into the loras list
searchInput.addEventListener("input", () => {
if (isSyncing) return;
isSyncing = true;
try {
const existing = Array.isArray(embedded.widget?.value) ? embedded.widget.value : [];
const merged = lm.mergeLoras(searchInput.value || "", existing);
if (embedded.widget) embedded.widget.value = merged;
writeLorasState(stateWidget, merged);
} finally {
isSyncing = false;
notifyHeightChange(node);
}
});
col.appendChild(title);
col.appendChild(searchInput);
col.appendChild(embedded.host);
embedded.host.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
return {
key: slotDef.key,
stateWidget,
searchInput,
lorasWidget: embedded.widget,
fastPreviewCleanup: embedded.fastPreviewCleanup,
col,
};
}
// ---------------------------------------------------------------------------
// Restore widget state from persisted JSON
// ---------------------------------------------------------------------------
function refreshFromStoredValues(node) {
if (!node?.__pmMultiLmSlots || !node.__pmMultiLmBridge) return;
for (const slot of node.__pmMultiLmSlots) {
const state = parseLorasState(slot.stateWidget?.value ?? "[]");
// Restore from persisted JSON directly. Do NOT call mergeLoras here:
// mergeLoras requires syntax in text input, and would drop entries
// during tab-switch/workflow-load when textarea is initially empty.
if (slot.lorasWidget) slot.lorasWidget.value = state;
writeLorasState(slot.stateWidget, state);
// Keep syntax textarea consistent with restored list.
const nextText = node.__pmMultiLmBridge.applyLoraValuesToText(slot.searchInput.value || "", state);
if (slot.searchInput.value !== nextText) slot.searchInput.value = nextText;
}
notifyHeightChange(node);
}
// ---------------------------------------------------------------------------
// Main async UI setup
// ---------------------------------------------------------------------------
async function setupNodeUi(node) {
if (!node || node.__pmMultiLmReady) return;
ensureStyles();
const lm = await loadLmBridge();
if (!lm || node.__pmMultiLmReady) return;
hideStateWidgets(node);
const root = document.createElement("div");
root.className = "pm-multi-lm-root";
// Top-left custom stack count control (1..4)
const topbar = document.createElement("div");
topbar.className = "pm-multi-lm-topbar";
const stackControl = document.createElement("div");
stackControl.className = "pm-multi-lm-stack-control";
const stackLabel = document.createElement("div");
stackLabel.className = "pm-multi-lm-stack-label";
stackLabel.textContent = "Lora Stack";
const stepper = document.createElement("div");
stepper.className = "pm-multi-lm-stepper";
const decBtn = document.createElement("button");
decBtn.className = "pm-multi-lm-step-btn";
decBtn.type = "button";
decBtn.textContent = "<";
const valueEl = document.createElement("div");
valueEl.className = "pm-multi-lm-step-value";
valueEl.textContent = String(getStackCount(node));
const incBtn = document.createElement("button");
incBtn.className = "pm-multi-lm-step-btn";
incBtn.type = "button";
incBtn.textContent = ">";
decBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) - 1));
incBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) + 1));
stepper.appendChild(decBtn);
stepper.appendChild(valueEl);
stepper.appendChild(incBtn);
stackControl.appendChild(stackLabel);
stackControl.appendChild(stepper);
topbar.appendChild(stackControl);
root.appendChild(topbar);
// 4-column LoRA grid
const grid = document.createElement("div");
grid.className = "pm-multi-lm-grid";
root.appendChild(grid);
const slots = SLOT_DEFS.map((slotDef) => {
const slot = buildSlotColumn(node, lm, slotDef);
grid.appendChild(slot.col);
return slot;
});
const uiWidget = node.addDOMWidget("multi_lora_ui", "div", root, {
serialize: false,
hideOnZoom: false,
getMinHeight: () => computeContentHeight(node),
getHeight: () => "100%",
});
node.__pmMultiLmBridge = lm;
node.__pmMultiLmSlots = slots;
node.__pmMultiLmGrid = grid;
node.__pmStackControl = { dec: decBtn, inc: incBtn, value: valueEl };
node.__pmMultiLmRoot = root;
node.__pmMultiLmReady = true;
node.__pmMultiLmRefresh = () => {
refreshFromStoredValues(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
syncStackCountWidget(node, getStackCount(node));
updateActiveColumnHighlight(node);
};
// comfyClass already set synchronously in onNodeCreated — no registry tricks needed
// Restore any lora data that onConfigure may have written before async completed
refreshFromStoredValues(node);
hideStateWidgets(node);
applyVisibleStackCount(node);
updateStackControlUi(node);
updateActiveColumnHighlight(node);
notifyHeightChange(node);
applyNodeSizeConstraints(node);
}
// ---------------------------------------------------------------------------
// Extension registration
// ---------------------------------------------------------------------------
app.registerExtension({
name: "PromptManager.MultiLoraStackerLM",
async beforeRegisterNodeDef(nodeType) {
if (nodeType.comfyClass !== NODE_CLASS) return;
// Attach the send-to-node listener once, immediately (synchronous)
attachLoraCodeListener();
// Ensure prompt uses backend class while keeping LM comfyClass at runtime.
attachPromptSerializationShim();
// ── onNodeCreated ──────────────────────────────────────────────────
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
this.serialize_widgets = true;
// Set comfyClass SYNCHRONOUSLY so LM WorkflowRegistry includes us
// on the next lora_registry_refresh sweep
this.comfyClass = LM_PROVIDER_CLASS;
if (!this.properties) this.properties = {};
if (!this.properties.pmActiveSlot) this.properties.pmActiveSlot = "model_a";
if (!Number.isFinite(Number(this.properties.pmLoraStackCount))) {
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
} else {
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
}
ensureActiveSlotVisible(this);
syncStackCountWidget(this, this.properties.pmLoraStackCount);
applyNodeSizeConstraints(this, true);
void setupNodeUi(this);
return result;
};
// ── onConfigure (workflow load / tab switch) ──────────────────────
const onConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (config) {
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
// Re-assert comfyClass in case ComfyUI reset it during configure
this.comfyClass = LM_PROVIDER_CLASS;
hideStateWidgets(this);
if (!Number.isFinite(Number(this.properties?.pmLoraStackCount))) {
if (!this.properties) this.properties = {};
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
} else {
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
}
ensureActiveSlotVisible(this);
syncStackCountWidget(this, this.properties.pmLoraStackCount);
if (typeof this.__pmMultiLmRefresh === "function") {
this.__pmMultiLmRefresh();
}
applyNodeSizeConstraints(this);
return result;
};
const onModeChange = nodeType.prototype.onModeChange;
nodeType.prototype.onModeChange = function () {
const result = onModeChange ? onModeChange.apply(this, arguments) : undefined;
hideStateWidgets(this);
if (typeof this.__pmMultiLmRefresh === "function") {
this.__pmMultiLmRefresh();
}
applyNodeSizeConstraints(this);
return result;
};
const onResize = nodeType.prototype.onResize;
nodeType.prototype.onResize = function () {
const result = onResize ? onResize.apply(this, arguments) : undefined;
applyNodeSizeConstraints(this);
return result;
};
// ── onRemoved ──────────────────────────────────────────────────────
const onRemoved = nodeType.prototype.onRemoved;
nodeType.prototype.onRemoved = function () {
if (Array.isArray(this.__pmMultiLmSlots)) {
for (const slot of this.__pmMultiLmSlots) {
try {
slot?.fastPreviewCleanup?.();
} catch (_e) {
}
}
}
this.__pmMultiLmSlots = null;
this.__pmMultiLmRoot = null;
this.__pmMultiLmBridge = null;
this.__pmMultiLmGrid = null;
this.__pmStackControl = null;
this.__pmMultiLmReady = false;
this.__pmMultiLmRefresh = null;
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
};
},
});
+119
View File
@@ -0,0 +1,119 @@
/**
* Prompt Manager's side of the shared file browser (file_browser.js, the
* same file as in FBnodes): its routes and Custom-folder setting, root
* resolution, and the input/output/absolute selection classifier, so the
* Prompt Extractor can browse anywhere while keeping old workflows working.
*/
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
export const SETTING_CUSTOM_PATH = "PromptManager.PromptExtractorCustomPath";
// This pack's routes for the shared file browser.
export const BROWSER_ROUTES = {
list: "/prompt-extractor/path-browser/list",
file: "/prompt-extractor/path-browser/file",
remove: "/prompt-extractor/path-browser/delete",
videoFrame: "/prompt-extractor/video-frame",
};
export function getCustomPresetPath() {
const pref = app.ui?.settings?.getSettingValue(SETTING_CUSTOM_PATH) || "";
return typeof pref === "string" ? pref.trim() : "";
}
/** Store the Custom folder (the same setting as in Preferences). */
export function setCustomPresetPath(path) {
return app.ui.settings.setSettingValueAsync(SETTING_CUSTOM_PATH, String(path || "").trim());
}
/** URL that streams a media file from any path (for previews of out-of-tree files). */
export function mediaFileUrl(absPath) {
return api.apiURL(`${BROWSER_ROUTES.file}?path=${encodeURIComponent(absPath)}`);
}
function normalizeSlashes(p) {
return String(p || "").replace(/\\/g, "/");
}
/** True when `child` is inside `parent` (both absolute), case-insensitive on Windows. */
function isUnder(child, parent) {
if (!child || !parent) return false;
let c = normalizeSlashes(child).replace(/\/+$/, "");
let p = normalizeSlashes(parent).replace(/\/+$/, "");
if (navigator.platform.startsWith("Win")) {
c = c.toLowerCase();
p = p.toLowerCase();
}
return c === p || c.startsWith(p + "/");
}
/**
* Given a selected absolute path and the input/output roots, work out how to
* store it so old workflows keep working:
* - inside input -> { sourceFolder:"input", value:<relative> }
* - inside output -> { sourceFolder:"output", value:<relative> }
* - elsewhere -> { sourceFolder:null, value:<absolute> }
*/
export function classifySelection(absPath, roots) {
const inputRoot = roots?.input || "";
const outputRoot = roots?.output || "";
const norm = normalizeSlashes(absPath);
if (inputRoot && isUnder(absPath, inputRoot)) {
const rel = norm.slice(normalizeSlashes(inputRoot).replace(/\/+$/, "").length + 1);
return { sourceFolder: "input", value: rel, absPath };
}
if (outputRoot && isUnder(absPath, outputRoot)) {
const rel = norm.slice(normalizeSlashes(outputRoot).replace(/\/+$/, "").length + 1);
return { sourceFolder: "output", value: rel, absPath };
}
return { sourceFolder: null, value: absPath, absPath };
}
async function fetchBrowser(path, kind) {
const params = [];
if (path) params.push(`path=${encodeURIComponent(path)}`);
if (kind) params.push(`kind=${encodeURIComponent(kind)}`);
const query = params.length ? `?${params.join("&")}` : "";
const resp = await api.fetchApi(`${BROWSER_ROUTES.list}${query}`);
if (!resp.ok) {
let msg = `Request failed (${resp.status})`;
try {
const err = await resp.json();
if (err?.error) msg = err.error;
} catch {
// ignore
}
throw new Error(msg);
}
return await resp.json();
}
/** Resolve the input/output preset roots once (backend "roots" mode). */
export async function getMediaRoots() {
try {
const data = await fetchBrowser("", "");
const roots = Array.isArray(data?.roots) ? data.roots : [];
return { input: roots[0] || "", output: roots[1] || "" };
} catch {
return { input: "", output: "" };
}
}
// Register the shared Custom-path preference once.
app.registerExtension({
name: "PromptManager.PromptExtractorPathBrowser",
settings: [
{
id: SETTING_CUSTOM_PATH,
category: ["Prompt Manager", "Prompt Extractor", "Custom Browser Path"],
name: "Prompt Extractor Custom Browser Path",
tooltip: "The folder the Custom button opens in the Prompt Extractor's file browser.",
type: "text",
defaultValue: "",
},
],
});
BIN
View File
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 747 B

After

Width:  |  Height:  |  Size: 29 KiB

+95
View File
@@ -0,0 +1,95 @@
// Prompt Manager's small form dialogs on the FB UI kit modal: text fields and
// selects in a column, Enter to confirm, Esc or a click outside to cancel.
//
// formDialog({ title, fields, confirmText }) -> Promise<{ [key]: value } | null>
// fields: [{ key, label, type: "text" | "select" | "check", value, options }]
// options: values or { value, label }, or (values) => options for a select
// that follows the fields above it (a category list per prompt group).
import { button } from "./fbui/controls.js";
import { el } from "./fbui/dom.js";
import { openModal } from "./fbui/modal.js";
import { T } from "./fbui/theme.js";
function fillSelect(select, options, value) {
select.replaceChildren(...options.map((option) => {
const entry = typeof option === "object" && option ? option : { value: option, label: option };
const item = el("option", "", String(entry.label ?? entry.value ?? ""));
item.value = String(entry.value ?? "");
return item;
}));
if (options.length) select.value = String(value ?? "");
if (!select.value && select.options.length) select.selectedIndex = 0;
}
export function formDialog({ title, fields, confirmText = "OK" }) {
return new Promise((resolve) => {
let answer = null;
const controls = new Map();
const values = () => Object.fromEntries([...controls].map(([key, control]) => [key, control.type === "checkbox" ? control.checked : control.value]));
const refreshDependent = () => {
for (const field of fields) {
if (field.type === "select" && typeof field.options === "function") {
const select = controls.get(field.key);
const keep = select.value || field.value;
fillSelect(select, field.options(values()), keep);
}
}
};
const body = fields.map((field, index) => {
if (field.type === "check") {
const box = el("input");
box.type = "checkbox";
box.checked = Boolean(field.value);
box.style.cssText = `margin:0;accent-color:${T.brand}`;
controls.set(field.key, box);
const row = el("label");
row.style.cssText = `display:flex;align-items:center;gap:8px;margin-top:${index ? 10 : 0}px;color:${T.inkSoft};font-size:12px;cursor:pointer`;
row.append(box, el("span", "", field.label));
return row;
}
const label = el("div", "", field.label);
label.style.cssText = `margin:${index ? 10 : 0}px 0 5px;color:${T.label};font-size:12px`;
let control;
if (field.type === "select") {
control = el("select", "fbui-select");
if (typeof field.options !== "function") fillSelect(control, field.options ?? [], field.value);
control.addEventListener("change", refreshDependent);
} else {
control = el("input", "fbui-text");
control.type = "text";
control.spellcheck = false;
control.value = String(field.value ?? "");
}
control.style.width = "100%";
// Enter moves to the next field, and confirms on the last one.
control.addEventListener("keydown", (event) => {
if (event.key !== "Enter") return;
event.preventDefault();
const next = [...controls.values()].slice([...controls.keys()].indexOf(field.key) + 1).find((other) => other.type !== "checkbox");
if (next) next.focus();
else accept();
});
controls.set(field.key, control);
const row = el("div");
row.append(label, control);
return row;
});
const accept = () => {
answer = values();
dialog.close();
};
const dialog = openModal({
title,
body,
width: 440,
footer: [button("Cancel", { onClick: () => dialog.close() }), button(confirmText, { primary: true, onClick: accept })],
onClose: () => resolve(answer),
});
refreshDependent();
const first = controls.values().next().value;
first?.focus();
if (first?.type === "text") first.select();
});
}
+5067
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
import { api } from "../../scripts/api.js";
import { COMPOSER_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
const COMPOSER_CATEGORY_KEY_SEPARATOR = "::";
function newComposerLibrary() {
return { __meta__: { schema_version: 2, storage: "type_files" }, _types_: {} };
}
function isCanonicalComposerLibrary(library) {
return !!(
library
&& typeof library === "object"
&& !Array.isArray(library)
&& library._types_
&& typeof library._types_ === "object"
&& !Array.isArray(library._types_)
);
}
function normalizeComposerLibrary(library) {
if (!isCanonicalComposerLibrary(library)) {
throw new Error("Prompt Composer requires canonical v2 library data with _types_");
}
return library;
}
function getComposerTypeOrder(typeData) {
const numeric = Number(typeData?.order);
return Number.isInteger(numeric) ? numeric : Number.POSITIVE_INFINITY;
}
function getOrderedComposerTypes(types) {
const entries = Object.entries(types || {});
const hasExplicitOrder = entries.some(([, typeData]) => Number.isInteger(Number(typeData?.order)));
if (!hasExplicitOrder) {
return entries.sort((a, b) => String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" }));
}
return entries.sort((a, b) => {
const orderDiff = getComposerTypeOrder(a[1]) - getComposerTypeOrder(b[1]);
if (orderDiff !== 0) return orderDiff;
return String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" });
});
}
function buildComposerCategoryKey(typeFile, categoryName) {
const normalizedTypeFile = String(typeFile || "").trim();
const normalizedCategory = String(categoryName || "").trim();
if (!normalizedTypeFile) return normalizedCategory;
return `${normalizedTypeFile}${COMPOSER_CATEGORY_KEY_SEPARATOR}${normalizedCategory}`;
}
function normalizeComposerSubjectKind(value, fallback = "other") {
const normalized = String(value || "").trim().toLowerCase();
if (["character", "animal", "environment", "other"].includes(normalized)) {
return normalized;
}
if (normalized === "person") return "character";
return fallback;
}
function defaultComposerSubjectKind(subjectType) {
return String(subjectType || "").trim().toLowerCase() === "new_subject" ? "character" : "other";
}
function parseComposerCategoryKey(category) {
const raw = String(category || "").trim();
const separatorIndex = raw.indexOf(COMPOSER_CATEGORY_KEY_SEPARATOR);
if (separatorIndex <= 0) {
return { typeFile: "", categoryName: raw };
}
return {
typeFile: raw.slice(0, separatorIndex).trim(),
categoryName: raw.slice(separatorIndex + COMPOSER_CATEGORY_KEY_SEPARATOR.length).trim(),
};
}
export function resolveComposerCategoryKey(data, category) {
const raw = String(category || "").trim();
if (!raw) return "";
if (data?.[raw] && typeof data[raw] === "object") {
return raw;
}
const parsed = parseComposerCategoryKey(raw);
const normalizedCategoryName = String(parsed.categoryName || raw).trim().toLowerCase();
const normalizedTypeFile = String(parsed.typeFile || "").trim().toLowerCase();
let fallback = "";
for (const [categoryKey, categoryData] of Object.entries(data || {})) {
if (categoryKey === "__meta__" || !categoryData || typeof categoryData !== "object") continue;
const candidateCategoryName = String(categoryData._category_name_ || categoryKey).trim().toLowerCase();
if (candidateCategoryName !== normalizedCategoryName) continue;
const candidateTypeFile = String(categoryData._type_file_ || "").trim().toLowerCase();
if (normalizedTypeFile && candidateTypeFile === normalizedTypeFile) {
return categoryKey;
}
if (!fallback) {
fallback = categoryKey;
}
}
if (fallback) return fallback;
if (parsed.typeFile && parsed.categoryName) {
return buildComposerCategoryKey(parsed.typeFile, parsed.categoryName);
}
return raw;
}
function flattenComposerType(typeFile, typeData, flatData) {
if (!typeData || typeof typeData !== "object") return;
const typeKey = String(typeFile || "").replace(/\.json$/i, "").trim().toLowerCase();
const typeName = String(typeData.name || "").trim() || typeKey || "Misc";
const typePrefix = String(typeData.prefix || "");
const typeBasePrompt = String(typeData.base_prompt || "");
const typeSubjectType = String(typeData.subject_type || "subject").trim().toLowerCase() || "subject";
const typeSubjectKind = normalizeComposerSubjectKind(typeData.subject_kind, defaultComposerSubjectKind(typeSubjectType));
const typeNsfw = typeData.nsfw === true;
const categories = typeData.categories;
if (!categories || typeof categories !== "object" || Array.isArray(categories)) return;
for (const [categoryName, categoryData] of Object.entries(categories)) {
if (!categoryName || !categoryData || typeof categoryData !== "object") continue;
const promptEntries = categoryData._prompts_ && typeof categoryData._prompts_ === "object"
? categoryData._prompts_
: {};
const effectivePrefix = String(categoryData.prefix || typePrefix || "");
const effectiveBasePrompt = String(categoryData.base_prompt || typeBasePrompt || "");
const effectiveNsfw = categoryData.nsfw === true || typeNsfw;
const flatCategory = {
_prompts_: promptEntries,
_category_name_: String(categoryName || "").trim(),
_prompt_type_: typeKey,
_type_file_: String(typeFile || ""),
_type_name_: typeName,
_subject_type_: typeSubjectType,
_subject_kind_: typeSubjectKind,
};
if (effectivePrefix.trim()) flatCategory._prompt_prefix_ = effectivePrefix;
if (effectiveBasePrompt.trim()) flatCategory._base_prompt_ = effectiveBasePrompt;
if (String(categoryData.prefix || "").trim()) flatCategory._category_prefix_ = String(categoryData.prefix || "");
if (String(categoryData.base_prompt || "").trim()) flatCategory._category_base_prompt_ = String(categoryData.base_prompt || "");
if (typePrefix.trim()) flatCategory._type_prefix_ = typePrefix;
if (typeBasePrompt.trim()) flatCategory._type_base_prompt_ = typeBasePrompt;
if (typeNsfw) flatCategory._type_nsfw_ = true;
if (effectiveNsfw) flatCategory.__meta__ = { nsfw: true };
flatData[buildComposerCategoryKey(typeFile, categoryName)] = flatCategory;
}
}
export function flattenComposerLibrary(library) {
const normalized = normalizeComposerLibrary(library);
const flatData = { __meta__: normalized.__meta__ || { schema_version: 2, storage: "type_files" } };
for (const [typeFile, typeData] of getOrderedComposerTypes(normalized._types_ || {})) {
flattenComposerType(typeFile, typeData, flatData);
}
return flatData;
}
export async function loadComposerPrompts(node) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/get-prompts`, {
cache: "no-store",
});
const library = await resp.json();
node.composerPromptLibrary = normalizeComposerLibrary(library);
node.composerPrompts = flattenComposerLibrary(node.composerPromptLibrary);
// Make the shared browser see composer data instead of prompt_manager_data.json.
node.prompts = node.composerPrompts;
} catch (err) {
console.error("[PromptComposer] Error loading composer prompts:", err);
node.composerPromptLibrary = newComposerLibrary();
node.composerPrompts = {};
node.prompts = {};
}
return node.composerPrompts;
}
function getComposerData(node) {
// The shared browser mutates node.prompts; for composer nodes that is always composer data.
return node.prompts || node.composerPrompts || {};
}
export function getComposerCategories(node) {
const data = getComposerData(node);
return Object.keys(data).filter((c) => c !== "__meta__").sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
export function getComposerNames(node, category) {
const data = getComposerData(node);
const catData = data[resolveComposerCategoryKey(data, category)];
if (!catData || typeof catData !== "object") return [];
return Object.keys(getCategoryPromptEntries(catData, "composer")).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
export function getComposerEntry(node, category, name) {
const data = getComposerData(node);
const catData = data[resolveComposerCategoryKey(data, category)];
if (!catData || typeof catData !== "object") return null;
return getCategoryPromptEntries(catData, "composer")[name] || null;
}
export async function saveComposerCategorySettings(category, settings) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-category-settings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category,
type_file: settings.typeFile || "",
base_prompt: settings.basePrompt || "",
prompt_type: settings.promptType || "",
prefix: settings.promptPrefix || "",
}),
});
return await resp.json();
} catch (err) {
console.error("[PromptComposer] Error saving category settings:", err);
return { success: false, error: String(err) };
}
}
export async function saveComposerTypeSettings(settings) {
try {
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-type-settings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type_file: settings.typeFile || "",
prompt_type: settings.promptType || "",
type_name: settings.typeName || "",
subject_type: settings.subjectType || "subject",
subject_kind: normalizeComposerSubjectKind(
settings.subjectKind,
defaultComposerSubjectKind(settings.subjectType || "subject")
),
prefix: settings.promptPrefix || "",
base_prompt: settings.basePrompt || "",
}),
});
return await resp.json();
} catch (err) {
console.error("[PromptComposer] Error saving type settings:", err);
return { success: false, error: String(err) };
}
}
export { COMPOSER_ENDPOINT_PREFIX };
+1323 -171
View File
File diff suppressed because it is too large Load Diff
+414
View File
@@ -0,0 +1,414 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { showThumbnailBrowser } from "./prompt_browser.js";
import { SYSTEM_PROMPTS_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
import { setPromptTextLocked } from "./prompt_text_lock.js";
function setupSystemPromptSelector(node) {
const widget = node.widgets?.find(w => w.name === "system_prompt");
if (!widget || widget.type === "system_prompt_selector") return;
const selectPrompt = async (value) => {
widget.value = value;
await widget.callback?.call(widget, value, app.canvas, node);
updateDisplay();
node.setDirtyCanvas(true, true);
};
const loadSystemPrompts = async () => {
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/get-prompts`, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load system prompts (${response.status})`);
const prompts = await response.json();
node.prompts = prompts;
// The combo list comes from page load; keep it current with prompts added or moved since.
const choices = getChoices(prompts);
if (choices.length && widget.options && typeof widget.options.values !== "function") widget.options.values = choices;
return prompts;
};
const getChoices = (prompts) => Object.entries(prompts)
.filter(([category, entries]) => !category.startsWith("_") && entries && typeof entries === "object")
.flatMap(([category, entries]) => Object.entries(getCategoryPromptEntries(entries, "generator"))
.filter(([name, entry]) => {
const text = entry && typeof entry === "object" ? entry.prompt : entry;
return !name.startsWith("_") && String(text ?? "").trim();
})
.map(([name]) => `${category} / ${name}`))
.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));
let busy = false;
const activate = async (direction) => {
if (busy) return;
busy = true;
try {
if (direction) {
const choices = getChoices(await loadSystemPrompts());
if (!choices.length) return;
const index = choices.indexOf(widget.value);
const nextIndex = index < 0
? (direction > 0 ? 0 : choices.length - 1)
: (index + direction + choices.length) % choices.length;
await selectPrompt(choices[nextIndex]);
} else {
const value = String(widget.value ?? "");
const separator = value.indexOf(" / ");
const category = separator < 0 ? "" : value.slice(0, separator);
const name = separator < 0 ? value : value.slice(separator + 3);
const selection = await showThumbnailBrowser(node, category, name, {
title: "Select System Prompt",
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
loadPromptsFn: loadSystemPrompts,
preferenceScope: "system",
promptOnly: true,
allowMultiSelect: false,
});
if (selection?.prompt) {
await selectPrompt(`${selection.category} / ${selection.prompt}`);
}
}
} catch (error) {
console.error("[PromptGenerator] System prompt selection failed:", error);
app.extensionManager.toast.add({
severity: "error",
summary: "System prompts unavailable",
detail: String(error.message || error),
});
} finally {
busy = false;
}
};
const container = document.createElement("div");
// Mirrors Prompt Manager's selector; the dark backing is what keeps the translucent name button dark.
container.style.cssText = `
display: flex;
align-items: center;
gap: 0;
background: #1a1a1a;
border-radius: 6px;
width: 100%;
min-width: 0;
height: 26px;
box-sizing: border-box;
`;
for (const eventName of ["pointerdown", "mousedown", "dblclick"]) {
container.addEventListener(eventName, event => event.stopPropagation());
}
const makeButton = (label, title, direction) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.setAttribute("aria-label", title);
button.style.cssText = `
background: #2a2a2a;
border: none;
color: #888;
padding: 0 10px;
height: 100%;
cursor: pointer;
font-size: 12px;
transition: all 0.15s ease;
`;
button.addEventListener("mouseover", () => {
button.style.background = direction ? "#3a3a3a" : "rgba(56, 130, 246, 0.32)";
if (direction) button.style.color = "#fff";
});
button.addEventListener("mouseout", () => {
button.style.background = direction ? "#2a2a2a" : "rgba(56, 130, 246, 0.22)";
if (direction) button.style.color = "#888";
});
button.addEventListener("click", event => {
event.stopPropagation();
void activate(direction);
});
container.appendChild(button);
return button;
};
makeButton("\u25c0", "Previous system prompt", -1);
const nameButton = makeButton("", "Browse System Prompts", 0);
nameButton.style.cssText = `
flex: 1;
min-width: 0;
text-align: center;
color: #dbeafe;
font-family: inherit;
font-size: 15px;
padding: 0 10px;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background: rgba(56, 130, 246, 0.22);
border: 1px solid rgba(56, 130, 246, 0.85);
border-radius: 4px;
height: 100%;
transition: background 0.15s ease;
box-sizing: border-box;
`;
makeButton("\u25b6", "Next system prompt", 1);
const updateDisplay = () => {
nameButton.textContent = String(widget.value ?? "").replace(" / ", " : ");
nameButton.title = `Browse System Prompts: ${widget.value ?? ""}`;
};
const index = node.widgets.indexOf(widget);
const selector = node.addDOMWidget("system_prompt", "system_prompt_selector", container, {
getMinHeight: () => 26,
getMaxHeight: () => 26,
getValue: () => widget.value,
setValue: value => {
widget.value = value;
updateDisplay();
},
});
selector.computeSize = width => [width, 28];
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
selector.computeLayoutSize = undefined;
selector.serializeValue = () => widget.value;
node.widgets.splice(node.widgets.indexOf(selector), 1);
node.widgets.splice(index, 1, selector);
const matchChoice = (value, choices, allowFallback) => {
const normalized = String(value ?? "").trim().toLowerCase();
const entries = choices.map(choice => {
const separator = choice.indexOf(" / ");
return { value: choice, category: choice.slice(0, separator), name: choice.slice(separator + 3) };
});
const exact = entries.find(entry => entry.value.toLowerCase() === normalized);
const legacy = entries.find(entry => `${entry.name} (${entry.category})`.toLowerCase() === normalized);
// A prompt moved to another category keeps its name.
const previousName = normalized.includes(" / ") ? normalized.slice(normalized.indexOf(" / ") + 3) : normalized;
const names = entries.filter(entry => entry.name.toLowerCase() === previousName);
const match = exact || legacy || (names.length === 1 ? names[0] : null);
if (match || !allowFallback) return match;
return entries.find(entry => entry.value.toLowerCase() === "image / enhance prompt") || entries[0] || null;
};
const applyMatch = (match) => {
if (!match || widget.value === match.value) return;
const previous = widget.value;
selector.value = match.value;
console.log(`[PromptGenerator] Migrated system prompt '${previous}' to '${match.value}'.`);
node.setDirtyCanvas(true, true);
};
// The combo's choices date from page load, so canonical values are checked against the live list.
const reconcileSelection = async () => {
let choices;
try {
choices = getChoices(await loadSystemPrompts());
} catch (error) {
console.warn("[PromptGenerator] Could not refresh system prompts; keeping the saved selection.", error);
return;
}
if (choices.length) applyMatch(matchChoice(widget.value, choices, true));
};
const onConfigure = node.onConfigure;
node.onConfigure = function() {
const result = onConfigure?.apply(this, arguments);
// Legacy labels such as "Enhance Prompt (Image)" migrate at once so an immediate queue never sends them.
if (!String(widget.value ?? "").includes(" / ")) {
const choices = typeof widget.options?.values === "function" ? widget.options.values() : widget.options?.values;
if (Array.isArray(choices) && choices.length) applyMatch(matchChoice(widget.value, choices, false));
}
void reconcileSelection();
return result;
};
updateDisplay();
}
function migrateLegacyPromptGenOptionsWidgets(node) {
if (!node?.widgets || node.widgets.length === 0) {
return false;
}
const byName = (name) => node.widgets.find(w => w.name === name);
const modeWidget = byName("system_prompt_mode");
const systemPromptWidget = byName("system_prompt");
const useDefaultWidget = byName("use_model_default_sampling");
const temperatureWidget = byName("temperature");
const topKWidget = byName("top_k");
const topPWidget = byName("top_p");
const minPWidget = byName("min_p");
const repeatPenaltyWidget = byName("repeat_penalty");
const contextSizeWidget = byName("context_size");
const showConsoleWidget = byName("show_everything_in_console");
if (!modeWidget || !systemPromptWidget || !useDefaultWidget || !temperatureWidget ||
!topKWidget || !topPWidget || !minPWidget || !repeatPenaltyWidget ||
!contextSizeWidget || !showConsoleWidget) {
return false;
}
const modeIsValid = modeWidget.value === "replace" || modeWidget.value === "append";
const looksLegacyShape = typeof systemPromptWidget.value === "boolean" && typeof useDefaultWidget.value === "number";
if (modeIsValid && !looksLegacyShape) {
return false;
}
const oldSystemPrompt = modeWidget.value;
const oldUseDefaultSampling = systemPromptWidget.value;
const oldTemperature = useDefaultWidget.value;
const oldTopK = temperatureWidget.value;
const oldTopP = topPWidget.value;
const oldMinP = topPWidget.value;
const oldRepeatPenalty = repeatPenaltyWidget.value;
const oldContextSize = contextSizeWidget.value;
const oldShowInConsole = showConsoleWidget.value;
modeWidget.value = "replace";
systemPromptWidget.value = typeof oldSystemPrompt === "string" ? oldSystemPrompt : "";
useDefaultWidget.value = Boolean(oldUseDefaultSampling);
temperatureWidget.value = Number(oldTemperature);
topKWidget.value = Number.isFinite(Number(oldTopK)) ? Math.round(Number(oldTopK)) : oldTopK;
topPWidget.value = Number(oldTopP);
minPWidget.value = Number(oldMinP);
repeatPenaltyWidget.value = Number(oldRepeatPenalty);
contextSizeWidget.value = Number.isFinite(Number(oldContextSize)) ? Math.round(Number(oldContextSize)) : oldContextSize;
showConsoleWidget.value = Boolean(oldShowInConsole);
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
console.log("[PromptManager] Migrated legacy PromptGenOptions widget order for workflow compatibility.");
return true;
}
app.registerExtension({
name: "comfyui-prompt-manager.generator",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
// Make the Options node taller/wider by default so the system_prompt area is roomier
if (nodeData.name === "PromptGenOptions") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
migrateLegacyPromptGenOptionsWidgets(this);
// Model selection now lives on the Prompt Generator base node. The
// Options node's model widget is kept (hidden) purely so old workflows
// still load and pass their value through as a fallback.
const modelWidget = this.widgets?.find(w => w.name === "model");
if (modelWidget) {
modelWidget.hidden = true;
modelWidget.computeSize = () => [0, -4];
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
}
// Set a default size (width x height)
try {
this.setSize([400, 420]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
const onConfigureOpt = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function(info) {
const result = onConfigureOpt?.apply(this, arguments);
migrateLegacyPromptGenOptionsWidgets(this);
// Re-hide the legacy model widget on restore (tab switch / reload).
const modelWidget = this.widgets?.find(w => w.name === "model");
if (modelWidget) {
modelWidget.hidden = true;
modelWidget.computeSize = () => [0, -4];
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
}
return result;
};
// Enforce sensible minimums when the user resizes the options node
const onResizeOpt = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
};
}
// Enforce minimum size for PromptGenerator node (no default size)
if (nodeData.name === "PromptGenerator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
setupSystemPromptSelector(this);
// Set a default size (width x height) - taller to fit the UI comfortably
try {
this.setSize([400, 600]);
} catch (e) {
// ignore if method unavailable
}
// Darken + make the prompt widget read-only while a `prompt_input`
// link is connected (mirrors PromptManager's use_prompt_input UI).
const node = this;
const promptWidget = node.widgets?.find(w => w.name === "prompt");
const promptInputSlot = () => node.inputs?.find(i => i && i.name === "prompt_input");
const isPromptInputConnected = () => {
const inp = promptInputSlot();
return !!(inp && inp.link != null);
};
const applyPromptInputState = () => {
setPromptTextLocked(promptWidget, isPromptInputConnected());
};
// Python echoes back the value it actually received on prompt_input
// (only when that input was connected) in the "executed" event.
// Display it here; when the key is absent, never touch the widget.
const prevOnConnectionsChange = node.onConnectionsChange;
node.onConnectionsChange = function () {
const r = prevOnConnectionsChange?.apply(this, arguments);
applyPromptInputState();
return r;
};
const prevOnConfigure = node.onConfigure;
node.onConfigure = function () {
const r = prevOnConfigure?.apply(this, arguments);
applyPromptInputState();
return r;
};
const prevOnExecuted = node.onExecuted;
node.onExecuted = function (output) {
const r = prevOnExecuted?.apply(this, arguments);
applyPromptInputState();
const echoed = output && output.ui ? output.ui.prompt : null;
if (Array.isArray(echoed) && typeof echoed[0] === "string" && echoed[0].length > 0) {
promptWidget.value = echoed[0];
if (promptWidget.inputEl) {
promptWidget.inputEl.value = echoed[0];
}
node.setDirtyCanvas(true, true);
}
return r;
};
// Listen for incoming prompt_input text updates from the backend.
// This fires at the very start of execution, before the LLM call.
api.addEventListener("prompt-generator-update-text", (event) => {
if (String(event.detail.node_id) === String(node.id)) {
const incoming = event.detail.prompt || "";
if (event.detail.has_prompt_input) {
if (promptWidget) {
promptWidget.value = incoming;
if (promptWidget.inputEl) {
promptWidget.inputEl.value = incoming;
}
setPromptTextLocked(promptWidget, true);
}
} else {
setPromptTextLocked(promptWidget, false);
}
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
}
});
// Initial state.
applyPromptInputState();
return result;
};
const onResizeModel = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
};
}
}
});
console.log("[PromptManager] PromptGenerator extension loaded");
File diff suppressed because it is too large Load Diff
+584
View File
@@ -0,0 +1,584 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { PM_UI_PALETTE as UI } from "./ui_palette.js";
import { showInfo, showConfirm } from "./prompt_manager_advanced.js";
import { showThumbnailBrowser, getPromptNamesForCategory } from "./prompt_browser.js";
import {
exportComposerJsonLibrary,
mergeComposerJsonLibrary,
openComposerJsonLibrary,
showComposerImportModeDialog,
triggerBrowserDownload,
} from "./prompt_composer.js";
import { loadComposerPrompts } from "./prompt_composer_common.js";
import {
COMPOSER_ENDPOINT_PREFIX,
PROMPT_ADVANCED_ENDPOINT_PREFIX,
PROMPT_ENDPOINT_PREFIX,
SYSTEM_PROMPTS_ENDPOINT_PREFIX,
getCategoryPromptEntries,
isHiddenPromptEntryKey,
} from "./prompt_store_adapters.js";
const HUB_TITLE = "Prompt Library Hub";
const STYLE_ID = "pm-library-hub-style";
// Saved prompts of every type (prompts, recipes, Composer setups, layouts) share
// prompt_manager_data.json; the Prompt Browser's Type filter tells them apart.
const SECTIONS = [
{ id: "prompts", title: "Saved Prompts", store: "manager", hint: "Prompts, recipes, Composer setups and layouts saved from Prompt Manager or Library Manager. Filter them by Type in the browser.", unit: "entr" },
{ id: "snippets", title: "Saved Snippets", browseTitle: "Saved Composer Snippets", store: "composer", hint: "Prompt snippets used by Prompt Composer.", unit: "snippet" },
{ id: "system", title: "Saved System Prompts", store: "generator", hint: "System prompts used by Prompt Generator.", unit: "prompt" },
];
const plural = (count, unit) => `${count} ${unit === "entr" ? (count === 1 ? "entry" : "entries") : `${unit}${count === 1 ? "" : "s"}`}`;
function libraryFor(section) {
return { id: section.id, title: section.browseTitle || section.title, store: section.store, unit: section.unit };
}
const STORE_ENDPOINTS = {
generator: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
composer: COMPOSER_ENDPOINT_PREFIX,
manager: PROMPT_ADVANCED_ENDPOINT_PREFIX,
};
// Stand-in "node" objects: the shared browser and Composer helpers keep their loaded data on these.
const hosts = {
generator: { prompts: {} },
composer: { prompts: {} },
manager: { prompts: {} },
};
async function fetchStore(host, endpointPrefix) {
const response = await api.fetchApi(`${endpointPrefix}/get-prompts`, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load ${endpointPrefix} (${response.status})`);
host.prompts = await response.json();
return host.prompts;
}
const loadSystemPrompts = (host) => fetchStore(host, SYSTEM_PROMPTS_ENDPOINT_PREFIX);
const loadManagerPrompts = (host) => fetchStore(host, PROMPT_ADVANCED_ENDPOINT_PREFIX);
function categoryNames(data) {
return Object.keys(data || {})
.filter((category) => category !== "__meta__" && data[category] && typeof data[category] === "object")
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
function entryNames(library, category) {
const data = hosts[library.store].prompts;
if (library.store === "manager") {
return getPromptNamesForCategory(hosts.manager, category, { endpointPrefix: PROMPT_ADVANCED_ENDPOINT_PREFIX });
}
return Object.keys(getCategoryPromptEntries(data?.[category], library.store));
}
function summarize(library) {
const data = hosts[library.store].prompts;
let entries = 0;
let categories = 0;
for (const category of categoryNames(data)) {
const count = entryNames(library, category).length;
entries += count;
if (count) categories += 1;
}
const groups = library.store === "composer" ? Object.keys(hosts.composer.composerPromptLibrary?._types_ || {}).length : 0;
return { entries, categories, groups };
}
function timestamp() {
return new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
}
function pickJsonFile() {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json,application/json";
input.onchange = () => resolve(input.files?.[0] || null);
input.oncancel = () => resolve(null);
input.click();
});
}
async function readLibraryFile() {
const file = await pickJsonFile();
if (!file) return null;
let data;
try {
data = JSON.parse(await file.text());
} catch {
throw new Error(`"${file.name}" is not valid JSON.`);
}
if (!data || typeof data !== "object" || Array.isArray(data)) {
throw new Error(`"${file.name}" is not a prompt library (expected categories of entries).`);
}
return { file, data };
}
function makeButton(label, { primary = false, title = "" } = {}) {
const button = document.createElement("button");
button.type = "button";
button.textContent = label;
button.title = title;
button.className = primary ? "pm-hub-btn pm-hub-btn-primary" : "pm-hub-btn";
return button;
}
// Category picker modelled on Prompt Composer's "Save JSONs" dialog.
function showCategoryExportDialog(library, categories) {
return new Promise((resolve) => {
const selected = new Set(categories.map((item) => item.name));
const overlay = document.createElement("div");
overlay.className = "pm-hub-overlay";
const dialog = document.createElement("div");
dialog.className = "pm-hub-dialog";
const header = document.createElement("div");
header.className = "pm-hub-dialog-header";
const heading = document.createElement("div");
heading.className = "pm-hub-dialog-title";
heading.textContent = `Export ${library.title}`;
const hint = document.createElement("div");
hint.className = "pm-hub-muted";
hint.textContent = "Select the categories to export as one JSON file.";
header.append(heading, hint);
const body = document.createElement("div");
body.className = "pm-hub-dialog-grid";
const cards = new Map();
for (const item of categories) {
const card = document.createElement("button");
card.type = "button";
card.className = "pm-hub-pick";
const name = document.createElement("div");
name.className = "pm-hub-pick-name";
name.textContent = item.name;
const count = document.createElement("div");
count.className = "pm-hub-muted";
count.textContent = `${item.count} entr${item.count === 1 ? "y" : "ies"}`;
card.append(name, count);
card.onclick = () => {
if (selected.has(item.name)) selected.delete(item.name);
else selected.add(item.name);
sync();
};
cards.set(item.name, card);
body.appendChild(card);
}
const footer = document.createElement("div");
footer.className = "pm-hub-dialog-footer";
const info = document.createElement("div");
info.className = "pm-hub-muted";
info.style.marginRight = "auto";
const clearButton = makeButton("Clear");
const allButton = makeButton("Select All");
const cancelButton = makeButton("Cancel");
const saveButton = makeButton("Export JSON", { primary: true });
footer.append(info, clearButton, allButton, cancelButton, saveButton);
function sync() {
cards.forEach((card, name) => card.classList.toggle("active", selected.has(name)));
const total = categories.filter((item) => selected.has(item.name)).reduce((sum, item) => sum + item.count, 0);
info.textContent = `${selected.size} categor${selected.size === 1 ? "y" : "ies"} · ${total} entr${total === 1 ? "y" : "ies"}`;
saveButton.disabled = selected.size === 0;
}
const finish = (value) => {
overlay.remove();
resolve(value);
};
clearButton.onclick = () => { selected.clear(); sync(); };
allButton.onclick = () => { categories.forEach((item) => selected.add(item.name)); sync(); };
cancelButton.onclick = () => finish(null);
saveButton.onclick = () => finish(categories.map((item) => item.name).filter((name) => selected.has(name)));
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
dialog.append(header, body, footer);
overlay.appendChild(dialog);
document.body.appendChild(overlay);
sync();
});
}
async function exportLibrary(library) {
if (library.store === "composer") {
await loadComposerPrompts(hosts.composer);
await exportComposerJsonLibrary(hosts.composer);
return;
}
const data = hosts[library.store].prompts;
const categories = categoryNames(data)
.map((name) => ({ name, count: entryNames(library, name).length }))
.filter((item) => item.count > 0);
if (!categories.length) {
await showInfo("Nothing to Export", `${library.title} has no entries yet.`);
return;
}
const picked = await showCategoryExportDialog(library, categories);
if (!picked?.length) return;
const out = {};
for (const category of picked) {
const source = data[category];
const names = new Set(entryNames(library, category));
out[category] = Object.fromEntries(Object.entries(source).filter(([key]) => names.has(key) || isHiddenPromptEntryKey(key)));
}
const blob = new Blob([JSON.stringify(out, null, 2)], { type: "application/json" });
triggerBrowserDownload(blob, `${library.id}_${timestamp()}.json`);
}
function showChoiceDialog(title, choices) {
return new Promise((resolve) => {
const overlay = document.createElement("div");
overlay.className = "pm-hub-overlay";
const dialog = document.createElement("div");
dialog.className = "pm-hub-dialog pm-hub-dialog-small";
const header = document.createElement("div");
header.className = "pm-hub-dialog-header";
const heading = document.createElement("div");
heading.className = "pm-hub-dialog-title";
heading.textContent = title;
header.appendChild(heading);
const body = document.createElement("div");
body.className = "pm-hub-dialog-list";
const finish = (value) => {
overlay.remove();
resolve(value);
};
for (const choice of choices) {
const option = document.createElement("button");
option.type = "button";
option.className = "pm-hub-pick";
const name = document.createElement("div");
name.className = "pm-hub-pick-name";
name.textContent = choice.label;
const description = document.createElement("div");
description.className = "pm-hub-muted";
description.textContent = choice.description;
option.append(name, description);
option.onclick = () => finish(choice.value);
body.appendChild(option);
}
const footer = document.createElement("div");
footer.className = "pm-hub-dialog-footer";
const cancelButton = makeButton("Cancel");
cancelButton.style.marginLeft = "auto";
cancelButton.onclick = () => finish(null);
footer.appendChild(cancelButton);
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
dialog.append(header, body, footer);
overlay.appendChild(dialog);
document.body.appendChild(overlay);
});
}
async function importLibrary(library) {
if (library.store === "manager") {
await importJsonFile(library, false);
return;
}
const choices = [
{ value: "merge", label: "Merge a file", description: "Add the file's entries; you choose what happens to entries that already exist." },
{ value: "replace", label: "Replace with a file", description: `Replace all ${library.title} with the file's contents.` },
];
if (library.store === "generator") {
choices.push({ value: "defaults", label: "Restore built-in defaults", description: "Add back missing built-in system prompts without touching yours." });
}
const action = await showChoiceDialog(`Import ${library.title}`, choices);
if (!action) return;
if (action === "defaults") {
await restoreDefaultSystemPrompts();
} else if (library.store === "composer") {
await loadComposerPrompts(hosts.composer);
await (action === "replace" ? openComposerJsonLibrary : mergeComposerJsonLibrary)(hosts.composer);
} else {
await importJsonFile(library, action === "replace");
}
}
async function importJsonFile(library, replace) {
const picked = await readLibraryFile();
if (!picked) return;
if (replace) {
const confirmed = await showConfirm(
`Replace ${library.title}`,
`Replace ALL ${library.title} with "${picked.file.name}"? This cannot be undone.`,
"Replace",
UI.accent,
);
if (!confirmed) return;
}
let mode = replace ? "replace" : "skip_existing";
if (!replace) {
const current = hosts[library.store].prompts;
let duplicates = 0;
for (const category of categoryNames(picked.data)) {
const existing = getCategoryPromptEntries(current?.[category], library.store);
for (const name of Object.keys(getCategoryPromptEntries(picked.data[category], library.store))) {
if (Object.prototype.hasOwnProperty.call(existing, name)) duplicates += 1;
}
}
if (duplicates) {
mode = await showComposerImportModeDialog({ duplicatePromptCount: duplicates });
if (mode === "cancel") return;
}
}
// Prompt Manager's file is shared by all saved kinds; entries keep their kind through their data blocks.
const endpointPrefix = library.store === "manager" ? PROMPT_ENDPOINT_PREFIX : STORE_ENDPOINTS[library.store];
const response = await api.fetchApi(`${endpointPrefix}/import-prompts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: picked.data, mode }),
});
const result = await response.json();
if (!response.ok || !result?.success) throw new Error(result?.error || "Import failed.");
if (replace) {
await showInfo("Replace Complete", `${library.title} replaced with "${picked.file.name}".`);
return;
}
const imported = Number(result.imported_prompts || 0);
const skipped = Number(result.skipped_prompts || 0);
const created = Number(result.created_categories || 0);
const parts = [`Imported ${imported} entr${imported === 1 ? "y" : "ies"}`];
if (created) parts.push(`created ${created} categor${created === 1 ? "y" : "ies"}`);
if (skipped) parts.push(`kept ${skipped} existing entr${skipped === 1 ? "y" : "ies"}`);
await showInfo("Import Complete", `${parts.join(", ")}.`);
}
async function restoreDefaultSystemPrompts() {
const confirmed = await showConfirm(
"Restore Default System Prompts",
"This adds any missing built-in system prompts without overwriting your custom ones. Continue?",
"Restore",
UI.accent,
);
if (!confirmed) return;
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/reimport-default-prompts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const result = await response.json();
if (!response.ok || !result?.success) throw new Error(result?.error || "Failed to restore default system prompts.");
await showInfo("Restore Complete", "Added back any missing built-in system prompts.");
}
async function browseLibrary(library) {
const title = library.title;
if (library.store === "generator") {
await showThumbnailBrowser(hosts.generator, "", "", {
title,
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
loadPromptsFn: loadSystemPrompts,
promptOnly: true,
allowMultiSelect: false,
editMode: true,
});
} else if (library.store === "composer") {
await showThumbnailBrowser(hosts.composer, "", "", {
title,
endpointPrefix: COMPOSER_ENDPOINT_PREFIX,
loadPromptsFn: loadComposerPrompts,
preferenceScope: "composer",
promptOnly: true,
allowMultiSelect: false,
editMode: true,
});
} else {
await showThumbnailBrowser(hosts.manager, "", "", {
title,
loadPromptsFn: loadManagerPrompts,
contentFilter: "all",
filterEmptyCategories: true,
allowMultiSelect: false,
editMode: true,
});
}
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = `
.pm-hub { display: flex; flex-direction: column; gap: 12px; height: 100%; overflow: auto; padding: 12px;
box-sizing: border-box; color: ${UI.textPrimary}; font: 14px/1.4 sans-serif; }
.pm-hub-header { display: flex; align-items: center; gap: 8px; }
.pm-hub-title { font-size: 16px; font-weight: 700; color: ${UI.textHeading}; margin-right: auto; }
.pm-hub-muted { color: ${UI.textMuted}; font-size: 13px; }
.pm-hub-section { border: 1px solid ${UI.panelBorder}; border-radius: 8px; background: ${UI.panel}; padding: 12px;
display: flex; flex-direction: column; gap: 10px; }
.pm-hub-section-head { display: flex; align-items: baseline; gap: 8px; }
.pm-hub-name { font-size: 15px; font-weight: 700; color: ${UI.textHeading}; }
.pm-hub-count { margin-left: auto; color: ${UI.textHint}; font-size: 13px; white-space: nowrap; }
.pm-hub-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
.pm-hub-btn { padding: 6px 10px; border-radius: 6px; border: 1px solid ${UI.inputBorder}; background: ${UI.buttonBg};
color: ${UI.textPrimary}; font: inherit; font-size: 13px; cursor: pointer; white-space: nowrap; }
.pm-hub-btn:hover:not(:disabled) { border-color: ${UI.accentBorder}; }
.pm-hub-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.pm-hub-btn-primary { border-color: ${UI.accentBorder}; background: hsl(208 73% 57% / 0.2); color: #dbeafe; }
.pm-hub-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.72); z-index: 9999; display: flex;
align-items: center; justify-content: center; }
.pm-hub-dialog { width: min(860px, calc(100vw - 48px)); max-height: min(760px, calc(100vh - 48px)); background: ${UI.panel};
border: 1px solid ${UI.panelBorder}; border-radius: 10px; box-shadow: 0 10px 32px rgba(0, 0, 0, 0.45);
color: ${UI.textPrimary}; display: flex; flex-direction: column; overflow: hidden; font: 14px/1.4 sans-serif; }
.pm-hub-dialog-small { width: min(480px, calc(100vw - 48px)); }
.pm-hub-dialog-header { padding: 16px 18px 10px; border-bottom: 1px solid ${UI.sectionBorder}; }
.pm-hub-dialog-title { font-size: 16px; font-weight: 700; margin-bottom: 6px; }
.pm-hub-dialog-grid { padding: 16px 18px; overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
.pm-hub-dialog-list { padding: 16px 18px; overflow: auto; display: flex; flex-direction: column; gap: 10px; }
.pm-hub-dialog-footer { padding: 12px 18px 18px; border-top: 1px solid ${UI.sectionBorder}; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.pm-hub-pick { text-align: left; min-height: 64px; border: 1px solid ${UI.inputBorder}; border-radius: 10px; background: ${UI.cardBg};
color: ${UI.textPrimary}; padding: 12px; cursor: pointer; display: flex; flex-direction: column; gap: 6px; font: inherit; }
.pm-hub-pick:hover { border-color: ${UI.accentBorder}; }
.pm-hub-pick.active { background: hsl(208 73% 57% / 0.16); border-color: ${UI.accentBorder}; }
.pm-hub-pick-name { font-size: 15px; font-weight: 700; word-break: break-word; }
`;
document.head.appendChild(style);
}
function renderHub(container) {
ensureStyle();
container.replaceChildren();
const root = document.createElement("div");
root.className = "pm-hub";
container.appendChild(root);
const header = document.createElement("div");
header.className = "pm-hub-header";
const title = document.createElement("div");
title.className = "pm-hub-title";
title.textContent = HUB_TITLE;
const refreshButton = makeButton("Refresh", { title: "Reload all libraries" });
header.append(title, refreshButton);
const status = document.createElement("div");
status.className = "pm-hub-muted";
root.append(header);
let busy = false;
const updaters = [];
const update = () => updaters.forEach((fn) => fn());
const refresh = async () => {
status.textContent = "Loading libraries…";
const results = await Promise.allSettled([
loadManagerPrompts(hosts.manager),
loadComposerPrompts(hosts.composer),
loadSystemPrompts(hosts.generator),
]);
const failed = results.filter((result) => result.status === "rejected");
failed.forEach((result) => console.error("[PromptLibraryHub]", result.reason));
status.textContent = failed.length ? "Some libraries could not be loaded; see the console." : "";
update();
};
const run = async (task) => {
if (busy) return;
busy = true;
try {
await task();
} catch (error) {
console.error("[PromptLibraryHub]", error);
await showInfo(HUB_TITLE, error?.message || String(error));
} finally {
busy = false;
await refresh();
}
};
for (const section of SECTIONS) {
const card = document.createElement("div");
card.className = "pm-hub-section";
const head = document.createElement("div");
head.className = "pm-hub-section-head";
const name = document.createElement("div");
name.className = "pm-hub-name";
name.textContent = section.title;
const count = document.createElement("div");
count.className = "pm-hub-count";
head.append(name, count);
const hint = document.createElement("div");
hint.className = "pm-hub-muted";
hint.textContent = section.hint;
card.append(head, hint);
const library = libraryFor(section);
const actions = document.createElement("div");
actions.className = "pm-hub-actions";
const browse = makeButton("Browse & Edit", { primary: true });
browse.onclick = () => run(() => browseLibrary(library));
const importButton = makeButton("Import");
importButton.onclick = () => run(() => importLibrary(library));
const exportButton = makeButton("Export");
exportButton.onclick = () => run(() => exportLibrary(library));
actions.append(browse, importButton, exportButton);
card.appendChild(actions);
browse.title = `Open ${library.title} in the Prompt Browser with editing on`;
importButton.title = section.store === "manager"
? "Merge a JSON file into Saved Prompts (entries keep their own type)"
: `Merge or replace ${library.title} from a file`;
exportButton.title = section.store === "composer" ? "Export selected prompt groups as a ZIP" : "Export selected categories as JSON";
updaters.push(() => {
const { entries, categories, groups } = summarize(library);
const parts = [plural(entries, library.unit), `${categories} categor${categories === 1 ? "y" : "ies"}`];
if (groups) parts.push(`${groups} group${groups === 1 ? "" : "s"}`);
count.textContent = parts.join(" · ");
});
root.appendChild(card);
}
root.appendChild(status);
refreshButton.onclick = () => run(async () => {});
update();
refresh();
}
const SHOW_SIDEBAR_SETTING = "PromptManager.LibraryHub.ShowSidebar";
const SIDEBAR_TAB_ID = "prompt-library-hub";
let sidebarTabRegistered = false;
function syncSidebarTab(show) {
const manager = app.extensionManager;
if (show && !sidebarTabRegistered && manager?.registerSidebarTab) {
manager.registerSidebarTab({
id: SIDEBAR_TAB_ID,
icon: "pi pi-book",
title: HUB_TITLE,
tooltip: HUB_TITLE,
label: "Prompts",
type: "custom",
render: (container) => renderHub(container),
});
sidebarTabRegistered = true;
} else if (!show && sidebarTabRegistered && manager?.unregisterSidebarTab) {
manager.unregisterSidebarTab(SIDEBAR_TAB_ID);
sidebarTabRegistered = false;
}
}
app.registerExtension({
name: "PromptManager.LibraryHub",
settings: [
{
id: SHOW_SIDEBAR_SETTING,
category: ["Prompt Manager", "4. Advanced Preferences", "Show Prompts Sidebar Button"],
name: "Show the Prompts button (Prompt Library Hub) in the sidebar",
tooltip: "Adds a Prompts button to ComfyUI's left sidebar that opens the Prompt Library Hub.",
type: "boolean",
defaultValue: true,
onChange: (value) => syncSidebarTab(value !== false),
},
],
setup() {
const value = app.extensionManager?.setting?.get?.(SHOW_SIDEBAR_SETTING)
?? app.ui?.settings?.getSettingValue?.(SHOW_SIDEBAR_SETTING);
syncSidebarTab(value !== false);
},
});
+259 -144
View File
@@ -1,41 +1,136 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
import { api } from "../../scripts/api.js";
import { setPromptTextLocked } from "./prompt_text_lock.js";
let promptInputMaskPatched = false;
const AUTO_SELECT_MODEL_OPTION = "Default (auto-select)";
const preferredModelSettingOptions = [AUTO_SELECT_MODEL_OPTION];
const preferredModelBaseTooltip = "Select the preferred model for all modes (text and vision). Leave blank to auto-select.";
function normalizePreferredModelSettingValue(value) {
return value === AUTO_SELECT_MODEL_OPTION || value == null ? "" : String(value);
}
function updatePreferredModelSettingDefinition(definition, models, tooltip) {
preferredModelSettingOptions.splice(0, preferredModelSettingOptions.length, AUTO_SELECT_MODEL_OPTION, ...models);
definition.options = preferredModelSettingOptions;
definition.tooltip = tooltip || preferredModelBaseTooltip;
const registeredDefinition = app?.ui?.settings?.settingsLookup?.[definition.id];
if (registeredDefinition) {
registeredDefinition.options = preferredModelSettingOptions;
registeredDefinition.tooltip = definition.tooltip;
}
const currentValue = app?.ui?.settings?.getSettingValue?.(definition.id);
if (currentValue === "") {
app.ui.settings.setSettingValue(definition.id, AUTO_SELECT_MODEL_OPTION);
}
}
async function refreshPreferredModelOptions(definition) {
try {
const response = await api.fetchApi("/prompt-manager/available-models");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const models = Array.isArray(data?.models)
? data.models.filter(model => typeof model === "string" && model.trim())
: [];
const tooltipParts = [preferredModelBaseTooltip];
const status = typeof data?.status === "string" ? data.status.trim() : "";
if (status && !status.toLowerCase().startsWith("error:")) {
tooltipParts.push(status);
}
updatePreferredModelSettingDefinition(definition, models, tooltipParts.join("\n"));
} catch (error) {
console.error("[PromptManager] Error loading preferred model options:", error);
updatePreferredModelSettingDefinition(definition, [], preferredModelBaseTooltip);
}
}
function isTruthyInputFlag(value) {
return value === true || value === 1 || value === "1" || value === "true";
}
function attachPromptInputMaskShim() {
if (promptInputMaskPatched) return;
if (!app || typeof app.graphToPrompt !== "function") return;
promptInputMaskPatched = true;
const originalGraphToPrompt = app.graphToPrompt.bind(app);
app.graphToPrompt = async function (...args) {
const result = await originalGraphToPrompt(...args);
const promptData = result && typeof result === "object"
? (result.output && typeof result.output === "object"
? result.output
: (result.prompt && typeof result.prompt === "object" ? result.prompt : null))
: null;
if (!promptData) return result;
for (const nodeId of Object.keys(promptData)) {
const nodePayload = promptData[nodeId];
if (!nodePayload || typeof nodePayload !== "object") continue;
const classType = String(nodePayload.class_type || nodePayload.type || "");
if (classType !== "PromptManager") continue;
const inputs = nodePayload.inputs;
if (!inputs || typeof inputs !== "object") continue;
const useExternal = isTruthyInputFlag(inputs.use_external);
if (!useExternal && Object.prototype.hasOwnProperty.call(inputs, "llm_input")) {
delete inputs.llm_input;
}
}
return result;
};
}
const preferredModelSetting = {
id: "PromptManager.PreferredModel",
category: ["Prompt Manager", "1. Model Preferences", "Preferred Model"],
name: "Preferred Model",
tooltip: preferredModelBaseTooltip,
type: "combo",
options: preferredModelSettingOptions,
defaultValue: AUTO_SELECT_MODEL_OPTION,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_model", value: normalizePreferredModelSettingValue(value) })
}).catch(error => {
console.error("[PromptManager] Error saving preferred model preference:", error);
});
}
};
app.registerExtension({
name: "PromptManager",
settings: [
preferredModelSetting,
{
id: "PromptManager.PreferredBaseModel",
category: ["Prompt Manager", "1. Model Preferences", "Base Model (text enhancement)"],
name: "Preferred Base Model",
tooltip: "Filename of default model for 'Enhance User Prompt' mode (leave empty to auto-select model)",
type: "text",
defaultValue: "",
id: "PromptManager.HideDownloadableModels",
category: ["Prompt Manager", "1. Model Preferences", "Hide Downloadable Models"],
name: "Hide downloadable built-in models",
tooltip: "When enabled, Prompt Generator dropdowns only show locally available models instead of also listing the built-in HuggingFace download options.",
type: "boolean",
defaultValue: false,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving base model preference:", error);
});
}
},
{
id: "PromptManager.PreferredVisionModel",
category: ["Prompt Manager", "1. Model Preferences", "Vision Model (image analysis)"],
name: "Preferred Vision Model",
tooltip: "Filename of default model for 'Analyze Image' modes (leave empty to auto-select model)",
type: "text",
defaultValue: "",
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving vision model preference:", error);
body: JSON.stringify({ key: "hide_downloadable_models", value: value })
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving hide-downloadable-models preference:", error);
});
}
},
@@ -68,7 +163,7 @@ app.registerExtension({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "custom_llama_model_path", value: value })
}).catch(error => {
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving Model path preference:", error);
});
}
@@ -123,14 +218,55 @@ app.registerExtension({
type: "boolean",
defaultValue: true
},
{
id: "PromptManager.DefaultViewMode",
category: ["Prompt Manager", "4. Advanced Preferences", "Prompt Browser View Mode"],
name: "Default prompt browser view mode",
tooltip: "Choose the default display mode for the prompt browser: thumbnails grid or compact list view.",
type: "combo",
options: ["thumbnails", "list"],
defaultValue: "thumbnails"
id: "PromptManager.EnableThumbnailPreview",
category: ["Prompt Manager", "4. Advanced Preferences", "Enable Thumbnail Hover Preview"],
name: "Enable thumbnail hover preview",
tooltip: "When enabled, hovering over thumbnails in the prompt browser shows a larger preview after a short delay.",
type: "boolean",
defaultValue: false
},
{
id: "PromptManager.CompactPromptBrowser",
category: ["Prompt Manager", "4. Advanced Preferences", "Compact Prompt Browser"],
name: "Use compact prompt browser",
tooltip: "When enabled, the prompt browser dialog uses the smaller legacy size. When disabled (default), it is enlarged to show more thumbnails.",
type: "boolean",
defaultValue: false
},
{
id: "PromptManager.ThumbnailCheckpoint",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Checkpoint"],
name: "Checkpoint for thumbnail generation",
tooltip: "The checkpoint model used when generating thumbnails via right-click menu. Can also be changed from the prompt context menu.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailRenderSteps",
category: ["Prompt Manager", "4. Advanced Preferences", "Thumbnail Generation Steps"],
name: "Thumbnail generation steps (per family overrides)",
tooltip: "JSON map of model family -> step count used for thumbnail generation, e.g. {\"sdxl\": 12}. Set from the gear icon in the prompt browser (Steps row). Leave empty to use the hardcoded per-family defaults, or use the Reset button in the picker to revert a family.",
type: "text",
defaultValue: ""
},
{
id: "PromptManager.ThumbnailComposerSeed",
category: ["Prompt Manager", "4. Advanced Preferences", "Composer Thumbnail Seed"],
name: "Static seed for Prompt Composer thumbnail generation",
tooltip: "Seed used by Thumbnail Generator for Prompt Composer Manager categories. Set to 0 to use random seeds instead.",
type: "number",
defaultValue: 42,
onChange(value) {
fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "thumbnail_composer_seed", value: value })
}).catch(error => {
console.error("[PromptManager] Error saving composer thumbnail seed preference:", error);
});
}
},
{
id: "PromptManager.LLMBackend",
@@ -145,7 +281,7 @@ app.registerExtension({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "llm_backend", value: value })
}).catch(error => {
}).then(() => refreshPreferredModelOptions(preferredModelSetting)).catch(error => {
console.error("[PromptManager] Error saving LLM backend preference:", error);
});
}
@@ -189,8 +325,8 @@ app.registerExtension({
// Load settings from ComfyUI and sync to Python cache
try {
// Sync current values to Python cache first
const baseModel = app.ui.settings.getSettingValue("PromptManager.PreferredBaseModel");
const visionModel = app.ui.settings.getSettingValue("PromptManager.PreferredVisionModel");
const preferredModel = normalizePreferredModelSettingValue(app.ui.settings.getSettingValue("PromptManager.PreferredModel"));
const hideDownloadableModels = app.ui.settings.getSettingValue("PromptManager.HideDownloadableModels");
const llamaPath = app.ui.settings.getSettingValue("PromptManager.LlamaPath");
const modelPath = app.ui.settings.getSettingValue("PromptManager.ModelPath");
const port = app.ui.settings.getSettingValue("PromptManager.Port");
@@ -199,16 +335,16 @@ app.registerExtension({
const ollamaUrl = app.ui.settings.getSettingValue("PromptManager.OllamaUrl");
const ollamaKeepAlive = app.ui.settings.getSettingValue("PromptManager.OllamaKeepAlive");
console.log("[PromptManager] Syncing preferences:", { baseModel, visionModel, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
console.log("[PromptManager] Syncing preferences:", { preferredModel, hideDownloadableModels, llamaPath, modelPath, port, CloseLlama, llmBackend, ollamaUrl, ollamaKeepAlive });
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_base_model", value: baseModel })
body: JSON.stringify({ key: "preferred_model", value: preferredModel })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "preferred_vision_model", value: visionModel })
body: JSON.stringify({ key: "hide_downloadable_models", value: hideDownloadableModels === true })
});
await fetch("/prompt-manager/save-preference", {
method: "POST",
@@ -245,12 +381,15 @@ app.registerExtension({
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "ollama_keep_alive", value: ollamaKeepAlive })
});
await refreshPreferredModelOptions(preferredModelSetting);
} catch (error) {
console.error("[PromptManager] Error syncing preferences:", error);
await refreshPreferredModelOptions(preferredModelSetting);
}
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "PromptManager") {
attachPromptInputMaskShim();
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
@@ -278,15 +417,9 @@ app.registerExtension({
useExternalWidget.label = "use llm input";
}
// Make text widget scrollable even when disabled
// Make text widget scrollable even when read-only
if (promptTextWidget && promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
promptTextWidget.inputEl.addEventListener("mousedown", function(e) {
if (this.disabled) {
// Allow scrolling but prevent editing
e.stopPropagation();
}
});
}
// Listen for text updates from backend (when connected inputs change or toggle changes)
@@ -297,16 +430,11 @@ app.registerExtension({
const llmInput = event.detail.llm_input || "";
if (useExternal && llmInput) {
// When using external, display the LLM input text (grayed out)
// When using external, display the LLM input text (read-only, ghosted)
promptTextWidget.value = llmInput;
promptTextWidget.disabled = true;
// Keep scrolling enabled
if (promptTextWidget.inputEl) {
promptTextWidget.inputEl.style.pointerEvents = "auto";
}
setPromptTextLocked(promptTextWidget, true);
} else {
// When using internal, enable the widget
promptTextWidget.disabled = false;
setPromptTextLocked(promptTextWidget, false);
}
this.serialize_widgets = true;
@@ -323,7 +451,7 @@ app.registerExtension({
// Load prompts asynchronously (data only, not widgets)
loadPrompts(node).then(() => {
filterPromptDropdown(node);
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Ensure height is sufficient after data is loaded
setTimeout(() => {
@@ -346,17 +474,24 @@ app.registerExtension({
const result = onConfigure?.apply(this, arguments);
const node = this;
// Mark workflow restore so async onNodeCreated load does not coerce selection.
node._configuredFromWorkflow = true;
node._restoringFromWorkflow = true;
// Reload prompts from server and reapply filtering
setTimeout(() => {
loadPrompts(node).then(() => {
filterPromptDropdown(node);
try {
filterPromptDropdown(node, { preserveDanglingSelection: true });
// Reattach button bar if needed
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
// Reattach button bar if needed
if (!node.buttonBarAttached) {
addButtonBar(node);
setupCategoryChangeHandler(node);
setupUseExternalToggleHandler(node);
}
} finally {
node._restoringFromWorkflow = false;
}
});
}, 100);
@@ -419,46 +554,6 @@ app.registerExtension({
};
}
// Make the Options node taller/wider by default so the system_prompt area is roomier
if (nodeData.name === "PromptGenOptions") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 420]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
// Enforce sensible minimums when the user resizes the options node
const onResizeOpt = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
};
}
// Enforce minimum size for ModelGenerator node (no default size)
if (nodeData.name === "PromptGenerator") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Set a default size (width x height)
try {
this.setSize([400, 300]);
} catch (e) {
// ignore if method unavailable
}
return result;
};
const onResizeModel = nodeType.prototype.onResize;
nodeType.prototype.onResize = function(size) {
size[0] = Math.max(300, size[0]);
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
};
}
}
});
@@ -507,7 +602,8 @@ function hasUnsavedChanges(node) {
return currentText !== savedText;
}
function filterPromptDropdown(node) {
function filterPromptDropdown(node, options = {}) {
const preserveDanglingSelection = options?.preserveDanglingSelection === true;
// Filter name dropdown to only show prompts from current category
const categoryWidget = node.widgets.find(w => w.name === "category");
const promptWidget = node.widgets.find(w => w.name === "name");
@@ -516,13 +612,23 @@ function filterPromptDropdown(node) {
const hideNSFW = app.ui.settings.getSettingValue("PromptManager.DefaultHideNSFW");
// Filter NSFW categories from the category dropdown
if (hideNSFW && node.prompts) {
if (node.prompts) {
let categories = Object.keys(node.prompts).sort((a, b) => a.localeCompare(b));
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
categoryWidget.options.values = categories.length > 0 ? categories : ["Default"];
const currentCategoryValue = String(categoryWidget.value || "");
// If current category is now hidden, switch to first visible
if (!categories.includes(categoryWidget.value) && categories.length > 0) {
if (hideNSFW) {
categories = categories.filter(cat => node.prompts[cat]?.["__meta__"]?.nsfw !== true);
}
let categoryOptions = categories.length > 0 ? [...categories] : ["Default"];
if (preserveDanglingSelection && currentCategoryValue && !categoryOptions.includes(currentCategoryValue)) {
categoryOptions = [currentCategoryValue, ...categoryOptions];
}
categoryWidget.options.values = categoryOptions;
// If current category is now hidden, switch only when we are not preserving
// workflow-restored dangling selections.
if (!categoryOptions.includes(categoryWidget.value) && categories.length > 0) {
categoryWidget.value = categories[0];
}
}
@@ -538,6 +644,10 @@ function filterPromptDropdown(node) {
promptNames = promptNames.filter(name => !node.prompts[currentCategory][name]?.nsfw);
}
}
const currentPromptValue = String(promptWidget.value || "");
if (preserveDanglingSelection && currentPromptValue && !promptNames.includes(currentPromptValue)) {
promptNames = [currentPromptValue, ...promptNames];
}
if (promptNames.length === 0) {
promptNames.push("");
}
@@ -628,7 +738,7 @@ function addButtonBar(node) {
const newPromptBtn = createButton("New Prompt", async () => {
// Check for unsaved changes before creating new prompt
const hasUnsaved = hasUnsavedChanges(node);
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.warnUnsavedChanges");
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.WarnUnsavedChanges");
if (hasUnsaved && warnEnabled) {
const confirmed = await showConfirm(
@@ -717,7 +827,13 @@ function addButtonBar(node) {
{
label: "Import JSON",
action: async () => {
await importPromptsJSON(node);
await importPromptsJSON(node, "merge");
}
},
{
label: "Replace JSON",
action: async () => {
await importPromptsJSON(node, "replace");
}
}
]);
@@ -734,6 +850,8 @@ function addButtonBar(node) {
htmlWidget.computeSize = function(width) {
return [width, 36];
};
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
htmlWidget.computeLayoutSize = undefined;
node.buttonBarAttached = true;
}
@@ -750,6 +868,13 @@ function setupCategoryChangeHandler(node) {
// Update prompt dropdown when category changes
categoryWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalCallback) {
originalCallback.apply(this, arguments);
}
return;
}
if (originalCallback) {
originalCallback.apply(this, arguments);
}
@@ -766,10 +891,10 @@ function setupCategoryChangeHandler(node) {
}
promptWidget.options.values = promptNames;
// Only update the text widget if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (promptNames.length > 0) {
promptWidget.value = promptNames[0];
// Only update text widget if not using external
const useExternal = useExternalWidget ? useExternalWidget.value : false;
if (!useExternal) {
const promptData = node.prompts[category][promptNames[0]];
textWidget.value = promptData?.prompt || "";
@@ -790,6 +915,13 @@ function setupCategoryChangeHandler(node) {
// Update text widget when prompt selection changes
promptWidget.callback = async function(value) {
if (node._restoringFromWorkflow) {
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
return;
}
if (originalPromptCallback) {
originalPromptCallback.apply(this, arguments);
}
@@ -848,7 +980,7 @@ function setupCategoryChangeHandler(node) {
if (hasOtherCategoryPrompts) {
setTimeout(() => {
filterPromptDropdown(node);
filterPromptDropdown(node, { preserveDanglingSelection: node._restoringFromWorkflow === true });
}, 50);
}
}
@@ -875,13 +1007,8 @@ function setupUseExternalToggleHandler(node) {
const isLlmConnected = llmInputConnection && llmInputConnection.link != null;
if (value && isLlmConnected) {
// Using LLM and it's connected - disable text widget immediately
textWidget.disabled = true;
// Keep scrolling enabled but prevent editing
if (textWidget.inputEl) {
textWidget.inputEl.style.pointerEvents = "auto";
textWidget.inputEl.readOnly = true;
}
// Using LLM and it's connected - make text widget read-only (ghosted)
setPromptTextLocked(textWidget, true);
// Try to show LLM value if available
const graph = app.graph;
@@ -904,10 +1031,7 @@ function setupUseExternalToggleHandler(node) {
}
} else {
// Using internal text - enable widget but keep current text (which may be LLM output)
textWidget.disabled = false;
if (textWidget.inputEl) {
textWidget.inputEl.readOnly = false;
}
setPromptTextLocked(textWidget, false);
}
};
@@ -951,7 +1075,7 @@ function createButton(text, callback) {
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "11px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.overflow = "hidden";
@@ -982,7 +1106,7 @@ function createDropdownButton(text, items) {
button.style.color = "#fff";
button.style.border = "1px solid #444";
button.style.borderRadius = "6px";
button.style.fontSize = "11px";
button.style.fontSize = "13px";
button.style.fontWeight = "normal";
button.style.whiteSpace = "nowrap";
button.style.height = "28px";
@@ -1015,7 +1139,7 @@ function createDropdownButton(text, items) {
menuItem.style.cssText = `
padding: 8px 12px;
cursor: pointer;
font-size: 11px;
font-size: 13px;
color: #fff;
white-space: nowrap;
`;
@@ -1095,12 +1219,12 @@ function showPromptWithCategory(title, message, defaultName, categories, default
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px;">
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">Category:</div>
<select style="width: 100%; padding: 8px; margin-bottom: 12px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;">
${categoryOptions}
</select>
<div style="margin-bottom: 6px; color: #aaa; font-size: 12px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px; box-sizing: border-box;" />
<div style="margin-bottom: 6px; color: #aaa; font-size: 14px;">${message}</div>
<input type="text" value="${defaultName}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px; box-sizing: border-box;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
@@ -1212,7 +1336,7 @@ async function exportPromptsJSON(node) {
}
}
async function importPromptsJSON(node) {
async function importPromptsJSON(node, importMode = "merge") {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
@@ -1236,15 +1360,6 @@ async function importPromptsJSON(node) {
return;
}
// Ask user how to handle import
const importMode = await showImportOptions();
if (importMode === null) {
// User cancelled
resolve(false);
return;
}
// Send to backend
const response = await fetch("/prompt-manager/import-prompts", {
method: "POST",
@@ -1277,10 +1392,10 @@ async function importPromptsJSON(node) {
node.serialize_widgets = true;
app.graph.setDirtyCanvas(true, true);
await showInfo("Import Complete", `Successfully imported prompts!`);
await showInfo(importMode === "replace" ? "Replace Complete" : "Import Complete", importMode === "replace" ? "Successfully replaced prompts!" : "Successfully imported prompts!");
resolve(true);
} else {
await showInfo("Error", result.error || "Failed to import prompts");
await showInfo("Error", result.error || (importMode === "replace" ? "Failed to replace prompts" : "Failed to import prompts"));
resolve(false);
}
} catch (error) {
@@ -1401,7 +1516,7 @@ function showTextPrompt(title, message, defaultValue = "") {
dialog.innerHTML = `
<div style="margin-bottom: 15px; font-size: 16px; font-weight: bold; color: #fff;">${title}</div>
<div style="margin-bottom: 10px; color: #ccc;">${message}</div>
<input type="text" value="${defaultValue}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 14px;" />
<input type="text" value="${defaultValue}" style="width: 100%; padding: 8px; margin-bottom: 15px; background: #333; border: 1px solid #555; color: #fff; border-radius: 4px; font-size: 16px;" />
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button class="cancel-btn" style="padding: 8px 16px; background: #555; color: #fff; border: none; border-radius: 4px; cursor: pointer;">Cancel</button>
<button class="ok-btn" style="padding: 8px 16px; background: #0a0; color: #fff; border: none; border-radius: 4px; cursor: pointer;">OK</button>
+5985 -2012
View File
File diff suppressed because it is too large Load Diff
+753
View File
@@ -0,0 +1,753 @@
/**
* Prompt Manager (PromptManagerV2): a saved prompt with its LoRA stacks and
* trigger words, on one fbui card with the legacy node's look: the prompt
* bar, Save / New / More, a stack card per slot in use and the trigger words.
*
* The stock widgets stay hidden and hold the saved values: category, name,
* use_prompt_input, lora_mode, text, and state, the node's edits
* {loras: {slot: {name: {active, strength, removed}}}, order: {slot: [name]},
* trigger_words: {text: {active, removed}}} (names in lower case). Before a
* run the cards show the saved prompt's LoRAs; after one, the rows the node
* ran with (its UI output, see nodes/prompt_manager_v2.py), connected LoRAs
* included; those rows are kept in the node's properties, so a loaded
* workflow shows them too.
*/
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { mountCard } from "./fbui/card.js";
import { notifyChange, toast } from "./fbui/comfy.js";
import { button, helpBadge } from "./fbui/controls.js";
import { chainCallback, el } from "./fbui/dom.js";
import { confirm, openMenu } from "./fbui/modal.js";
import { FONT } from "./fbui/theme.js";
import { findWidget, hideInputsInDef, hideWidget } from "./fbui/widgets.js";
import { DEFAULT_THUMBNAIL, exportPromptsJSON, getLoraManagerPreviewTooltip, PMA_THEME } from "./prompt_manager_advanced.js";
import { getHideNSFW, hasComposeLikePayload, hasLayoutPayload, hasRecipeLikePayload, openPromptBrowserForSave, showThumbnailBrowser } from "./prompt_browser.js";
import { buildSavePromptRequestBodyForEndpoint, isHiddenPromptEntryKey, PROMPT_ADVANCED_ENDPOINT_PREFIX as ENDPOINT } from "./prompt_store_adapters.js";
const NODE_NAME = "PromptManagerV2";
const SLOTS = ["a", "b", "c", "d"];
const MODE_LABELS = { "Prompt LoRAs Only": "Prompt only", "Combine LoRAs": "Combine", "Input LoRAs Only": "Input only" };
const MODE_TITLES = {
"Prompt LoRAs Only": "The saved prompt's LoRAs only.",
"Combine LoRAs": "The saved prompt's LoRAs, then the connected ones.",
"Input LoRAs Only": "The connected LoRAs only.",
};
const PROMPT_ONLY = "Prompt LoRAs Only";
const INPUT_ONLY = "Input LoRAs Only";
const MIN_WIDTH = 460;
const TEXT_MIN_HEIGHT = 90;
const BAR_HEIGHT = 26;
const BUTTONS_HEIGHT = 28;
// A stack card's padding and title bar, then one 24px line of tags per 28px.
const STACK_HEAD = 50;
const CSS_ID = "pm-v2-css-v2";
// The last run's panel rows, saved with the workflow.
const RUN_PROPERTY = "pm_last_run";
const GUIDE = [
"Pick a prompt with ◀ ▶ or click its name to browse the library.",
"LoRA stacks in:",
["lora_stacks", "one LoRA stack: connect it here, it is stack A."],
["Multi LoRA Stack", "stacks A-D from one node: connect its output here."],
["Multi LoRA Relay", "several separate stacks: wire them into its lora_stack_a…d, and its lora_stacks out here."],
"LoRA stacks out: a plain LoRA stack when one stack has LoRAs, a multi LoRA stack when several do. A node that takes one plain stack (a LoRA loader) fails on a prompt with several; put Multi LoRA Relay in between and use its lora_stack_a…d.",
"Click a LoRA or trigger word to switch it off or on, its number to set the strength; right-click to move or delete it. Save Prompt keeps these edits with the prompt.",
];
function ensureCss() {
if (document.getElementById(CSS_ID)) return;
const style = document.createElement("style");
style.id = CSS_ID;
style.textContent = `
.pm-v2-bar{display:flex;align-items:center;width:100%;height:100%;background:#1a1a1a;border-radius:6px;pointer-events:auto}
.pm-v2-arrow{height:100%;padding:0 10px;border:none;background:#2a2a2a;color:#888;font-size:12px;cursor:pointer;transition:all .15s ease}
.pm-v2-arrow:first-child{border-radius:6px 0 0 6px}
.pm-v2-arrow:last-child{border-radius:0 6px 6px 0}
.pm-v2-arrow:hover{background:#3a3a3a;color:#fff}
.pm-v2-name{flex:1;min-width:0;height:100%;display:flex;align-items:center;justify-content:center;padding:0 10px;box-sizing:border-box;border:1px solid rgba(56,130,246,.85);border-radius:4px;background:rgba(56,130,246,.22);color:#dbeafe;font-size:15px;cursor:pointer;transition:background .15s ease}
.pm-v2-name:hover{background:rgba(56,130,246,.32)}
.pm-v2-name .label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pm-v2-badge{flex-shrink:0;margin-left:6px;color:#fff;font-weight:bold}
.pm-v2-badge.nsfw{padding:0 4px;border-radius:2px;background:rgba(204,50,50,.85);font-size:8px;line-height:12px}
.pm-v2-badge.kind{width:14px;height:14px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;font-size:9px;line-height:1}
.pm-v2-thumb{position:fixed;display:none;z-index:10001;pointer-events:none}
.pm-v2-thumb img{display:block;max-width:300px;max-height:300px;object-fit:contain;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.5)}
.pm-v2-buttons{display:flex;align-items:center;gap:2px;width:100%;height:100%;pointer-events:auto}
.pm-v2-btn{min-width:80px;height:28px;font:500 13px/1 ${FONT}}
.pm-v2-text.fbui-text{width:100%;height:100%;min-height:${TEXT_MIN_HEIGHT}px;padding:6px 8px;box-sizing:border-box;resize:none;pointer-events:auto}
.pm-v2-text[readonly]{opacity:.5}
.pm-v2-stack{display:flex;flex-direction:column;gap:4px;padding:8px;box-sizing:border-box;width:100%;border-radius:6px;background:${PMA_THEME.cardBg};pointer-events:auto}
.pm-v2-stack .head{display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;padding-bottom:4px;border-bottom:1px solid ${PMA_THEME.sectionBorder}}
.pm-v2-stack .title{color:${PMA_THEME.textMuted};font-size:14px;font-weight:bold}
.pm-v2-stack .tools{display:flex;gap:4px}
.pm-v2-mini{padding:2px 8px;border:1px solid ${PMA_THEME.inputBorder};border-radius:6px;background:${PMA_THEME.buttonBg};color:${PMA_THEME.textPrimary};font-size:12px;cursor:pointer}
.pm-v2-tags{display:flex;flex-wrap:wrap;gap:4px}
.pm-v2-tag{display:inline-flex;align-items:center;gap:6px;height:24px;padding:4px 10px;box-sizing:border-box;border:1px solid rgba(226,232,240,.2);border-radius:6px;background:rgba(45,55,72,.7);color:rgba(226,232,240,.6);font-size:14px;cursor:pointer;user-select:none;transition:background-color .15s ease,color .15s ease,border-color .15s ease}
.pm-v2-tag:hover{transform:translateY(-1px);box-shadow:0 2px 4px rgba(0,0,0,.2)}
.pm-v2-tag .name{flex-grow:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pm-v2-tag.lora{flex-shrink:0;width:min(200px,calc(50% - 2px))}
.pm-v2-tag.lora.on{background:rgba(66,153,225,.9);border-color:rgba(122,188,243,.9);color:#fff}
.pm-v2-tag.lora.input.on{background:rgba(50,112,163,.9);border-color:rgba(66,153,225,.9)}
.pm-v2-tag.lora.missing{background:rgba(220,53,69,.4);border-color:rgba(220,53,69,.9);color:rgba(255,200,200,.8)}
.pm-v2-tag.lora.missing.on{background:rgba(220,53,69,.9);color:#fff}
.pm-v2-tag.lora.missing .name{text-decoration:line-through;opacity:.8}
.pm-v2-tag .warn{margin-right:-2px;font-size:13px}
.pm-v2-strength{width:38px;padding:1px 4px;border:1px solid transparent;border-radius:999px;outline:none;background:rgba(255,255,255,.15);color:rgba(255,255,255,.9);font-size:12px;font-weight:600;text-align:center;cursor:text}
.pm-v2-strength:focus{border-color:rgba(66,153,225,.6);background:rgba(255,255,255,.25)}
.pm-v2-tag.word{justify-content:center;max-width:100%;white-space:nowrap;overflow:hidden}
.pm-v2-tag.word.on{background:rgba(72,187,120,.9);border-color:rgba(72,187,120,.9);color:#fff}
`;
document.head.append(style);
}
// ---------------------------------------------------------------- library
async function loadPrompts(node) {
const response = await api.fetchApi(`${ENDPOINT}/get-prompts`, { cache: "no-store" });
// The prompt browser reads the library from node.prompts too.
node.prompts = response.ok ? await response.json() : {};
return node.prompts;
}
const selection = (node) => ({ category: findWidget(node, "category")?.value || "", name: findWidget(node, "name")?.value || "" });
// A run's rows stand for the prompt and LoRA mode they were made with.
const runKey = (category, name, mode) => `${category}\u0000${name}\u0000${mode}`;
function currentKey(node) {
const { category, name } = selection(node);
return runKey(category, name, findWidget(node, "lora_mode")?.value);
}
function entryOf(node) {
const { category, name } = selection(node);
const entry = name ? node.prompts?.[category]?.[name] : null;
return entry && typeof entry === "object" ? entry : null;
}
function isNsfw(node, category, name) {
const entries = node.prompts?.[category];
return entries?.__meta__?.nsfw === true || entries?.[name]?.nsfw === true;
}
// Every prompt in library order, NSFW ones left out while they are hidden.
function allPrompts(node) {
const hide = getHideNSFW(app) === true;
const out = [];
for (const [category, entries] of Object.entries(node.prompts ?? {})) {
if (!entries || typeof entries !== "object" || isHiddenPromptEntryKey(category)) continue;
for (const name of Object.keys(entries)) {
if (isHiddenPromptEntryKey(name)) continue;
if (hide && isNsfw(node, category, name)) continue;
out.push({ category, name });
}
}
return out;
}
// ---------------------------------------------------------------- state
function readState(node) {
try {
const state = JSON.parse(findWidget(node, "state")?.value || "{}");
return state && typeof state === "object" ? state : {};
} catch {
return {};
}
}
function writeState(node, state) {
findWidget(node, "state").value = JSON.stringify(state);
node._pm.card.refresh();
notifyChange();
}
const hasEdits = (state) => ["loras", "order"].some((key) => Object.values(state[key] ?? {}).some((slot) => Object.keys(slot ?? {}).length)) || Object.keys(state.trigger_words ?? {}).length > 0;
// Rewrite one entry of an edits map; an empty entry is dropped.
function setEdit(map, key, change) {
const next = change({ ...(map[key] ?? {}) });
if (Object.keys(next).length) map[key] = next;
else delete map[key];
}
function editLoras(node, slot, changes) {
const state = readState(node);
state.loras ??= {};
state.loras[slot] ??= {};
for (const [name, change] of changes) setEdit(state.loras[slot], name.toLowerCase(), change);
writeState(node, state);
}
function editWords(node, changes) {
const state = readState(node);
state.trigger_words ??= {};
for (const [text, change] of changes) setEdit(state.trigger_words, text.toLowerCase(), change);
writeState(node, state);
}
// An on/off edit, dropped when it matches the row's own state.
const activeEdit = (row, active) => (edit) => {
if (active === (row.base_active ?? true)) delete edit.active;
else edit.active = active;
return edit;
};
// ---------------------------------------------------------------- rows
// The rows the node runs with: the last run's when it ran this prompt in
// this mode, else as nodes/prompt_manager_v2.py builds them, from the saved
// prompt's LoRAs and the last run's connected ones (those do not depend on
// the prompt), a connected LoRA of a saved one's name left out.
function baseLoras(node, slot) {
const pm = node._pm;
if (pm.run?.key === currentKey(node)) return pm.run.loras?.[slot] ?? [];
const mode = findWidget(node, "lora_mode")?.value;
const saved = mode === INPUT_ONLY ? [] : savedLoras(node, slot);
const connected = mode === PROMPT_ONLY ? [] : (pm.run?.loras?.[slot] ?? []).filter((row) => row.from_input);
const names = new Set(saved.map((row) => row.name.toLowerCase()));
return [...saved, ...connected.filter((row) => !names.has(row.name.toLowerCase()))];
}
function savedLoras(node, slot) {
return (entryOf(node)?.[`loras_${slot}`] ?? [])
.filter((lora) => lora && typeof lora === "object" && String(lora.name ?? "").trim())
.map((lora) => {
const strength = Number(lora.strength ?? lora.model_strength ?? 1);
return {
name: String(lora.name).trim(),
path: lora.path ?? lora.name,
strength,
clip_strength: Number(lora.clip_strength ?? strength),
base_strength: strength,
base_active: lora.active !== false,
available: node._pm.available.get(String(lora.name).trim().toLowerCase()) ?? true,
from_input: false,
};
});
}
// Rows as shown: the base with the node's edits, removed ones left out, in the node's order.
function loraRows(node, slot) {
const state = readState(node);
const edits = state.loras?.[slot] ?? {};
const order = state.order?.[slot] ?? [];
const at = (row) => (order.includes(row.name.toLowerCase()) ? order.indexOf(row.name.toLowerCase()) : order.length);
return baseLoras(node, slot)
.filter((row) => edits[row.name.toLowerCase()]?.removed !== true)
.map((row) => {
const edit = edits[row.name.toLowerCase()] ?? {};
const strength = typeof edit.strength === "number" ? edit.strength : row.base_strength ?? row.strength;
return { ...row, strength, active: edit.active ?? row.base_active ?? row.active };
})
.sort((a, b) => at(a) - at(b));
}
// Trigger words the same way: saved ones, then the last run's connected ones.
function baseWords(node) {
const pm = node._pm;
if (pm.run?.key === currentKey(node)) return pm.run.trigger_words ?? [];
const saved = (entryOf(node)?.trigger_words ?? []).map((word) => (typeof word === "string" ? { text: word, base_active: true } : { text: word?.text ?? "", base_active: word?.active !== false }));
const texts = new Set(saved.map((word) => String(word.text).toLowerCase()));
return [...saved, ...(pm.run?.trigger_words ?? []).filter((word) => word.from_input && !texts.has(word.text.toLowerCase()))];
}
function wordRows(node) {
const base = baseWords(node);
const edits = readState(node).trigger_words ?? {};
return base
.filter((word) => String(word.text ?? "").trim() && edits[word.text.toLowerCase()]?.removed !== true)
.map((word) => ({ ...word, active: edits[word.text.toLowerCase()]?.active ?? word.base_active ?? word.active }));
}
// Which saved LoRAs are found locally, asked once per prompt shown.
async function checkAvailability(node) {
const entry = entryOf(node);
const names = SLOTS.flatMap((slot) => (entry?.[`loras_${slot}`] ?? []).map((lora) => String(lora?.name ?? "").trim())).filter(Boolean);
if (!names.length) return;
const response = await api.fetchApi(`${ENDPOINT}/check-loras`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ lora_names: names }),
});
const result = response.ok ? await response.json() : null;
for (const [name, found] of Object.entries(result?.results ?? {})) node._pm.available.set(name.toLowerCase(), found === true);
node._pm.card.refresh();
}
// ---------------------------------------------------------------- selection
const isLinked = (node, name) => node.inputs?.find((input) => input.name === name)?.link != null;
function isDirty(node) {
const entry = entryOf(node);
const text = findWidget(node, "text")?.value ?? "";
return hasEdits(readState(node)) || (entry ? text !== (entry.prompt ?? "") : text.trim() !== "");
}
async function mayLeave(node) {
if (!isDirty(node) || app.ui.settings.getSettingValue("PromptManager.WarnUnsavedChanges") === false) return true;
return confirm({ title: "Unsaved changes", message: "The prompt's text or LoRA edits are not saved. Discard them and switch?", confirmText: "Discard & Switch" });
}
// Show a prompt: its saved text and no edits. The last run's rows no longer
// stand for it (even a prompt just saved may differ from what ran), but its
// connected LoRAs and trigger words still show.
function select(node, category, name) {
findWidget(node, "category").value = category;
findWidget(node, "name").value = name;
findWidget(node, "text").value = name ? node.prompts?.[category]?.[name]?.prompt ?? "" : "";
if (node._pm.run) node._pm.run.key = null;
writeState(node, {});
checkAvailability(node);
}
async function step(node, delta) {
const list = allPrompts(node);
if (!list.length || !(await mayLeave(node))) return;
const { category, name } = selection(node);
const at = list.findIndex((item) => item.category === category && item.name === name);
const next = list[(at + delta + list.length) % list.length] ?? list[0];
select(node, next.category, next.name);
}
async function browse(node) {
const { category, name } = selection(node);
const picked = await showThumbnailBrowser(node, category, name, { endpointPrefix: ENDPOINT, loadPromptsFn: loadPrompts, filterEmptyCategories: true, showAllCategoriesToggle: true });
if (!picked?.prompt || (picked.category === category && picked.prompt === name) || !(await mayLeave(node))) return;
select(node, picked.category, picked.prompt);
}
async function newPrompt(node) {
if (!(await mayLeave(node))) return;
select(node, selection(node).category, "");
}
async function deletePrompt(node) {
const { category, name } = selection(node);
if (!name || !(await confirm({ title: "Delete prompt", message: `Delete "${name}" from ${category}? This cannot be undone.`, confirmText: "Delete", danger: true }))) return;
const response = await api.fetchApi(`${ENDPOINT}/delete-prompt`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, name }),
});
const result = await response.json();
if (!result?.success) return toast(result?.error || "Could not delete the prompt.", { severity: "error" });
node.prompts = result.prompts;
select(node, category, "");
}
function importPrompts(node, mode) {
const input = el("input");
input.type = "file";
input.accept = ".json";
input.addEventListener("change", async () => {
const file = input.files?.[0];
if (!file) return;
let data;
try {
data = JSON.parse(await file.text());
} catch {
return toast(`${file.name} is not valid JSON.`, { severity: "error" });
}
if (mode === "replace" && !(await confirm({ title: "Replace prompts", message: `Replace the whole prompt library with ${file.name}?`, confirmText: "Replace", danger: true }))) return;
const response = await api.fetchApi(`${ENDPOINT}/import-prompts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data, mode }),
});
const result = await response.json();
if (!result?.success) return toast(result?.error || "Could not import the prompts.", { severity: "error" });
node.prompts = result.prompts;
node._pm.card.refresh();
toast(mode === "replace" ? "Prompts replaced." : "Prompts imported.");
});
input.click();
}
// Save through the library's save dialog, edits included; the saved prompt
// then carries them, so the node's edits are cleared.
async function savePrompt(node) {
const { category, name } = selection(node);
const entry = entryOf(node);
const initialName = name || "New Prompt";
const loras = Object.fromEntries(SLOTS.map((slot) => [`loras_${slot}`, loraRows(node, slot).map((row) => ({
name: row.name, path: row.path, strength: row.strength, clip_strength: row.clip_strength,
active: row.active, available: row.available, fromInput: row.from_input === true,
}))]));
const words = wordRows(node).map((word) => ({ text: word.text, active: word.active }));
await openPromptBrowserForSave({
node,
currentCategory: category,
currentPrompt: name,
title: "Save Prompt",
saveButtonText: "Save",
namePlaceholder: "Prompt name",
initialName,
saveWithEditPanel: true,
saveMode: true,
showNSFWOnOpen: Boolean(entry) && isNsfw(node, category, name),
saveDraft: { category, name: initialName, text: findWidget(node, "text").value || "", thumbnail: entry?.thumbnail || null, workflow_data: entry?.workflow_data || null, ...loras, trigger_words: words },
onSave: async ({ category: target, name: saveName, overwrite, text, thumbnail, ...edited }) => {
const promptName = String(saveName || "").trim();
const targetCategory = String(target || "").trim();
if (!promptName || !targetCategory) return { success: false, error: "Category and prompt name are required." };
const payload = { category: targetCategory, name: promptName, text: typeof text === "string" ? text : findWidget(node, "text").value || "", thumbnail };
for (const slot of SLOTS) payload[`loras_${slot}`] = Array.isArray(edited[`loras_${slot}`]) ? edited[`loras_${slot}`] : loras[`loras_${slot}`];
payload.trigger_words = Array.isArray(edited.trigger_words) ? edited.trigger_words : words;
const response = await api.fetchApi(`${ENDPOINT}/save-prompt`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildSavePromptRequestBodyForEndpoint(ENDPOINT, payload)),
});
const result = await response.json();
if (!result?.success) return { success: false, error: result?.error || "Could not save the prompt." };
node.prompts = result.prompts;
select(node, targetCategory, promptName);
return { success: true, category: targetCategory, name: promptName, overwritten: overwrite === true };
},
});
}
// ---------------------------------------------------------------- prompt bar
// The saved prompt's thumbnail at its own size above the bar, while hovered.
function thumbnailHover(node, target) {
const preview = el("div", "pm-v2-thumb");
const image = el("img");
preview.append(image);
document.body.append(preview);
chainCallback(node, "onRemoved", () => preview.remove());
let timer = null;
target.addEventListener("mouseenter", () => {
timer = setTimeout(() => {
const thumbnail = entryOf(node)?.thumbnail;
if (!thumbnail || thumbnail === DEFAULT_THUMBNAIL) return;
const probe = new Image();
probe.onload = () => {
image.src = thumbnail;
const width = Math.min(probe.naturalWidth, 300);
const height = Math.min(probe.naturalHeight, 300);
const box = target.getBoundingClientRect();
preview.style.left = `${Math.max(5, Math.min(box.left + box.width / 2 - width / 2, window.innerWidth - width - 5))}px`;
preview.style.top = `${Math.max(5, Math.min(box.top - height - 8, window.innerHeight - height - 5))}px`;
preview.style.display = "block";
};
probe.src = thumbnail;
}, 300);
});
target.addEventListener("mouseleave", () => {
clearTimeout(timer);
preview.style.display = "none";
});
}
function promptBar(node) {
ensureCss();
const bar = el("div", "pm-v2-bar");
const back = el("button", "pm-v2-arrow", "◀");
const label = el("span", "label");
const nsfw = el("span", "pm-v2-badge nsfw", "NSFW");
const kind = el("span", "pm-v2-badge kind");
const name = el("div", "pm-v2-name");
const next = el("button", "pm-v2-arrow", "▶");
back.title = "Previous prompt";
next.title = "Next prompt";
name.append(label, nsfw, kind);
bar.append(back, name, next);
back.addEventListener("click", () => step(node, -1));
next.addEventListener("click", () => step(node, 1));
name.addEventListener("click", () => browse(node));
bar.addEventListener("contextmenu", (event) => event.preventDefault());
thumbnailHover(node, name);
return {
element: bar,
sync() {
const { category, name: prompt } = selection(node);
label.textContent = `${category} : ${prompt || "new prompt"}`;
name.title = `${label.textContent}\nClick to browse the prompt library`;
const entry = entryOf(node);
nsfw.hidden = !prompt || !isNsfw(node, category, prompt);
// L, C or R: the entry also holds a layout, a Composer setup or a recipe.
const compose = hasComposeLikePayload(entry);
const layout = compose && hasLayoutPayload(entry);
const recipe = !compose && hasRecipeLikePayload(entry);
kind.hidden = !compose && !recipe;
kind.textContent = layout ? "L" : compose ? "C" : "R";
kind.style.background = layout ? "rgba(124,92,220,.95)" : compose ? "rgba(55,165,95,.95)" : "rgba(235,140,35,.95)";
},
};
}
function buttonBar(node) {
const row = el("div", "pm-v2-buttons");
const add = (text, title, onClick) => {
const btn = button(text, { soft: true, grow: true, title, onClick });
btn.classList.add("pm-v2-btn");
row.append(btn);
};
add("Save Prompt", "Save the prompt, its LoRAs and trigger words to the library", () => savePrompt(node));
add("New Prompt", "Start a new prompt", () => newPrompt(node));
add("More ▼", "", (event) => {
const box = event.currentTarget.getBoundingClientRect();
openMenu(box.left, box.bottom + 4, [
{ label: "Delete Prompt", danger: true, disabled: !selection(node).name, action: () => deletePrompt(node) },
{ label: "Undo LoRA and trigger word edits", disabled: !hasEdits(readState(node)), action: () => writeState(node, {}) },
null,
{ label: "Export JSON", action: () => exportPromptsJSON(node) },
{ label: "Import JSON", action: () => importPrompts(node, "merge") },
{ label: "Replace JSON", action: () => importPrompts(node, "replace") },
]);
});
row.addEventListener("contextmenu", (event) => event.preventDefault());
return { element: row };
}
function textPanel(node) {
const area = el("textarea", "fbui-text pm-v2-text");
area.spellcheck = false;
area.addEventListener("input", () => { findWidget(node, "text").value = area.value; });
area.addEventListener("change", notifyChange);
// Typing and selecting here must not drag the node or reach the canvas.
area.addEventListener("pointerdown", (event) => event.stopPropagation());
area.addEventListener("keydown", (event) => event.stopPropagation());
return {
element: area,
sync() {
// With the prompt input on, its text from the last run, read-only.
const fromInput = findWidget(node, "use_prompt_input")?.value === true && isLinked(node, "prompt");
area.readOnly = fromInput;
const shown = fromInput ? node._pm.run?.prompt_input ?? "" : findWidget(node, "text").value ?? "";
if (area.value !== shown && document.activeElement !== area) area.value = shown;
area.placeholder = fromInput ? "From the prompt input (shown after a run)" : "Enter prompt text";
},
};
}
// ---------------------------------------------------------------- stack cards
// A titled card with buttons at the right and a wrap of tags; it measures its
// own height and asks the node's card to follow. Tags are rebuilt only when
// what they show changes, and never under an open strength field.
function stackCard(node, key, title, tools, renderTags) {
const box = el("div", "pm-v2-stack");
const head = el("div", "head");
const buttons = el("div", "tools");
for (const [text, hint, onClick] of tools) {
const btn = el("button", "pm-v2-mini", text);
btn.title = hint;
btn.addEventListener("click", onClick);
buttons.append(btn);
}
head.append(el("span", "title", title), buttons);
const tags = el("div", "pm-v2-tags");
box.append(head, tags);
box.addEventListener("contextmenu", (event) => event.preventDefault());
const measure = () => {
const height = Math.ceil(box.scrollHeight);
if (height && height !== node._pm.heights[key]) {
node._pm.heights[key] = height;
node._pm.card.refresh();
}
};
new ResizeObserver(measure).observe(tags);
let shown = null;
return {
element: box,
sync() {
// A strength being typed keeps its field; anything else (a button just clicked) redraws.
if (box.contains(document.activeElement) && document.activeElement.classList.contains("pm-v2-strength")) return;
const { signature, elements } = renderTags();
if (signature === shown) return;
shown = signature;
tags.replaceChildren(...elements);
requestAnimationFrame(measure);
},
};
}
function strengthField(node, slot, row) {
const input = el("input", "pm-v2-strength");
input.type = "text";
input.value = Number(row.strength).toFixed(2);
input.addEventListener("focus", () => input.select());
input.addEventListener("blur", () => {
const value = parseFloat(input.value);
if (Number.isNaN(value) || value === row.strength) {
input.value = Number(row.strength).toFixed(2);
return;
}
editLoras(node, slot, [[row.name, (edit) => {
if (value === row.base_strength) delete edit.strength;
else edit.strength = value;
return edit;
}]]);
});
input.addEventListener("keydown", (event) => {
event.stopPropagation();
if (event.key === "Enter") input.blur();
if (event.key === "Escape") {
input.value = Number(row.strength).toFixed(2);
input.blur();
}
});
input.addEventListener("pointerdown", (event) => event.stopPropagation());
input.addEventListener("click", (event) => event.stopPropagation());
return input;
}
function moveLora(node, slot, index, delta) {
const names = loraRows(node, slot).map((row) => row.name.toLowerCase());
const to = index + delta;
if (to < 0 || to >= names.length) return;
names.splice(to, 0, names.splice(index, 1)[0]);
const state = readState(node);
state.order ??= {};
state.order[slot] = names;
writeState(node, state);
}
function loraTag(node, slot, row, index, count) {
const missing = row.available === false;
const tag = el("div", "pm-v2-tag lora");
tag.classList.toggle("on", row.active);
tag.classList.toggle("input", row.from_input === true);
tag.classList.toggle("missing", missing);
if (missing) tag.append(el("span", "warn", "⚠️"));
tag.append(el("span", "name", row.name), strengthField(node, slot, row));
tag.addEventListener("click", () => editLoras(node, slot, [[row.name, activeEdit(row, !row.active)]]));
tag.addEventListener("contextmenu", (event) => {
event.preventDefault();
event.stopPropagation();
openMenu(event.clientX, event.clientY, [
{ label: "Move Up", disabled: index === 0, action: () => moveLora(node, slot, index, -1) },
{ label: "Move Down", disabled: index === count - 1, action: () => moveLora(node, slot, index, 1) },
...(missing ? [{ label: "🔍 Search on CivitAI", action: () => window.open(`https://civitai.com/search/models?sortBy=models_v9&query=${encodeURIComponent(row.name)}&modelType=LORA`, "_blank") }] : []),
null,
{ label: "Delete", danger: true, action: () => editLoras(node, slot, [[row.name, (edit) => ({ ...edit, removed: true })]]) },
]);
});
tag.title = missing
? `${row.name}\n⚠️ NOT FOUND - This LoRA is missing from your system\nRight-click for options`
: `${row.name}${row.from_input ? " (from the input)" : ""}\nStrength: ${Number(row.strength).toFixed(2)}\nClick to toggle on/off\nRight-click for options`;
if (missing) return tag;
// LoRA Manager's preview beside the tag when it is installed, in place of the plain tooltip.
let timer = null;
tag.addEventListener("mouseenter", () => {
const box = tag.getBoundingClientRect();
timer = setTimeout(async () => {
const tooltip = await getLoraManagerPreviewTooltip();
if (!tooltip) return;
tag.removeAttribute("title");
tooltip.show(row.name, box.right, box.top);
}, 300);
});
tag.addEventListener("mouseleave", () => {
clearTimeout(timer);
getLoraManagerPreviewTooltip().then((tooltip) => tooltip?.hide());
});
return tag;
}
function loraCard(node, slot) {
return stackCard(node, slot, `LoRAs Stack ${slot.toUpperCase()}`, [
["Reset Strength", "Reset all strength values to their original values", () => {
editLoras(node, slot, loraRows(node, slot).map((row) => [row.name, (edit) => {
delete edit.strength;
return edit;
}]));
}],
["Toggle All", "Switch all of this stack's LoRAs on, or off when they all are", () => {
const rows = loraRows(node, slot);
const active = !rows.every((row) => row.active);
editLoras(node, slot, rows.map((row) => [row.name, activeEdit(row, active)]));
}],
], () => {
const rows = loraRows(node, slot);
return {
signature: JSON.stringify(rows),
elements: rows.map((row, index) => loraTag(node, slot, row, index, rows.length)),
};
});
}
function wordTag(node, word) {
const tag = el("div", "pm-v2-tag word");
tag.classList.toggle("on", word.active);
tag.append(el("span", "name", word.text));
tag.title = `${word.text}${word.from_input ? " (from the input)" : ""}\nClick to toggle on/off\nRight-click for options`;
tag.addEventListener("click", () => editWords(node, [[word.text, activeEdit(word, !word.active)]]));
tag.addEventListener("contextmenu", (event) => {
event.preventDefault();
event.stopPropagation();
openMenu(event.clientX, event.clientY, [{ label: "Delete", danger: true, action: () => editWords(node, [[word.text, (edit) => ({ ...edit, removed: true })]]) }]);
});
return tag;
}
function wordsCard(node) {
return stackCard(node, "words", "Trigger Words", [
["Toggle All", "Switch all trigger words on, or off when they all are", () => {
const words = wordRows(node);
const active = !words.every((word) => word.active);
editWords(node, words.map((word) => [word.text, activeEdit(word, active)]));
}],
], () => {
const words = wordRows(node);
return { signature: JSON.stringify(words), elements: words.map((word) => wordTag(node, word)) };
});
}
// ---------------------------------------------------------------- node
function setupNode(node) {
ensureCss();
const pm = { run: null, available: new Map(), heights: { a: STACK_HEAD + 28, b: STACK_HEAD + 28, c: STACK_HEAD + 28, d: STACK_HEAD + 28, words: STACK_HEAD + 28 } };
node._pm = pm;
// The card stands in for these; use_prompt_input and lora_mode are card rows.
for (const name of ["category", "name", "text", "state"]) hideWidget(findWidget(node, name));
pm.card = mountCard(node, {
minWidth: MIN_WIDTH,
rows: [
{ widget: "use_prompt_input", label: "Prompt input" },
{ widget: "lora_mode", label: "LoRA input", kind: "segment", labels: MODE_LABELS, titles: MODE_TITLES },
{ panel: textPanel, grow: true, height: TEXT_MIN_HEIGHT },
{ panel: promptBar, height: BAR_HEIGHT },
{ panel: buttonBar, height: BUTTONS_HEIGHT },
...SLOTS.map((slot) => ({ panel: (n) => loraCard(n, slot), height: () => pm.heights[slot], when: (_values, n) => loraRows(n, slot).length > 0 })),
{ panel: wordsCard, height: () => pm.heights.words, when: (_values, n) => wordRows(n).length > 0 },
],
});
helpBadge(node, GUIDE);
chainCallback(node, "onRemoved", () => getLoraManagerPreviewTooltip().then((tooltip) => tooltip?.hide()));
chainCallback(node, "onExecuted", (output) => {
const panels = output?.prompt_manager?.[0];
if (!panels) return;
pm.run = { ...panels, key: runKey(panels.category, panels.name, panels.lora_mode) };
node.properties[RUN_PROPERTY] = pm.run;
pm.card.refresh();
});
chainCallback(node, "onConfigure", () => {
pm.configured = true;
pm.run = node.properties?.[RUN_PROPERTY] ?? null;
loadPrompts(node).then(() => {
pm.card.refresh();
checkAvailability(node);
});
});
queueMicrotask(() => {
if (pm.configured) return;
loadPrompts(node).then(() => pm.card.refresh());
});
}
app.registerExtension({
name: "PromptManager.PromptManagerV2",
beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== NODE_NAME) return;
hideInputsInDef(nodeData, ["category", "name", "use_prompt_input", "lora_mode", "text", "state"]);
chainCallback(nodeType.prototype, "onNodeCreated", function () {
setupNode(this);
});
},
});
+227
View File
@@ -0,0 +1,227 @@
/**
* PromptModelLoader Extension for ComfyUI
* Displays model type and name info on the node.
* Dynamically shows/hides Model B outputs when two models are found.
* Hides CLIP/VAE slots for non-checkpoint models.
*/
import { app } from "../../scripts/app.js";
// --- Draw model info (shared between single and dual) ---
const TYPE_COLORS = {
"Checkpoint": "#4CAF50",
"Diffusion": "#2196F3",
"GGUF": "#FF9800",
"NOT FOUND": "#F44336",
"Unknown": "#9E9E9E"
};
function drawModelRow(ctx, typeText, modelName, yOffset, label, widgetWidth) {
const padding = 8;
const badgeColor = TYPE_COLORS[typeText] || TYPE_COLORS["Unknown"];
const badgeLabel = label ? `${label} ${typeText}` : typeText;
// Badge pill
ctx.font = "bold 11px Arial";
const typeWidth = ctx.measureText(badgeLabel).width + 14;
ctx.fillStyle = badgeColor;
ctx.beginPath();
ctx.roundRect(padding, yOffset + 4, typeWidth, 16, 8);
ctx.fill();
// Badge text
ctx.fillStyle = "#FFFFFF";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(badgeLabel, padding + 7, yOffset + 12);
// Model name to the right of badge
ctx.font = "12px Arial";
ctx.fillStyle = typeText === "NOT FOUND" ? "#F44336" : "#CCCCCC";
const nameX = padding + typeWidth + 8;
const maxNameWidth = widgetWidth - nameX - padding;
let displayName = modelName || "";
while (ctx.measureText(displayName).width > maxNameWidth && displayName.length > 5) {
displayName = displayName.slice(0, -4) + "...";
}
ctx.fillText(displayName, nameX, yOffset + 12);
}
app.registerExtension({
name: "PromptManager.ModelLoader",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "PromptModelLoader") return;
// Hook into onExecuted to receive UI data from Python
const origOnExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
origOnExecuted?.apply(this, arguments);
const info = message?.model_info?.[0];
if (!info) return;
this._applyModelInfo(info);
};
// Central method to apply model info
nodeType.prototype._applyModelInfo = function (info) {
const typeA = info.model_type_a || "Unknown";
const nameA = info.model_name_a || "";
const hasB = !!info.has_model_b;
const typeB = info.model_type_b || "";
const nameB = info.model_name_b || "";
const isCheckpointA = typeA === "Checkpoint";
const isCheckpointB = typeB === "Checkpoint";
// Store for display and serialization
this._modelInfo = info;
// Update title
this.title = hasB
? `Prompt Model Loader [${typeA} + ${typeB}]`
: `Prompt Model Loader [${typeA}]`;
// Update output slots
this._updateOutputSlots(hasB, isCheckpointA, isCheckpointB);
// Create/update info widget
this._ensureInfoWidget();
this.setDirtyCanvas(true, true);
};
// Save state into the workflow JSON
const origOnSerialize = nodeType.prototype.onSerialize;
nodeType.prototype.onSerialize = function (o) {
origOnSerialize?.apply(this, arguments);
if (this._modelInfo) {
o._modelLoaderState = this._modelInfo;
}
};
// Restore state when workflow is loaded / tab is switched back
const origOnConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (info) {
origOnConfigure?.apply(this, arguments);
const state = info?._modelLoaderState;
if (state) {
requestAnimationFrame(() => {
this._applyModelInfo(state);
});
}
};
// Manage output slot visibility
// Full outputs: model_a(0), clip_a(1), vae_a(2), model_b(3), clip_b(4), vae_b(5)
nodeType.prototype._updateOutputSlots = function (hasB, isCheckpointA, isCheckpointB) {
if (!this._originalOutputs) {
this._originalOutputs = this.outputs.map(o => ({ ...o }));
}
// Build desired output list
const desired = [];
// Model A always present
desired.push(this._originalOutputs[0]); // model_a
// CLIP A / VAE A only for checkpoints
if (isCheckpointA) {
desired.push(this._originalOutputs[1]); // clip_a
desired.push(this._originalOutputs[2]); // vae_a
}
// Model B outputs only when two models found
if (hasB) {
desired.push(this._originalOutputs[3]); // model_b
if (isCheckpointB) {
desired.push(this._originalOutputs[4]); // clip_b
desired.push(this._originalOutputs[5]); // vae_b
}
}
// Disconnect outputs that will be removed
for (let i = this.outputs.length - 1; i >= desired.length; i--) {
if (this.outputs[i]?.links?.length > 0) {
for (const linkId of [...this.outputs[i].links]) {
this.disconnectOutput(i);
}
}
this.removeOutput(i);
}
// Add/update outputs to match desired
for (let i = 0; i < desired.length; i++) {
if (i < this.outputs.length) {
this.outputs[i].name = desired[i].name;
this.outputs[i].type = desired[i].type;
} else {
this.addOutput(desired[i].name, desired[i].type);
}
}
this.computeSize();
};
// Info widget helper
nodeType.prototype._ensureInfoWidget = function () {
const info = this._modelInfo;
if (!info) return;
const hasB = !!info.has_model_b;
const widgetHeight = hasB ? 50 : 26;
let widget = this.widgets?.find(w => w.name === "_model_info_display");
if (!widget) {
widget = {
name: "_model_info_display",
type: "custom",
y: 0,
computeSize: () => [0, widgetHeight],
draw: function (ctx, node, widgetWidth, y) {
const info = node._modelInfo;
if (!info) return;
const hasB = !!info.has_model_b;
if (hasB) {
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "A:", widgetWidth);
drawModelRow(ctx, info.model_type_b || "Unknown", info.model_name_b || "", y + 24, "B:", widgetWidth);
} else {
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "", widgetWidth);
}
}
};
if (!this.widgets) this.widgets = [];
this.widgets.push(widget);
}
// Update height for single vs dual model
widget.computeSize = () => [0, widgetHeight];
this.computeSize();
};
// Reset display on clear/reconnect
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function () {
origOnConnectionsChange?.apply(this, arguments);
// Reset info when input connection changes
if (arguments[1] === 0 && arguments[0] === 1) {
this._modelInfo = null;
this.title = "Prompt Model Loader";
// Restore all outputs
if (this._originalOutputs) {
while (this.outputs.length < this._originalOutputs.length) {
const orig = this._originalOutputs[this.outputs.length];
this.addOutput(orig.name, orig.type);
}
}
// Remove info widget
if (this.widgets) {
const idx = this.widgets.findIndex(w => w.name === "_model_info_display");
if (idx >= 0) {
this.widgets.splice(idx, 1);
this.computeSize();
}
}
this.setDirtyCanvas(true, true);
}
};
}
});
+119
View File
@@ -0,0 +1,119 @@
export const PROMPT_ENDPOINT_PREFIX = "/prompt-manager";
export const PROMPT_ADVANCED_ENDPOINT_PREFIX = "/prompt-manager-advanced";
export const SYSTEM_PROMPTS_ENDPOINT_PREFIX = "/prompt-generator";
export const COMPOSER_ENDPOINT_PREFIX = "/prompt-manager/compose";
export const SOURCE_COMPOSE = "Compose Data";
export const SOURCE_PROMPT = "Prompt Data";
export const SOURCE_SYSTEM_PROMPTS = "System Prompts";
export function isHiddenPromptEntryKey(name) {
const normalized = String(name || "").trim().toLowerCase();
return normalized === "__meta__"
|| normalized === "_base_prompt_"
|| normalized === "_prompt_prefix_"
|| normalized === "_category_base_prompt_"
|| normalized === "_category_prefix_"
|| normalized === "_prompt_type_"
|| normalized === "_prompts_"
|| normalized === "_category_name_"
|| normalized === "_type_file_"
|| normalized === "_type_name_"
|| normalized === "_subject_type_"
|| normalized === "_subject_kind_"
|| normalized === "_type_prefix_"
|| normalized === "_type_base_prompt_"
|| normalized === "_type_nsfw_";
}
export function getPromptStoreKindFromSource(source) {
if (source === SOURCE_COMPOSE) return "composer";
if (source === SOURCE_PROMPT) return "manager";
return "generator";
}
export function getPromptStoreKindFromEndpoint(endpointPrefix) {
if (endpointPrefix === COMPOSER_ENDPOINT_PREFIX) return "composer";
if (endpointPrefix === SYSTEM_PROMPTS_ENDPOINT_PREFIX) return "generator";
return "manager";
}
export function getEndpointPrefixForSource(source) {
if (source === SOURCE_PROMPT) return PROMPT_ENDPOINT_PREFIX;
if (source === SOURCE_SYSTEM_PROMPTS) return SYSTEM_PROMPTS_ENDPOINT_PREFIX;
return COMPOSER_ENDPOINT_PREFIX;
}
export function getCategoryPromptEntries(categoryData, storeKind = "manager") {
if (!categoryData || typeof categoryData !== "object" || Array.isArray(categoryData)) return {};
if (storeKind === "composer") {
const nested = categoryData._prompts_;
if (nested && typeof nested === "object" && !Array.isArray(nested)) {
return nested;
}
}
return Object.fromEntries(
Object.entries(categoryData).filter(([name]) => !isHiddenPromptEntryKey(name))
);
}
export function getCategoryPromptEntriesForSource(categoryData, source) {
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromSource(source));
}
export function getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix) {
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromEndpoint(endpointPrefix));
}
export function getCategoryPromptEntryForEndpoint(categoryData, promptName, endpointPrefix) {
return getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix)?.[promptName] || null;
}
export function buildSavePromptRequestBody(storeKind, payload) {
const body = {
category: payload?.category,
name: payload?.name,
text: payload?.text,
};
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_name")) body.old_name = payload.old_name;
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_category")) body.old_category = payload.old_category;
if (storeKind === "generator") {
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
return body;
}
if (storeKind === "composer") {
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora")) body.lora = payload.lora;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_strength")) body.lora_strength = payload.lora_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image")) body.lora_image = payload.lora_image;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image_strength")) body.lora_image_strength = payload.lora_image_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video")) body.lora_video = payload.lora_video;
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video_strength")) body.lora_video_strength = payload.lora_video_strength;
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod")) body.refmod = payload.refmod;
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod_weight")) body.refmod_weight = payload.refmod_weight;
return body;
}
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
if (Object.prototype.hasOwnProperty.call(payload || {}, "workflow_data")) body.workflow_data = payload.workflow_data;
if (Object.prototype.hasOwnProperty.call(payload || {}, "negative_prompt")) body.negative_prompt = payload.negative_prompt;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_a")) body.loras_a = payload.loras_a;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_b")) body.loras_b = payload.loras_b;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_c")) body.loras_c = payload.loras_c;
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_d")) body.loras_d = payload.loras_d;
if (Object.prototype.hasOwnProperty.call(payload || {}, "trigger_words")) body.trigger_words = payload.trigger_words;
return body;
}
export function buildSavePromptRequestBodyForSource(source, payload) {
return buildSavePromptRequestBody(getPromptStoreKindFromSource(source), payload);
}
export function buildSavePromptRequestBodyForEndpoint(endpointPrefix, payload) {
return buildSavePromptRequestBody(getPromptStoreKindFromEndpoint(endpointPrefix), payload);
}
+24
View File
@@ -0,0 +1,24 @@
let lockStyleInstalled = false;
function installLockStyle() {
if (lockStyleInstalled) return;
lockStyleInstalled = true;
const style = document.createElement("style");
style.textContent = '.lg-node-widgets textarea[data-pm-locked="true"] { opacity: 0.5; }';
document.head.appendChild(style);
}
// Read-only + ghosted prompt textarea: classic edits inputEl; Nodes 2.0 renders its own textarea from widget options.
export function setPromptTextLocked(widget, locked) {
if (!widget) return;
locked = !!locked;
if (widget.inputEl) {
widget.inputEl.readOnly = locked;
if (locked) widget.inputEl.style.pointerEvents = "auto";
widget.inputEl.style.opacity = locked ? "0.5" : "";
}
if (!!widget.options?.read_only === locked) return;
installLockStyle();
// Reassigning options (not mutating) is what makes the Vue widget store react.
widget.options = { ...widget.options, read_only: locked, "data-pm-locked": locked ? "true" : undefined };
}
+4880
View File
File diff suppressed because it is too large Load Diff
+456
View File
@@ -0,0 +1,456 @@
/**
* RecipeModelLoader extension.
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
*/
import { app } from "../../scripts/app.js";
const MODEL_CHOICES = ["model_a", "model_b"];
const WEIGHT_DTYPE_CHOICES = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"];
function _trimMiddle(text, maxLen) {
const s = String(text || "");
if (s.length <= maxLen) return s;
const left = Math.ceil((maxLen - 3) / 2);
const right = Math.floor((maxLen - 3) / 2);
return `${s.slice(0, left)}...${s.slice(s.length - right)}`;
}
function _shortName(name) {
const raw = String(name || "").trim();
if (!raw) return "";
const normalized = raw.replace(/\\/g, "/");
const base = normalized.split("/").pop() || normalized;
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
}
function _shortList(names) {
const list = Array.isArray(names) ? names : [];
return list.map(_shortName).filter(Boolean);
}
const COLORS = {
modelCheckpoint: "#4CAF50",
modelDiffusion: "#2196F3",
modelGguf: "#FF9800",
vae: "#FF6B6B",
clip: "#C4A300",
notFound: "#F44336",
muted: "#B0B0B0",
missing: "#E57373",
};
function _buildRows(info) {
const status = String(info.status || "").toLowerCase();
if (!info || status === "idle") {
return [
{ label: "Model", labelColor: COLORS.modelDiffusion, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Clip", labelColor: COLORS.clip, value: "(awaiting execution)", valueColor: COLORS.muted },
{ label: "Vae", labelColor: COLORS.vae, value: "(awaiting execution)", valueColor: COLORS.muted },
];
}
const modelKind = String(info.model_kind || info.loader_type || "").toLowerCase();
const modelColor = modelKind === "checkpoint"
? COLORS.modelCheckpoint
: (modelKind === "gguf" ? COLORS.modelGguf : COLORS.modelDiffusion);
const rows = [];
const modelShort = _shortName(info.model_name || "");
rows.push({
label: "Model",
labelColor: modelColor,
value: modelShort || "(none)",
valueColor: modelShort ? "#CCCCCC" : COLORS.missing,
});
const loaderType = String(info.loader_type || "").toLowerCase();
const vaeShort = _shortName(info.vae_name || "");
const clipShort = _shortList(info.clip_names);
if (loaderType === "checkpoint") {
// Keep all tags visible; show source explicitly for checkpoint-provided assets.
const usingInternalVae = !!info.uses_checkpoint_vae;
const usingInternalClip = !!info.uses_checkpoint_clip;
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: usingInternalClip ? "From Checkpoint" : (clipShort.length > 0 ? clipShort.join(", ") : "(none provided)"),
valueColor: usingInternalClip ? COLORS.muted : (clipShort.length > 0 ? "#CCCCCC" : COLORS.missing),
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: usingInternalVae ? "From Checkpoint" : (vaeShort || "(none provided)"),
valueColor: usingInternalVae ? COLORS.muted : (vaeShort ? "#CCCCCC" : COLORS.missing),
});
} else {
// Diffusion/UNet: always show Clip + Vae lines.
rows.push({
label: "Clip",
labelColor: COLORS.clip,
value: clipShort.length > 0 ? clipShort.join(", ") : "(none provided)",
valueColor: clipShort.length > 0 ? "#CCCCCC" : COLORS.missing,
});
rows.push({
label: "Vae",
labelColor: COLORS.vae,
value: vaeShort || "(none provided)",
valueColor: vaeShort ? "#CCCCCC" : COLORS.missing,
});
}
return rows;
}
function _drawPillRow(ctx, row, y, widgetWidth) {
const left = 8;
const badgeText = String(row.label || "");
const value = String(row.value || "");
const badgeW = 68;
const valueX = left + badgeW + 10;
const valueMax = Math.max(16, Math.floor((widgetWidth - valueX - 8) / 6));
const displayValue = _trimMiddle(value, valueMax);
ctx.font = "bold 11px Arial";
const badgeH = 16;
const badgeY = y - Math.floor(badgeH / 2);
ctx.fillStyle = row.labelColor || COLORS.muted;
ctx.beginPath();
ctx.roundRect(left, badgeY, badgeW, badgeH, 8);
ctx.fill();
ctx.fillStyle = "#FFFFFF";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(badgeText, left + 8, y + 0.5);
ctx.font = "12px Arial";
ctx.fillStyle = row.valueColor || "#CCCCCC";
ctx.fillText(displayValue, valueX, y + 0.5);
}
function _getWidgetValue(node, name, fallback = "") {
const w = node?.widgets?.find((x) => x.name === name);
if (!w || w.value == null) return fallback;
return String(w.value);
}
function _widgetByNames(node, names) {
const arr = Array.isArray(names) ? names : [names];
return node?.widgets?.find((w) => arr.includes(w.name));
}
function _sanitizeChoice(value, allowed, fallback) {
const v = String(value ?? "");
return allowed.includes(v) ? v : fallback;
}
function _selectedModelSlot(node) {
return _sanitizeChoice(
_getWidgetValue(node, "model", "model_a"),
MODEL_CHOICES,
"model_a"
);
}
function _readWidgetState(node) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
return {
model: _sanitizeChoice(modelWidget?.value, MODEL_CHOICES, "model_a"),
weight_dtype: _sanitizeChoice(dtypeWidget?.value, WEIGHT_DTYPE_CHOICES, "default"),
};
}
function _applyWidgetState(node, state, { persist = true } = {}) {
const modelWidget = _widgetByNames(node, ["model"]);
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
const modelVal = _sanitizeChoice(state?.model, MODEL_CHOICES, "model_a");
const dtypeVal = _sanitizeChoice(state?.weight_dtype, WEIGHT_DTYPE_CHOICES, "default");
if (modelWidget) modelWidget.value = modelVal;
if (dtypeWidget) dtypeWidget.value = dtypeVal;
if (persist) {
node.properties = node.properties || {};
node.properties.wfml_model = modelVal;
node.properties.wfml_weight_dtype = dtypeVal;
}
}
function _restoreOrNormalizeWidgetState(node) {
node.properties = node.properties || {};
const live = _readWidgetState(node);
const savedModel = _sanitizeChoice(node.properties.wfml_model, MODEL_CHOICES, "");
const savedDtype = _sanitizeChoice(node.properties.wfml_weight_dtype, WEIGHT_DTYPE_CHOICES, "");
_applyWidgetState(node, {
model: savedModel || live.model || "model_a",
weight_dtype: savedDtype || live.weight_dtype || "default",
}, { persist: true });
}
function _isRerouteNode(n) {
const t = String(n?.type || "").toLowerCase();
const c = String(n?.comfyClass || "").toLowerCase();
return t.includes("reroute") || c.includes("reroute");
}
function _resolveWorkflowUpstreamLink(node) {
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "manager_data");
if (wfInputIdx < 0) return null;
let linkId = node.inputs[wfInputIdx]?.link;
if (linkId == null) return null;
const graph = node.graph;
const seen = new Set();
for (let hop = 0; hop < 24; hop++) {
if (linkId == null || seen.has(linkId)) break;
seen.add(linkId);
const li = graph?.links?.[linkId];
if (!li) break;
const src = graph?.getNodeById?.(li.origin_id);
if (!src) break;
if (!_isRerouteNode(src)) {
return { sourceNode: src, sourceSlot: li.origin_slot };
}
const in0 = src.inputs?.[0];
linkId = in0?.link ?? null;
}
return null;
}
function _tryParseWorkflowData(value) {
if (!value) return null;
if (typeof value === "object") return value;
if (typeof value === "string") {
try {
const p = JSON.parse(value);
if (p && typeof p === "object") return p;
} catch {
return null;
}
}
return null;
}
function _clipListFromWf(wf) {
const c = wf?.clip;
if (Array.isArray(c)) return c.filter(Boolean);
if (typeof c === "string" && c) return [c];
if (c && Array.isArray(c.names)) return c.names.filter(Boolean);
return [];
}
function _vaeFromWf(wf) {
const v = wf?.vae;
if (typeof v === "string") return v;
if (v && typeof v === "object" && typeof v.name === "string") return v.name;
return "";
}
function _inferInfoFromWorkflowData(node, wf) {
const modelKey = _selectedModelSlot(node);
const modelName = typeof wf?.[modelKey] === "string" ? wf[modelKey] : "";
if (!modelName) return null;
const loaderType = String(wf?.loader_type || "").toLowerCase();
const selectedLower = modelName.toLowerCase();
const modelKind = loaderType === "checkpoint"
? "checkpoint"
: (selectedLower.endsWith(".gguf") ? "gguf" : "diffusion");
const vaeName = _vaeFromWf(wf);
const clipNames = _clipListFromWf(wf);
return {
model: modelKey,
model_name: _shortName(modelName),
loader_type: loaderType,
model_kind: modelKind,
vae_name: vaeName,
clip_names: clipNames,
status: "ok",
error_message: "",
missing_name: "",
uses_checkpoint_vae: (loaderType === "checkpoint" && !vaeName),
uses_checkpoint_clip: (loaderType === "checkpoint" && clipNames.length === 0),
};
}
function _refreshInfoFromUpstream(node) {
const resolved = _resolveWorkflowUpstreamLink(node);
if (!resolved) return false;
const { sourceNode, sourceSlot } = resolved;
const out = sourceNode?.outputs?.[sourceSlot];
const wfFromOutput = _tryParseWorkflowData(out?._data) || _tryParseWorkflowData(out?.value);
const wfFromBuilderCache = _tryParseWorkflowData(sourceNode?.properties?.we_extracted_cache);
const wf = wfFromOutput || wfFromBuilderCache;
if (!wf) return false;
const inferred = _inferInfoFromWorkflowData(node, wf);
if (!inferred) return false;
node._applyRecipeModelLoaderInfo(inferred);
return true;
}
function _defaultInfoFromWidgets(node) {
const selected = _selectedModelSlot(node);
return {
model: selected,
model_name: "",
loader_type: "",
model_kind: "",
vae_name: "",
clip_names: [],
status: "idle",
error_message: "",
missing_name: "",
uses_checkpoint_vae: false,
uses_checkpoint_clip: false,
};
}
app.registerExtension({
name: "PromptManager.RecipeModelLoader",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name !== "RecipeModelLoader") return;
const origOnExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
origOnExecuted?.apply(this, arguments);
const info = message?.workflow_model_loader_info?.[0];
if (!info) return;
this._applyRecipeModelLoaderInfo(info);
};
nodeType.prototype._applyRecipeModelLoaderInfo = function (info) {
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
this._recipeModelLoaderInfo = {
model: selected,
model_name: info.model_name || "",
loader_type: info.loader_type || "",
model_kind: info.model_kind || "",
vae_name: info.vae_name || "",
clip_names: Array.isArray(info.clip_names) ? info.clip_names : [],
status: info.status || "ok",
error_message: info.error_message || "",
missing_name: info.missing_name || "",
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
};
this._ensureRecipeModelInfoWidget();
this.setDirtyCanvas(true, true);
};
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = origOnNodeCreated?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
if (!this._recipeModelLoaderInfo) {
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
}
this._ensureRecipeModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function () {
const r = origOnConnectionsChange?.apply(this, arguments);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
return r;
};
const origOnWidgetChanged = nodeType.prototype.onWidgetChanged;
nodeType.prototype.onWidgetChanged = function (name, value, oldValue, w) {
const r = origOnWidgetChanged?.apply(this, arguments);
if (name === "model" || name === "weight_dtype") {
_restoreOrNormalizeWidgetState(this);
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
}
return r;
};
const origOnSerialize = nodeType.prototype.onSerialize;
nodeType.prototype.onSerialize = function (o) {
origOnSerialize?.apply(this, arguments);
const ws = _readWidgetState(this);
this.properties = this.properties || {};
this.properties.wfml_model = ws.model;
this.properties.wfml_weight_dtype = ws.weight_dtype;
if (this._recipeModelLoaderInfo) {
o._recipeModelLoaderInfo = this._recipeModelLoaderInfo;
o._workflowModelLoaderInfo = this._recipeModelLoaderInfo;
}
if (o) {
o.properties = o.properties || {};
o.properties.wfml_model = ws.model;
o.properties.wfml_weight_dtype = ws.weight_dtype;
}
};
const origOnConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function (info) {
origOnConfigure?.apply(this, arguments);
_restoreOrNormalizeWidgetState(this);
const state = info?._recipeModelLoaderInfo || info?._workflowModelLoaderInfo;
if (state) {
requestAnimationFrame(() => {
this._applyRecipeModelLoaderInfo(state);
_refreshInfoFromUpstream(this);
});
} else {
requestAnimationFrame(() => {
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
this._ensureRecipeModelInfoWidget();
_refreshInfoFromUpstream(this);
this.setDirtyCanvas(true, true);
});
}
};
nodeType.prototype._ensureRecipeModelInfoWidget = function () {
let widget = this.widgets?.find(w => w.name === "_recipe_model_loader_info");
if (!widget) {
widget = {
name: "_recipe_model_loader_info",
type: "custom",
y: 0,
computeSize: () => {
const rows = _buildRows(this._recipeModelLoaderInfo || {});
const h = Math.max(26, (rows.length * 22) + 6);
return [0, h];
},
draw: function (ctx, node, widgetWidth, y) {
const info = node._recipeModelLoaderInfo;
if (!info) return;
const rows = _buildRows(info);
ctx.save();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
for (let i = 0; i < rows.length; i++) {
const rowY = y + 12 + (i * 22);
const row = rows[i];
_drawPillRow(ctx, row, rowY, widgetWidth);
}
ctx.restore();
},
};
if (!this.widgets) this.widgets = [];
this.widgets.push(widget);
}
this.computeSize();
};
},
});
+120
View File
@@ -0,0 +1,120 @@
/**
* Recipe Model Picker
*
* Keeps Type/Model/VAE/CLIP widgets in sync with Builder family filtering
* and emits a single model_data payload for Recipe Relay.
*/
import { app } from "../../scripts/app.js";
const DEFAULT_ASSET = "(Default)";
const DEFAULT_FAMILY = "sdxl";
function getWidget(node, name) {
return node?.widgets?.find((w) => w.name === name) || null;
}
function setWidgetOptions(widget, values, fallback = "") {
if (!widget?.options) return;
const list = Array.isArray(values) && values.length > 0 ? values : [fallback];
widget.options.values = list;
}
function ensureWidgetValue(widget, preferred, fallback = "") {
if (!widget?.options) return;
const values = Array.isArray(widget.options.values) ? widget.options.values : [];
const candidate = (preferred != null && values.includes(preferred))
? preferred
: (values.includes(widget.value) ? widget.value : null);
widget.value = candidate != null ? candidate : (values[0] ?? fallback);
}
async function fetchJson(url) {
const response = await fetch(url);
return response.json();
}
function familyKeyFromTypeValue(typeValue, familiesMap) {
const raw = String(typeValue || "").trim();
if (!raw) return DEFAULT_FAMILY;
if (familiesMap[raw]) return raw;
for (const [key, label] of Object.entries(familiesMap)) {
if (label === raw) return key;
}
return DEFAULT_FAMILY;
}
async function reloadPickerLists(node) {
const typeWidget = getWidget(node, "type");
const modelWidget = getWidget(node, "model");
const vaeWidget = getWidget(node, "vae");
const clipWidget = getWidget(node, "clip");
if (!typeWidget || !modelWidget || !vaeWidget || !clipWidget) return;
let families = node._recipePickerFamilies;
if (!families) {
try {
const data = await fetchJson("/workflow-extractor/list-families");
families = data?.families || {};
} catch {
families = {};
}
node._recipePickerFamilies = families;
}
const familyKey = familyKeyFromTypeValue(typeWidget.value, families);
const [modelsData, vaesData, clipsData] = await Promise.all([
fetchJson(`/workflow-extractor/list-models?family=${encodeURIComponent(familyKey)}`),
fetchJson(`/workflow-extractor/list-vaes?family=${encodeURIComponent(familyKey)}`),
fetchJson(`/workflow-extractor/list-clips?family=${encodeURIComponent(familyKey)}`),
]).catch(() => [{ models: [] }, { vaes: [] }, { clips: [] }]);
const models = Array.isArray(modelsData?.models) ? modelsData.models : [];
const vaes = Array.isArray(vaesData?.vaes) ? vaesData.vaes : [];
const clips = Array.isArray(clipsData?.clips) ? clipsData.clips : [];
const prevModel = modelWidget.value;
const prevVae = vaeWidget.value;
const prevClip = clipWidget.value;
setWidgetOptions(modelWidget, models, "");
setWidgetOptions(vaeWidget, [DEFAULT_ASSET, ...vaes], DEFAULT_ASSET);
setWidgetOptions(clipWidget, [DEFAULT_ASSET, ...clips], DEFAULT_ASSET);
ensureWidgetValue(modelWidget, prevModel, "");
ensureWidgetValue(vaeWidget, prevVae, DEFAULT_ASSET);
ensureWidgetValue(clipWidget, prevClip, DEFAULT_ASSET);
if (typeof modelWidget.callback === "function") modelWidget.callback(modelWidget.value);
if (typeof vaeWidget.callback === "function") vaeWidget.callback(vaeWidget.value);
if (typeof clipWidget.callback === "function") clipWidget.callback(clipWidget.value);
app.graph.setDirtyCanvas(true, true);
}
app.registerExtension({
name: "prompt-manager.recipe-model-picker",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeModelPicker") return;
const typeWidget = getWidget(node, "type");
if (!typeWidget) return;
const originalTypeCallback = typeWidget.callback;
typeWidget.callback = async function wrappedTypeCallback(value) {
if (typeof originalTypeCallback === "function") {
originalTypeCallback.call(this, value);
}
await reloadPickerLists(node);
};
requestAnimationFrame(() => {
reloadPickerLists(node).catch(() => {
// Keep node usable even if API endpoints are temporarily unavailable.
});
});
},
});
+18
View File
@@ -0,0 +1,18 @@
/**
* Recipe Relay — set a compact default width for newly created nodes.
*/
import { app } from "../../scripts/app.js";
const RELAY_DEFAULT_WIDTH = 220;
app.registerExtension({
name: "prompt-manager.recipe-relay",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeRelay") return;
requestAnimationFrame(() => {
node.setSize([RELAY_DEFAULT_WIDTH, node.size[1]]);
app.graph.setDirtyCanvas(true, true);
});
},
});
+15
View File
@@ -0,0 +1,15 @@
/**
* Recipe Renderer — Set initial node size to match Recipe Builder width.
*/
import { app } from "../../scripts/app.js";
app.registerExtension({
name: "prompt-manager.recipe-renderer",
async nodeCreated(node) {
if (node.comfyClass !== "RecipeRenderer") return;
requestAnimationFrame(() => {
node.setSize([320, node.size[1]]);
app.graph.setDirtyCanvas(true, true);
});
},
});
+50
View File
@@ -0,0 +1,50 @@
// Prompt Manager's modal palette, now the FB UI kit's colours (js/fbui/theme.js)
// under the names the modals already use. Selected and hover states follow
// the kit: soft blue fill, solid blue edge.
import { T } from "./fbui/theme.js";
export const PM_UI_PALETTE = {
// Backdrop behind modal dialogs
overlay: T.overlay,
// Main modal surface
panel: T.panel,
// Outer border of modal containers
panelBorder: T.plateEdge,
// Dividers between modal sections (header/body/footer)
sectionBorder: T.rule,
// Text input/select control surface
inputBg: T.card,
// Input/select/button neutral stroke
inputBorder: T.plateEdge,
// Neutral button/chip background, and its hover
buttonBg: T.fill,
buttonHover: T.fillHover,
// Primary foreground text
textPrimary: T.inkSoft,
// Titles and important labels
textHeading: T.ink,
// Secondary text
textMuted: T.label,
// Hints and helper text
textHint: T.faint,
// Card/tile background (thumbnails, prompt cards)
cardBg: T.plate,
// Card default border
cardBorder: T.plateEdge,
// The accent (focus/selected), dimmed, as a soft fill, as an edge
accent: T.brand,
accentDim: T.brandInk,
accentSoft: T.brandSoftHover,
accentBorder: T.brand,
// Text on a solid accent fill
onAccent: T.onBrand,
// Destructive actions
danger: T.danger,
dangerSoft: T.dangerSoft,
dangerInk: T.dangerInk,
};
-197
View File
@@ -1,197 +0,0 @@
/**
* Video Metadata Reader - VHS Compatible
* Enables drag-and-drop workflow loading from videos saved by VideoHelperSuite
* without needing VHS installed.
*
* Based on VideoHelperSuite's videoinfo.js implementation.
*/
import { app } from '../../../scripts/app.js'
/**
* Parse video file bytes to extract embedded workflow/prompt metadata.
* Supports webm/mkv (EBML/Matroska) and mp4 (QuickTime) formats.
*/
function getVideoMetadata(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (event) => {
const videoData = new Uint8Array(event.target.result);
const dataView = new DataView(videoData.buffer);
const decoder = new TextDecoder();
// Check for known valid magic bytes
if (dataView.getUint32(0) === 0x1A45DFA3) {
// webm/mkv - EBML/Matroska format
// Metadata stored in COMMENT tags
// See: http://wiki.webmproject.org/webm-metadata/global-metadata
// See: https://www.matroska.org/technical/elements.html
let offset = 4 + 8; // Skip header, COMMENT is 7 chars + 1 to realign
while (offset < videoData.length - 16) {
// Check for text tags (0x4487 = TagString element)
if (dataView.getUint16(offset) === 0x4487) {
// Check that name of tag is COMMENT
const name = String.fromCharCode(...videoData.slice(offset - 7, offset));
if (name === "COMMENT") {
// Parse EBML variable-length integer
// See: https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown
let vint = dataView.getUint32(offset + 2);
let n_octets = Math.clz32(vint) + 1;
if (n_octets < 4) { // 250MB sanity cutoff
let length = (vint >> (8 * (4 - n_octets))) & ~(1 << (7 * n_octets));
const content = decoder.decode(videoData.slice(offset + 2 + n_octets, offset + 2 + n_octets + length));
try {
const json = JSON.parse(content);
resolve(json);
return;
} catch (e) {
console.warn("[VideoMetadata] Failed to parse COMMENT JSON:", e);
}
}
}
}
offset += 1;
}
} else if (dataView.getUint32(4) === 0x66747970) {
// mp4 - QuickTime/ISO format
// See: https://developer.apple.com/documentation/quicktime-file-format
// Metadata can be in various locations, search from end
// First try: Look for ©cmt (comment) atom - VHS style
let offset = videoData.length - 4;
while (offset > 16) {
if (dataView.getUint32(offset) === 0x64617461) { // 'data' tag
if (dataView.getUint32(offset - 8) === 0xa9636d74) { // '©cmt' (comment) tag
let size = dataView.getUint32(offset - 4) - 4 * 4;
const content = decoder.decode(videoData.slice(offset + 12, offset + 12 + size));
try {
const json = JSON.parse(content);
resolve(json);
return;
} catch (e) {
console.warn("[VideoMetadata] Failed to parse ©cmt JSON:", e);
}
}
}
offset -= 1;
}
// Second try: Look for 'prompt' or 'workflow' tags in metadata
// These are stored by our SaveVideoH26x node using movflags=use_metadata_tags
offset = 0;
while (offset < videoData.length - 100) {
// Look for 'prompt' or 'workflow' strings followed by JSON
const slice = decoder.decode(videoData.slice(offset, offset + 20));
if (slice.includes('prompt') || slice.includes('workflow')) {
// Try to find JSON starting after the key
for (let i = 0; i < 50 && offset + i < videoData.length - 1; i++) {
if (videoData[offset + i] === 0x7B) { // '{'
// Found potential JSON start, try to parse
let jsonEnd = offset + i;
let braceCount = 0;
for (let j = jsonEnd; j < Math.min(jsonEnd + 1000000, videoData.length); j++) {
if (videoData[j] === 0x7B) braceCount++;
if (videoData[j] === 0x7D) braceCount--;
if (braceCount === 0) {
jsonEnd = j + 1;
break;
}
}
const jsonStr = decoder.decode(videoData.slice(offset + i, jsonEnd));
try {
const json = JSON.parse(jsonStr);
if (json.workflow || json.prompt || json.nodes) {
resolve(json.workflow ? json : { workflow: json });
return;
}
} catch (e) {
// Not valid JSON, continue searching
}
}
}
}
offset += 100; // Skip ahead in larger chunks
}
}
// No metadata found
resolve(undefined);
};
reader.onerror = () => {
console.error("[VideoMetadata] Failed to read file");
resolve(undefined);
};
reader.readAsArrayBuffer(file);
});
}
/**
* Check if file is a video by extension
*/
function isVideoFile(file) {
const videoExtensions = ['.webm', '.mp4', '.mkv', '.mov', '.avi'];
const name = file?.name?.toLowerCase() || '';
return videoExtensions.some(ext => name.endsWith(ext));
}
// Store original handler
let originalHandleFile = null;
/**
* Custom file handler that intercepts video files to extract workflow metadata
*/
async function handleFile(file) {
// Check if this is a video file
if (file?.type?.startsWith("video/") || isVideoFile(file)) {
console.log("[VideoMetadata] Processing video file:", file.name);
try {
const videoInfo = await getVideoMetadata(file);
if (videoInfo?.workflow) {
console.log("[VideoMetadata] Found workflow in video, loading...");
await app.loadGraphData(videoInfo.workflow);
return;
} else {
console.log("[VideoMetadata] No workflow metadata found in video");
}
} catch (e) {
console.error("[VideoMetadata] Error extracting metadata:", e);
}
}
// Fall through to original handler
if (originalHandleFile) {
return await originalHandleFile.apply(this, arguments);
}
}
// Register extension
app.registerExtension({
name: "PromptManager.VideoMetadata",
async setup() {
// Only hijack if not already done by VHS
if (!window._vhsVideoMetadataRegistered) {
// Store and replace the file handler
originalHandleFile = app.handleFile;
app.handleFile = handleFile;
// Add video formats to file input accept attribute
const fileInput = document.getElementById("comfy-file-input");
if (fileInput && !fileInput.accept.includes("video/")) {
fileInput.accept += ",video/webm,video/mp4,video/x-matroska";
}
// Mark as registered to avoid double-registration if VHS loads later
window._vhsVideoMetadataRegistered = true;
console.log("[VideoMetadata] VHS-compatible video metadata reader registered");
} else {
console.log("[VideoMetadata] Video metadata handler already registered (likely by VHS)");
}
}
});
-352
View File
@@ -1,352 +0,0 @@
"""
Latent Preview for Video Sampling - Provides animated previews during KSampler execution for video models.
Based on VideoHelperSuite implementation, with compatibility checks to avoid conflicts.
"""
from PIL import Image
import time
import io
import struct
from threading import Thread
import functools
import torch
import torch.nn.functional as F
# Rates table for different video models (frames per second / temporal compression)
RATES_TABLE = {
'Mochi': 24 // 6,
'LTXV': 24 // 8,
'HunyuanVideo': 24 // 4,
'Cosmos1CV8x8x8': 24 // 8,
'Wan21': 16 // 4,
'Wan22': 24 // 4
}
# Global flag to track if we've hooked the previewer
_hook_installed = False
_original_get_previewer = None
def hook(obj, attr):
"""Decorator to hook/wrap an existing function on an object."""
def dec(f):
f = functools.update_wrapper(f, getattr(obj, attr))
setattr(obj, attr, f)
return f
return dec
# Import latent_preview at module level for proper inheritance
import latent_preview as _latent_preview_module
class WrappedPreviewer(_latent_preview_module.LatentPreviewer):
"""
Wraps the standard latent previewer to provide animated video previews.
This class intercepts preview requests and sends frames as an animation
instead of static images.
"""
def __init__(self, previewer, rate=8, server_instance=None, model_name=None):
# Don't call super().__init__() as we're wrapping an existing previewer
self.first_preview = True
self.last_time = 0
self.c_index = 0
self.rate = rate
self.server = server_instance
self.is_video_taesd = False
self.model_name = model_name
# Copy decoder attributes from the original previewer
# Check what type of previewer we have
if hasattr(previewer, 'taesd'):
self.taesd = previewer.taesd
# Detect if this is a video TAESD (VAE-based) vs regular TAESD
# Video TAESDs use a full VAE with first_stage_model
if hasattr(self.taesd, 'first_stage_model'):
self.is_video_taesd = True
elif hasattr(previewer, 'latent_rgb_factors'):
self.latent_rgb_factors = previewer.latent_rgb_factors
self.latent_rgb_factors_bias = previewer.latent_rgb_factors_bias
self.latent_rgb_factors_reshape = getattr(previewer, 'latent_rgb_factors_reshape', None)
else:
raise Exception('Unsupported preview type for animated latent previews')
def decode_latent_to_preview_image(self, preview_format, x0):
"""
Main preview method - intercepts the standard preview call and
converts it to animated frame previews for video latents.
"""
import server
if x0.ndim == 5:
# Keep batch major for video tensors
x0 = x0.movedim(2, 1)
x0 = x0.reshape((-1,) + x0.shape[-3:])
num_images = x0.size(0)
new_time = time.time()
num_previews = int((new_time - self.last_time) * self.rate)
self.last_time = self.last_time + num_previews / self.rate
if num_previews > num_images:
num_previews = num_images
elif num_previews <= 0:
return None
if self.first_preview:
self.first_preview = False
# Send initialization message to frontend
self.server.send_sync('PM_latentpreview', {
'length': num_images,
'rate': self.rate,
'id': self.server.last_node_id
})
self.last_time = new_time + 1 / self.rate
if self.c_index + num_previews > num_images:
x0 = x0.roll(-self.c_index, 0)[:num_previews]
else:
x0 = x0[self.c_index:self.c_index + num_previews]
# Process previews in a thread
if hasattr(self, 'latent_rgb_factors'):
Thread(target=self._process_latent2rgb_batch, args=(x0, self.c_index, num_images)).run()
else:
Thread(target=self._process_taesd_batch, args=(x0, self.c_index, num_images)).run()
self.c_index = (self.c_index + num_previews) % num_images
return None
def _process_taesd_batch(self, latent_frames, ind, leng):
"""Process and send preview frames to the frontend.
Args:
latent_frames: Latent tensor, shape (N, C, H, W) where N is number of frames
ind: Current frame index
leng: Total number of frames
"""
import server
# For TAESD, decode each frame (don't change this - it works)
for i in range(latent_frames.size(0)):
frame_latent = latent_frames[i:i + 1] # Keep batch dim: (1, C, H, W)
# Decode single frame to PIL Image (same as ComfyUI does)
preview_image = self.decode_single_frame(frame_latent)
if preview_image is None:
continue
# Resize if needed
if preview_image.width > 512 or preview_image.height > 512:
if preview_image.width > preview_image.height:
new_width = 512
new_height = int(512 * preview_image.height / preview_image.width)
else:
new_height = 512
new_width = int(512 * preview_image.width / preview_image.height)
preview_image = preview_image.resize((new_width, new_height), Image.LANCZOS)
# Send to frontend
message = io.BytesIO()
message.write((1).to_bytes(length=4, byteorder='big') * 2)
message.write(ind.to_bytes(length=4, byteorder='big'))
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
preview_image.save(message, format="JPEG", quality=95)
self.server.send_sync(
server.BinaryEventTypes.PREVIEW_IMAGE,
message.getvalue(),
self.server.client_id
)
ind = (ind + 1) % leng
def _process_latent2rgb_batch(self, x0, ind, leng):
"""Process Latent2RGB previews using batch decode (VHS style)."""
import server
# Apply reshape if needed
if self.latent_rgb_factors_reshape is not None:
x0 = self.latent_rgb_factors_reshape(x0)
self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
if self.latent_rgb_factors_bias is not None:
self.latent_rgb_factors_bias = self.latent_rgb_factors_bias.to(dtype=x0.dtype, device=x0.device)
# Batch decode: x0 is (N, C, H, W), output is (N, H, W, 3)
image_tensor = F.linear(x0.movedim(1, -1), self.latent_rgb_factors,
bias=self.latent_rgb_factors_bias)
# Resize if needed
if image_tensor.size(1) > 512 or image_tensor.size(2) > 512:
image_tensor = image_tensor.movedim(-1, 0)
if image_tensor.size(2) < image_tensor.size(3):
height = (512 * image_tensor.size(2)) // image_tensor.size(3)
image_tensor = F.interpolate(image_tensor, (height, 512), mode='bilinear')
else:
width = (512 * image_tensor.size(3)) // image_tensor.size(2)
image_tensor = F.interpolate(image_tensor, (512, width), mode='bilinear')
image_tensor = image_tensor.movedim(0, -1)
# Convert to uint8 (scale from -1..1 to 0..255)
previews_ubyte = (((image_tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF)).to(device="cpu", dtype=torch.uint8)
# Send each frame
for preview in previews_ubyte:
i = Image.fromarray(preview.numpy())
message = io.BytesIO()
message.write((1).to_bytes(length=4, byteorder='big') * 2)
message.write(ind.to_bytes(length=4, byteorder='big'))
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
i.save(message, format="JPEG", quality=95)
self.server.send_sync(
server.BinaryEventTypes.PREVIEW_IMAGE,
message.getvalue(),
self.server.client_id
)
ind = (ind + 1) % leng
def decode_single_frame(self, x0):
"""Decode a single TAESD latent frame to PIL Image.
Only used by _process_taesd_batch().
Args:
x0: Latent tensor, shape (1, C, H, W) for images or (1, C, T, H, W) for video
Returns:
PIL.Image
"""
if self.is_video_taesd:
# TAEHVPreviewerImpl style: x0[:1, :, :1] then [0][0]
if x0.ndim == 4:
x0 = x0.unsqueeze(2) # (1, C, H, W) -> (1, C, 1, H, W)
x_sample = self.taesd.decode(x0[:1, :, :1])[0][0]
# # Apply contrast boost for Wan models (TAESD looks washed out)
# if self.model_name and self.model_name.startswith('Wan'):
# x_sample = self._apply_contrast(x_sample, contrast=1.2, brightness=1.0)
# Video TAEs output 0-1 range, not -1 to 1
return self._tensor_to_image(x_sample, do_scale=False)
else:
# TAESDPreviewerImpl style: decode(x0[:1])[0].movedim(0, 2)
x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
return self._tensor_to_image(x_sample, do_scale=True)
def _apply_contrast(self, tensor, contrast=1.0, brightness=1.0):
"""Apply contrast and brightness adjustment to a tensor in 0-1 range."""
# Contrast: (x - 0.5) * contrast + 0.5
# Brightness: x * brightness
tensor = (tensor - 0.5) * contrast + 0.5
tensor = tensor * brightness
return tensor.clamp(0, 1)
def _tensor_to_image(self, tensor, do_scale=True):
"""Convert tensor to PIL Image, matching ComfyUI's preview_to_image."""
import comfy.model_management
if do_scale:
latents_ubyte = (((tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF))
else:
latents_ubyte = (tensor.clamp(0, 1).mul(0xFF))
if comfy.model_management.directml_enabled:
latents_ubyte = latents_ubyte.to(dtype=torch.uint8)
latents_ubyte = latents_ubyte.to(
device="cpu",
dtype=torch.uint8,
non_blocking=comfy.model_management.device_supports_non_blocking(tensor.device)
)
return Image.fromarray(latents_ubyte.numpy())
def is_vhs_installed():
"""Check if VideoHelperSuite is installed and has latent preview enabled."""
try:
# Check if VHS module is loaded
import sys
for module_name in sys.modules:
if 'videohelpersuite' in module_name.lower():
# VHS is installed, check if it has hooked the previewer
func = getattr(_latent_preview_module, 'get_previewer', None)
if func and hasattr(func, '__wrapped__'):
# VHS has already hooked the previewer
return True
return False
except:
return False
def install_latent_preview_hook():
"""
Install the latent preview hook if:
1. It's not already installed by us
2. VideoHelperSuite hasn't already installed it
"""
global _hook_installed, _original_get_previewer
if _hook_installed:
print("[PromptManager] Latent preview hook already installed")
return True
if is_vhs_installed():
print("[PromptManager] VideoHelperSuite detected with latent preview - skipping to avoid conflict")
return False
try:
import server
serv = server.PromptServer.instance
# Store original function
_original_get_previewer = _latent_preview_module.get_previewer
@hook(_latent_preview_module, 'get_previewer')
def get_latent_video_previewer(device, latent_format, *args, **kwargs):
"""Wrapped previewer that checks settings and returns animated previewer if enabled."""
previewer = get_latent_video_previewer.__wrapped__(device, latent_format, *args, **kwargs)
try:
extra_info = next(serv.prompt_queue.currently_running.values().__iter__())[3]['extra_pnginfo']['workflow']['extra']
prev_setting = extra_info.get('PM_latentpreview', False)
if extra_info.get('PM_latentpreviewrate', 0) != 0:
rate_setting = extra_info['PM_latentpreviewrate']
else:
rate_setting = RATES_TABLE.get(latent_format.__class__.__name__, 8)
except:
# For safety since there's lots of keys, any of which can fail
prev_setting = False
if not prev_setting or not hasattr(previewer, "decode_latent_to_preview"):
return previewer
model_name = latent_format.__class__.__name__
return WrappedPreviewer(previewer, rate_setting, serv, model_name)
_hook_installed = True
print("[PromptManager] Latent preview hook installed successfully")
return True
except Exception as e:
print(f"[PromptManager] Failed to install latent preview hook: {e}")
return False
def uninstall_latent_preview_hook():
"""Restore the original get_previewer function."""
global _hook_installed, _original_get_previewer
if not _hook_installed or _original_get_previewer is None:
return
try:
_latent_preview_module.get_previewer = _original_get_previewer
_hook_installed = False
_original_get_previewer = None
print("[PromptManager] Latent preview hook uninstalled")
except Exception as e:
print(f"[PromptManager] Failed to uninstall latent preview hook: {e}")
View File
+344
View File
@@ -0,0 +1,344 @@
"""
Library Manager - save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder.
Compared to the base Prompt Manager node:
- accepts an IMAGE input to provide/save a thumbnail alongside the data
- tags saved/forwarded workflow metadata as LibraryManager
"""
import json
import server
from ..py.prompt_store import load_prompts
from ..py.thumbnail_utils import image_to_base64_thumbnail
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
from .prompt_manager_adv import PromptManagerAdvanced
class LibraryManager(PromptManagerAdvanced):
"""Workflow-focused manager for manager_data payloads with explicit thumbnail input."""
SOURCE_NAME = "LibraryManager"
# Current, though the legacy Prompt Manager it builds on is deprecated.
DEPRECATED = False
@classmethod
def INPUT_TYPES(cls):
prompts_data = load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
first_category = categories[0] if categories else "Default"
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": ""}),
"text": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Enter prompt text",
"dynamicPrompts": False,
"tooltip": "Edit prompt text directly",
}),
},
"optional": {
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "manager_data from Prompt Manager, Recipe nodes, Prompt Composer or Prompt Layout Builder to save/forward"}),
"image": ("IMAGE", {"tooltip": "Optional image input used as the saved thumbnail when present."}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"loras_a_toggle": "STRING",
"loras_b_toggle": "STRING",
"saved_workflow_data": "STRING",
},
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Library Manager: save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder, with optional thumbnail image input."
RETURN_TYPES = ("MANAGER_DATA",)
RETURN_NAMES = ("manager_data",)
FUNCTION = "get_workflow"
OUTPUT_NODE = True
@classmethod
def IS_CHANGED(cls, category, name, text="", **kwargs):
data = kwargs.get("manager_data", None)
if data is None:
data = kwargs.get("data", None)
image = kwargs.get("image", None)
loras_a_toggle = kwargs.get("loras_a_toggle", "")
loras_b_toggle = kwargs.get("loras_b_toggle", "")
saved_workflow_data = kwargs.get("saved_workflow_data", "")
thumbnail_sig = None
try:
if image is not None:
thumbnail_sig = tuple(getattr(image, "shape", []) or [])
except Exception:
thumbnail_sig = "image"
return (
category,
name,
text,
str(data) if data else None,
thumbnail_sig,
loras_a_toggle or "",
loras_b_toggle or "",
saved_workflow_data or "",
)
def get_workflow(
self,
category,
name,
text="",
manager_data=None,
image=None,
unique_id=None,
loras_a_toggle=None,
loras_b_toggle=None,
saved_workflow_data=None,
**kwargs,
):
prompts_data = load_prompts()
source_name = self.SOURCE_NAME
recipe_data = manager_data
if recipe_data is None:
recipe_data = kwargs.get("data")
if recipe_data is None:
recipe_data = kwargs.get("recipe_data")
def _as_workflow_dict(raw):
if isinstance(raw, dict):
return raw
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else None
except (json.JSONDecodeError, TypeError):
return None
return None
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
if not isinstance(prompt_entry, dict) or not prompt_entry:
if isinstance(prompts_data, dict) and isinstance(name, str) and name:
for cat_prompts in prompts_data.values():
if isinstance(cat_prompts, dict) and isinstance(cat_prompts.get(name), dict):
prompt_entry = cat_prompts.get(name)
break
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else None
live_workflow_data = _as_workflow_dict(recipe_data)
hidden_saved_wf = _as_workflow_dict(saved_workflow_data)
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source=source_name) if isinstance(live_workflow_data, dict) else None
if resolved_workflow_data is None:
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source=source_name) if isinstance(hidden_saved_wf, dict) else None
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source=source_name)
if resolved_workflow_data is None and isinstance(prompt_entry, dict):
prompt_text = str(prompt_entry.get("prompt", "") or text or "")
negative_text = str(prompt_entry.get("negative_prompt", "") or "")
prompt_loras_a = prompt_entry.get("loras_a", []) if isinstance(prompt_entry.get("loras_a"), list) else []
prompt_loras_b = prompt_entry.get("loras_b", []) if isinstance(prompt_entry.get("loras_b"), list) else []
has_prompt_payload = bool(
prompt_text.strip() or
negative_text.strip() or
len(prompt_loras_a) > 0 or
len(prompt_loras_b) > 0
)
if has_prompt_payload:
resolved_workflow_data = build_v2_recipe_data_from_prompt(
prompt_text=prompt_text,
negative_prompt=negative_text,
loras_a=prompt_loras_a,
loras_b=prompt_loras_b,
source=source_name,
)
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
wf_model_a = get_v2_model_block(wf, "model_a") or {}
wf_model_b = get_v2_model_block(wf, "model_b") or {}
wf_has_model_b = isinstance(get_v2_model_block(wf, "model_b"), dict)
composer_payload = wf.get("prompt_composer") if isinstance(wf.get("prompt_composer"), dict) else {}
composer_input_data = composer_payload.get("input_data") if isinstance(composer_payload.get("input_data"), dict) else {}
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
incoming_has_model_b = None
if isinstance(incoming_wf, dict):
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source=source_name)
incoming_models = incoming_v2.get("models", {}) if isinstance(incoming_v2.get("models"), dict) else {}
incoming_has_model_b = isinstance(incoming_models.get("model_b"), dict)
output_text = (wf_model_a.get("positive_prompt", "") or text or "")
generated_thumbnail = image_to_base64_thumbnail(wf.get("IMAGE"), log_prefix=source_name) if isinstance(wf, dict) else None
incoming_thumbnail = image_to_base64_thumbnail(incoming_wf.get("IMAGE"), log_prefix=source_name) if isinstance(incoming_wf, dict) else None
explicit_thumbnail = image_to_base64_thumbnail(image, log_prefix=source_name) if image is not None else None
workflow_thumbnail = explicit_thumbnail if isinstance(explicit_thumbnail, str) and explicit_thumbnail else (
incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
)
)
)
)
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
wf_loras_a = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf_model_a.get("loras", [])
if isinstance(lora, dict) and lora.get("name")
]
wf_loras_b = []
if wf_has_model_b:
wf_loras_b = [
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
for lora in wf_model_b.get("loras", [])
if isinstance(lora, dict) and lora.get("name")
]
composer_input_loras_a = [
(
lora.get("path") or lora.get("name"),
lora.get("model_strength", 1.0),
lora.get("clip_strength", 1.0),
)
for lora in composer_input_data.get("lora_stack", [])
if isinstance(lora, dict) and (lora.get("path") or lora.get("name"))
]
merged_stack_a = list(wf_loras_a) if wf_loras_a else (list(preset_stack_a) if preset_stack_a else [])
if wf_has_model_b:
merged_stack_b = list(wf_loras_b) if wf_loras_b else (list(preset_stack_b) if preset_stack_b else [])
else:
merged_stack_b = []
processed_stack_a = self._process_lora_toggle(merged_stack_a, loras_a_toggle)
processed_stack_b = self._process_lora_toggle(merged_stack_b, loras_b_toggle)
loras_a_display = self._format_loras_for_display_with_unavailable(merged_stack_a, all_preset_loras_a)
loras_b_display = self._format_loras_for_display_with_unavailable(merged_stack_b, all_preset_loras_b)
unavailable_loras_a = [lora["name"] for lora in all_preset_loras_a if not lora.get("available", False)]
unavailable_loras_b = [lora["name"] for lora in all_preset_loras_b if not lora.get("available", False)]
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
"node_id": unique_id,
"prompt": output_text,
"use_prompt_input": False,
"use_workflow_data": True,
"prompt_input": "",
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source=source_name)) if isinstance(recipe_data, dict) else (
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
),
"loras_a": loras_a_display,
"loras_b": loras_b_display,
"input_loras_a": self._format_loras_for_display(composer_input_loras_a) if composer_input_loras_a else [],
"input_loras_b": self._format_loras_for_display(wf_loras_b) if wf_loras_b else [],
"unavailable_loras_a": unavailable_loras_a,
"unavailable_loras_b": unavailable_loras_b,
"trigger_words": [],
"connected_thumbnail": workflow_thumbnail,
"should_reset": False,
"original_strengths_a": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_a_display
if lora_item.get("name")
},
"original_strengths_b": {
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
for lora_item in loras_b_display
if lora_item.get("name")
},
})
out_workflow_data = ensure_v2_recipe_data(
dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {},
source=source_name,
)
models_out = out_workflow_data.get("models", {})
if not isinstance(models_out, dict):
models_out = {}
out_workflow_data["models"] = models_out
has_existing_model_b = isinstance(models_out.get("model_b"), dict)
model_a_out = models_out.get("model_a") if isinstance(models_out.get("model_a"), dict) else {}
model_b_out = models_out.get("model_b") if isinstance(models_out.get("model_b"), dict) else {}
model_a_out["positive_prompt"] = output_text
model_a_out["loras"] = [
{
"name": lora.get("name", ""),
"path": lora.get("path", lora.get("name", "")),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
}
for lora in loras_a_display
if isinstance(lora, dict) and lora.get("name")
]
model_b_loras = [
{
"name": lora.get("name", ""),
"path": lora.get("path", lora.get("name", "")),
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": lora.get("available", True),
}
for lora in loras_b_display
if isinstance(lora, dict) and lora.get("name")
]
models_out["model_a"] = model_a_out
model_a_name = str(model_a_out.get("model", "") or "").strip()
model_b_name = str(model_b_out.get("model", "") or "").strip()
model_b_pos = str(model_b_out.get("positive_prompt", "") or "").strip()
model_b_neg = str(model_b_out.get("negative_prompt", "") or "").strip()
model_b_has_runtime = any(
model_b_out.get(key) is not None
for key in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
)
keep_model_b = bool(model_b_loras) or bool(model_b_pos) or bool(model_b_neg) or model_b_has_runtime
if model_b_name and model_b_name != model_a_name:
keep_model_b = True
if (has_existing_model_b and model_b_name and model_b_name == model_a_name and
not model_b_loras and not model_b_pos and not model_b_neg and not model_b_has_runtime):
keep_model_b = False
if incoming_has_model_b is False:
keep_model_b = False
if keep_model_b:
model_b_out["loras"] = model_b_loras
models_out["model_b"] = model_b_out
else:
models_out.pop("model_b", None)
if workflow_thumbnail:
out_workflow_data["thumbnail"] = workflow_thumbnail
out_workflow_data["_source"] = source_name
return (out_workflow_data,)
def check_lazy_status(self, category, name, text="", **kwargs):
return []
+393
View File
@@ -0,0 +1,393 @@
"""Multi-slot LoRA stacker outputting four independent LORA_STACK outputs (A/B/C/D)."""
import json
import importlib
import os
import sys
from ..py.lora_stacks import coerce_lora_stack, normalize_lora_slots
from ..py.lora_utils import resolve_lora_path
try:
from ..py.lora_utils import get_lora_relative_path
except Exception:
def get_lora_relative_path(lora_name):
return str(lora_name or ""), False
def _try_get_lm_get_lora_info():
"""Return LM's get_lora_info function when available."""
# First, try already-loaded modules.
for mod_name, mod in list(sys.modules.items()):
if mod is None:
continue
mod_dict = getattr(mod, "__dict__", None)
if not isinstance(mod_dict, dict):
continue
# Use module __dict__ lookup to avoid invoking module-level __getattr__.
fn = mod_dict.get("get_lora_info")
if callable(fn):
file_path = str(mod_dict.get("__file__") or "").lower()
has_absolute_variant = callable(mod_dict.get("get_lora_info_absolute"))
if "comfyui-lora-manager" in file_path or has_absolute_variant:
return fn
# If not loaded yet, try common module paths directly.
candidate_modules = (
"custom_nodes.ComfyUI_Lora_Manager.py.utils.utils",
"ComfyUI_Lora_Manager.py.utils.utils",
"py.utils.utils",
)
for module_name in candidate_modules:
try:
mod = importlib.import_module(module_name)
except Exception:
continue
fn = getattr(mod, "get_lora_info", None)
if callable(fn):
return fn
return None
def _build_lora_stack(loras_json):
"""
Build a LORA_STACK list from the JSON state persisted by the JS widget.
Each entry: {"name": str, "strength": float, "clipStrength": float, "active": bool}
Returns a list of (lora_path, model_strength, clip_strength) tuples.
"""
empty_result = ([], [])
if isinstance(loras_json, str):
raw = loras_json.strip()
if not raw or raw == "[]":
return empty_result
try:
loras = json.loads(raw)
except Exception:
return empty_result
elif isinstance(loras_json, dict) and "__value__" in loras_json:
loras = loras_json["__value__"]
elif isinstance(loras_json, list):
loras = loras_json
else:
return empty_result
if not isinstance(loras, list):
return empty_result
get_lora_info = _try_get_lm_get_lora_info()
stack = []
trigger_words = []
def _normalize_to_relative_lora(raw_value, fallback_name):
candidate = str(raw_value or "").strip()
if candidate:
rel_path, available = get_lora_relative_path(candidate)
if available and rel_path:
return rel_path
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
if candidate_base:
rel_path, available = get_lora_relative_path(candidate_base)
if available and rel_path:
return rel_path
fallback = str(fallback_name or "").strip()
if fallback:
rel_path, available = get_lora_relative_path(fallback)
if available and rel_path:
return rel_path
return fallback
for lora in loras:
if not isinstance(lora, dict):
continue
if not lora.get("active", True):
continue
name = str(lora.get("name", "")).strip()
if not name:
continue
try:
strength = float(lora.get("strength", 1.0))
except (TypeError, ValueError):
strength = 1.0
try:
clip_strength = float(lora.get("clipStrength", strength))
except (TypeError, ValueError):
clip_strength = strength
# Prefer LM's path resolver (has full cache); fall back to folder_paths scan.
lora_path = None
if get_lora_info is not None:
try:
result = get_lora_info(name)
if isinstance(result, tuple):
if len(result) >= 1 and result[0]:
lora_path = _normalize_to_relative_lora(result[0], name)
if len(result) >= 2:
raw_triggers = result[1]
if isinstance(raw_triggers, str):
token = raw_triggers.strip()
if token:
trigger_words.append(token)
elif isinstance(raw_triggers, (list, tuple, set)):
for trigger in raw_triggers:
token = str(trigger or "").strip()
if token:
trigger_words.append(token)
except Exception:
pass
if not lora_path:
resolved, available = resolve_lora_path(name)
lora_path = _normalize_to_relative_lora(resolved if (available and resolved) else name, name)
stack.append((lora_path, strength, clip_strength))
return stack, trigger_words
class MultiLoraStackerLM:
"""Multi-slot LoRA stacker with per-slot and combined stack outputs."""
NAME = "Multi Lora Stacker (LoraManager)"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# JSON arrays persisted by the JS loras widget – one per slot.
"loras_state_a": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_b": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_c": ("STRING", {"default": "[]", "multiline": True}),
"loras_state_d": ("STRING", {"default": "[]", "multiline": True}),
},
"optional": {
"stack_count": ("INT", {
"default": 2,
"min": 1,
"max": 4,
"tooltip": "Number of LoRA stacks to expose and combine.",
}),
},
}
RETURN_TYPES = ("MULTI_LORA_STACK", "LORA_STACK", "STRING")
RETURN_NAMES = ("multi_lora_stack", "lora_stack", "trigger_words")
FUNCTION = "stack_multi"
DESCRIPTION = (
"Multi-slot LoRA stacker with a visual 4-panel UI (A / B / C / D). "
"Outputs one MULTI_LORA_STACK payload plus one combined LORA_STACK "
"containing A+B+C+D in order."
)
def stack_multi(
self,
loras_state_a="[]",
loras_state_b="[]",
loras_state_c="[]",
loras_state_d="[]",
stack_count=2,
**kwargs,
):
stack_a, triggers_a = _build_lora_stack(loras_state_a)
stack_b, triggers_b = _build_lora_stack(loras_state_b)
stack_c, triggers_c = _build_lora_stack(loras_state_c)
stack_d, triggers_d = _build_lora_stack(loras_state_d)
count = max(1, min(4, int(stack_count or 2)))
slot_stacks = [stack_a, stack_b, stack_c, stack_d]
slot_triggers = [triggers_a, triggers_b, triggers_c, triggers_d]
slot_keys = ["a", "b", "c", "d"]
multi_lora_stack = {}
combined_lora_stack = []
trigger_words = []
for i in range(4):
if i < count:
multi_lora_stack[slot_keys[i]] = slot_stacks[i]
combined_lora_stack.extend(slot_stacks[i])
trigger_words.extend(slot_triggers[i])
else:
multi_lora_stack[slot_keys[i]] = []
trigger_words_text = ",, ".join(trigger_words) if trigger_words else ""
return (multi_lora_stack, combined_lora_stack, trigger_words_text)
class MultiLoraCombine:
"""Combine optional multi stack + optional A/B/C/D stacks into one MULTI_LORA_STACK."""
NAME = "Multi LoRA Combine"
CATEGORY = "Prompt Manager"
DEPRECATED = True
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"multi_lora_stack": ("MULTI_LORA_STACK", {
"tooltip": "Optional existing MULTI_LORA_STACK to merge into.",
}),
"lora_stack_a": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot A.",
}),
"lora_stack_b": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot B.",
}),
"lora_stack_c": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot C.",
}),
"lora_stack_d": ("LORA_STACK", {
"tooltip": "Optional stack to append to slot D.",
}),
},
}
RETURN_TYPES = ("MULTI_LORA_STACK",)
RETURN_NAMES = ("multi_lora_stack",)
FUNCTION = "combine_multi"
DESCRIPTION = (
"Combine an optional MULTI_LORA_STACK with optional LORA_STACK A/B/C/D "
"inputs and output one MULTI_LORA_STACK payload."
)
def combine_multi(
self,
multi_lora_stack=None,
lora_stack_a=None,
lora_stack_b=None,
lora_stack_c=None,
lora_stack_d=None,
**kwargs,
):
# A plain LoRA stack (the Prompt Manager's when one slot has LoRAs) is slot A.
slots = normalize_lora_slots(multi_lora_stack, "a")
out_a, out_b, out_c, out_d = (slots[slot] for slot in "abcd")
# Append separate stack inputs to each slot (if connected).
out_a.extend(coerce_lora_stack(lora_stack_a))
out_b.extend(coerce_lora_stack(lora_stack_b))
out_c.extend(coerce_lora_stack(lora_stack_c))
out_d.extend(coerce_lora_stack(lora_stack_d))
merged = {
"a": out_a,
"b": out_b,
"c": out_c,
"d": out_d,
}
return (merged,)
class MultiLoraSplitter:
"""Split one MULTI_LORA_STACK payload into A/B/C/D LORA_STACK outputs."""
NAME = "Multi LoRA Splitter"
CATEGORY = "Prompt Manager"
DEPRECATED = True
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"multi_lora_stack": ("MULTI_LORA_STACK", {
"tooltip": "Input MULTI_LORA_STACK payload to split into A/B/C/D stacks.",
}),
},
}
RETURN_TYPES = ("LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK")
RETURN_NAMES = ("lora_stack_a", "lora_stack_b", "lora_stack_c", "lora_stack_d")
FUNCTION = "split_multi"
DESCRIPTION = "Split a MULTI_LORA_STACK payload into LORA_STACK outputs A/B/C/D."
def split_multi(self, multi_lora_stack, **kwargs):
# A plain LoRA stack (the Prompt Manager's when one slot has LoRAs) is slot A.
slots = normalize_lora_slots(multi_lora_stack, "a")
return tuple(slots[slot] for slot in "abcd")
class MultiLoraRelay:
"""LoRA stacks in and out as one set of slots A-D and as four plain stacks: a stack wired to a slot is appended
to it, so the node combines and splits, and passes through on both ends like Recipe Relay."""
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
slots = {f"lora_stack_{slot}": ("LORA_STACK", {"tooltip": f"Appended to slot {slot.upper()}."}) for slot in "abcd"}
return {
"required": {},
"optional": {
"lora_stacks": ("LORA_STACK,MULTI_LORA_STACK", {
"tooltip": "LoRA stacks for slots A-D, from a Prompt Manager or another relay; a plain LoRA stack is slot A.",
}),
**slots,
},
}
RETURN_TYPES = ("MULTI_LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK")
RETURN_NAMES = ("lora_stacks", "lora_stack_a", "lora_stack_b", "lora_stack_c", "lora_stack_d")
FUNCTION = "relay"
DESCRIPTION = "Combine and split LoRA stacks: slots A-D come in as one set and as separate stacks, and go out both ways."
def relay(self, lora_stacks=None, lora_stack_a=None, lora_stack_b=None, lora_stack_c=None, lora_stack_d=None):
incoming = normalize_lora_slots(lora_stacks, "a")
added = {"a": lora_stack_a, "b": lora_stack_b, "c": lora_stack_c, "d": lora_stack_d}
out = {slot: incoming[slot] + coerce_lora_stack(added[slot]) for slot in "abcd"}
return (out, out["a"], out["b"], out["c"], out["d"])
class LoraStackCombine:
"""Combine up to four LORA_STACK inputs into one merged LORA_STACK output."""
NAME = "LoRA Stack Combine"
CATEGORY = "Prompt Manager"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"lora_stack_a": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append first.",
}),
"lora_stack_b": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append second.",
}),
"lora_stack_c": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append third.",
}),
"lora_stack_d": ("LORA_STACK", {
"tooltip": "Optional LORA_STACK to append fourth.",
}),
},
}
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("lora_stack",)
FUNCTION = "combine_lora_stacks"
DESCRIPTION = "Combine up to four LORA_STACK inputs into one LORA_STACK output."
def combine_lora_stacks(
self,
lora_stack_a=None,
lora_stack_b=None,
lora_stack_c=None,
lora_stack_d=None,
**kwargs,
):
merged = []
merged.extend(coerce_lora_stack(lora_stack_a))
merged.extend(coerce_lora_stack(lora_stack_b))
merged.extend(coerce_lora_stack(lora_stack_c))
merged.extend(coerce_lora_stack(lora_stack_d))
return (merged,)
+33
View File
@@ -0,0 +1,33 @@
"""Bundled multi-slot helper node for Recipe Builder."""
import json
class RecipeBuilderMultiPrompts:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
"optional": {
"model_a": ("STRING", {"forceInput": True}),
"model_b": ("STRING", {"forceInput": True}),
"model_c": ("STRING", {"forceInput": True}),
"model_d": ("STRING", {"forceInput": True}),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("multi_prompt",)
FUNCTION = "bundle"
CATEGORY = "Prompt Manager"
DESCRIPTION = "Bundle model_a/model_b/model_c/model_d prompts into a JSON string payload."
def bundle(self,
model_a="", model_b="", model_c="", model_d=""):
payload = {
"model_a": str(model_a or ""),
"model_b": str(model_b or ""),
"model_c": str(model_c or ""),
"model_d": str(model_d or ""),
}
return (json.dumps(payload, ensure_ascii=True),)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
from .prompt_generator import PromptGenerator, _preferences_cache, ollama_unload_model
class PromptGeneratorKillSwitch:
"""Pass-through node that also stops the local llm server."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"value": ("*", {"forceInput": True, "tooltip": "Any input value to pass through unchanged."}),
}
}
RETURN_TYPES = ("*",)
RETURN_NAMES = ("value",)
FUNCTION = "pass_and_kill"
CATEGORY = "Prompt Manager"
DESCRIPTION = "Pass-through any value, stop Prompt Generator's llama.cpp server, and unload all Ollama models from memory."
@classmethod
def VALIDATE_INPUTS(cls, **kwargs):
return True
def pass_and_kill(self, value):
PromptGenerator.stop_server()
ok, msg = ollama_unload_model(_preferences_cache)
if msg:
print(f"Prompt Generator Kill Switch: {msg}")
return (value,)
@@ -1,5 +1,5 @@
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
from .ollama_wrapper import discover_ollama_models, is_ollama_available
from ..py.model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
from ..py.ollama_wrapper import discover_ollama_models, is_ollama_available
import time
# Global timestamp to track when models were last updated
@@ -10,12 +10,47 @@ def trigger_model_list_refresh():
global _last_model_update
_last_model_update = time.time()
def get_default_context_size():
"""Return a context size scaled to the active GPU's total VRAM.
Tiers:
>= 24 GB → 8192
>= 16 GB → 4096
< 16 GB → 2048
No GPU / unknown → 4096 (safe CPU default)
Note:
This uses GPU capacity (total VRAM), not current free/available VRAM.
"""
try:
import importlib
torch = importlib.import_module("torch")
if torch.cuda.is_available():
try:
device_index = torch.cuda.current_device()
except Exception:
device_index = 0
total_vram_gb = torch.cuda.get_device_properties(device_index).total_memory / (1024 ** 3)
if total_vram_gb >= 24:
return 8192
elif total_vram_gb >= 16:
return 4096
else:
return 2048
except Exception:
pass
return 4096 # CPU or VRAM detection failed
class PromptGenOptions:
"""Node that provides optional configuration for llama.cpp servers"""
@classmethod
def INPUT_TYPES(cls):
backend = _preferences_cache.get("llm_backend", "llama.cpp")
preferred_model = str(_preferences_cache.get("preferred_model", "") or "").strip()
hide_downloadable_models = _preferences_cache.get("hide_downloadable_models", False) is True
if backend == "ollama":
# Discover models from Ollama
@@ -27,13 +62,27 @@ class PromptGenOptions:
else:
available_models = get_all_models()
if not available_models:
available_models = ["No models found - check HuggingFace"]
if hide_downloadable_models:
available_models = ["No local models found - add a .gguf or disable 'Hide downloadable built-in models'"]
else:
available_models = ["No models found - check HuggingFace"]
default_model = available_models[0] if available_models else ""
if preferred_model and preferred_model in available_models:
default_model = preferred_model
if backend == "ollama":
model_tooltip = "Select the Ollama model to use."
elif hide_downloadable_models:
model_tooltip = "Select a locally available model. Built-in HuggingFace download entries are hidden by the Prompt Manager preference."
else:
model_tooltip = "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
return {
"optional": {
"model": (available_models, {
"default": available_models[0] if available_models else "",
"tooltip": "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
"default": default_model,
"tooltip": model_tooltip
}),
"image2": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
@@ -47,6 +96,10 @@ class PromptGenOptions:
"image5": ("IMAGE", {
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
}),
"system_prompt_mode": (["replace", "append"], {
"default": "append",
"tooltip": "replace: the text below fully replaces the default LLM instructions\nappend: the text below is added after the default LLM instructions"
}),
"system_prompt": ("STRING", {
"multiline": True,
"default": "",
@@ -54,25 +107,25 @@ class PromptGenOptions:
"tooltip": "Custom LLM Instructions (leave empty to use default)\nThe default instructions are designed for generating\ndetailed and imaginative prompts for text-to-image generation."
}),
"use_model_default_sampling": ("BOOLEAN", {
"default": False,
"default": True,
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
}),
"temperature": ("FLOAT", {
"default": 0.8,
"default": 0.7,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
}),
"top_k": ("INT", {
"default": 40,
"default": 20,
"min": 0,
"max": 100,
"step": 1,
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
}),
"top_p": ("FLOAT", {
"default": 0.95,
"default": 0.9,
"min": 0.0,
"max": 1.0,
"step": 0.01,
@@ -93,7 +146,7 @@ class PromptGenOptions:
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
}),
"context_size": ("INT", {
"default": 4096,
"default": get_default_context_size(),
"min": 512,
"max": 32768,
"step": 512,
@@ -102,11 +155,23 @@ class PromptGenOptions:
"show_everything_in_console": ("BOOLEAN", {
"default": False,
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
}),
"max_length": ("INT", {
"default": 512,
"min": 1,
"max": 32768,
"step": 1,
"tooltip": "Maximum number of tokens to generate when the Prompt Generator is connected to a CLIP/text encoder."
}),
"gpu_device": ("STRING", {
"default": "",
"tooltip": "GPU device index for llama.cpp (e.g. '0', '1').\nLeave empty to use the system default GPU.\nUseful with multi-GPU setups to control which GPU loads LLM weights."
})
}
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Configure LLM model, sampling parameters, and system prompt for the Prompt Generator."
RETURN_TYPES = ("OPTIONS",)
RETURN_NAMES = ("options",)
FUNCTION = "create_options"
@@ -117,12 +182,42 @@ class PromptGenOptions:
return _last_model_update
def create_options(self, model: str = None, image2=None, image3=None, image4=None, image5=None,
system_prompt: str = None, use_model_default_sampling: bool = None, temperature: float = None,
system_prompt: str = None, system_prompt_mode: str = "replace",
use_model_default_sampling: bool = None, temperature: float = None,
top_k: int = None, top_p: float = None, min_p: float = None,
repeat_penalty: float = None, context_size: int = None,
show_everything_in_console: bool = None) -> dict:
show_everything_in_console: bool = None, max_length: int = None,
gpu_device: str = None) -> dict:
"""Create options dictionary with model, LLM parameters, and extra images"""
# Backward compatibility for workflows saved before `system_prompt_mode` existed.
# Old widget arrays can shift values by one slot when loaded by newer node definitions.
mode_valid = system_prompt_mode in ("replace", "append")
legacy_shape = isinstance(system_prompt, bool) and (
not mode_valid or isinstance(use_model_default_sampling, (int, float))
)
if legacy_shape:
old_system_prompt = system_prompt_mode
old_use_default_sampling = system_prompt
old_temperature = use_model_default_sampling
old_top_k = temperature
old_top_p = top_k
old_min_p = top_p
old_repeat_penalty = min_p
old_context_size = repeat_penalty
old_show_console = context_size
system_prompt_mode = "replace"
system_prompt = old_system_prompt if isinstance(old_system_prompt, str) else ""
use_model_default_sampling = bool(old_use_default_sampling) if old_use_default_sampling is not None else None
temperature = old_temperature
top_k = old_top_k
top_p = old_top_p
min_p = old_min_p
repeat_penalty = old_repeat_penalty
context_size = old_context_size
show_everything_in_console = bool(old_show_console) if old_show_console is not None else None
options = {}
# Handle model selection and download if needed
@@ -173,6 +268,7 @@ class PromptGenOptions:
# Only include LLM parameters that are provided
if system_prompt and system_prompt.strip():
options["system_prompt"] = system_prompt
options["system_prompt_mode"] = system_prompt_mode
options["use_model_default_sampling"] = use_model_default_sampling
options["temperature"] = temperature
@@ -182,14 +278,14 @@ class PromptGenOptions:
options["repeat_penalty"] = repeat_penalty
options["context_size"] = context_size
options["show_everything_in_console"] = show_everything_in_console
options["max_length"] = max_length
# GPU device: use node input if provided, otherwise fall back to global preference
gpu_device_value = None
if gpu_device is not None and str(gpu_device).strip():
gpu_device_value = str(gpu_device).strip()
elif _preferences_cache.get("llama_gpu_device", ""):
gpu_device_value = _preferences_cache["llama_gpu_device"]
options["gpu_device"] = gpu_device_value
return (options,)
NODE_CLASS_MAPPINGS = {
"PromptGenOptions": PromptGenOptions
}
NODE_DISPLAY_NAME_MAPPINGS = {
"PromptGenOptions": "Prompt Generator Options"
}
+551
View File
@@ -0,0 +1,551 @@
"""
Prompt Layout Builder - draw a MOSS-Image layout (scene prompt + boxed regions) or load one from an LLM.
The editor stores boxes as canvas fractions {x, y, w, h, type, text, desc, palette} in the layout_data widget.
The prompt output follows output_format: the native MOSS-Image layout JSON (bbox in pixels from the canvas centre,
yxyx, the same format as MOSS-Image Layout Prompt), an Ideogram 4 JSON caption (0-1000 yxyx elements, as Build JSON
Prompt (Ideogram)) or the Krea 2 grounding lines of jimmycarter/krea2-turbo-bbox (x-first 0-1000 boxes).
import_json accepts the MOSS
format, percent or 0-1000 yxyx layouts written by
an LLM, Ideogram 4 captions, Krea 2 grounding lines, and the elements list from Create Bounding Boxes. The two converter nodes translate layouts to and from the
core BOUNDING_BOX / elements types so the builder can be chained with other box nodes.
"""
import json
import math
import re
import numpy as np
from PIL import Image
import comfy.utils
import nodes
from comfy_extras.nodes_bounding_boxes import (
boxes_from_input,
build_elements,
fractions_to_pixels,
pixels_to_fractions,
render_preview,
)
from comfy_extras.nodes_resolution import ASPECT_RATIOS
from ..py.workflow_data_utils import build_v2_recipe_data_from_prompt
REF_RATIO = "Use Reference Ratio"
# manager_data key holding the editor state, next to Prompt Composer's "prompt_composer".
LAYOUT_RECIPE_KEY = "prompt_layout"
SIZE_MULTIPLE = 16
CANVASES = ("single", "multi_panel", "collage")
BOX_TYPES = ("object", "character", "text", "panel")
BOX_PALETTE_MAX = 8
SUMMARY_PALETTE_MAX = 16
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
RELATIVE_SPACES = {"percent": 100.0, "relative_1000": 1000.0}
OUTPUT_FORMATS = ("MOSS", "Ideogram", "Krea 2")
# Krea 2 character tags: person, anime character, furry / anthro character.
KREA_CHARACTER_TAGS = ("pe", "ac", "fc")
KREA_CHARACTER_ID = re.compile(r"[a-z0-9_]+")
def _resolution(aspect_ratio, megapixels, ref_size):
if aspect_ratio != REF_RATIO:
w_ratio, h_ratio = ASPECT_RATIOS[aspect_ratio]
else:
w_ratio, h_ratio = ref_size or (1, 1)
scale = math.sqrt(megapixels * 1024 * 1024 / (w_ratio * h_ratio))
return tuple(max(SIZE_MULTIPLE, round(r * scale / SIZE_MULTIPLE) * SIZE_MULTIPLE) for r in (w_ratio, h_ratio))
def _strs(value):
if isinstance(value, str):
value = re.split(r"[,\n]", value)
return [str(v).strip() for v in (value if isinstance(value, list) else []) if str(v).strip()]
def _palette(value, limit):
return [c.upper() for c in _strs(value) if HEX_COLOR.fullmatch(c)][:limit]
def _clean_box(raw):
x, y, w, h = (float(raw.get(k) or 0.0) for k in ("x", "y", "w", "h"))
x1, x2 = sorted((x, x + w))
y1, y2 = sorted((y, y + h))
x1, y1, x2, y2 = (min(1.0, max(0.0, v)) for v in (x1, y1, x2, y2))
box_type = raw.get("type") if raw.get("type") in BOX_TYPES else "object"
box = {
"x": x1, "y": y1, "w": x2 - x1, "h": y2 - y1,
"type": box_type,
"text": str(raw.get("text") or "") if box_type == "text" else "",
"desc": str(raw.get("desc") or ""),
"palette": _palette(raw.get("palette"), BOX_PALETTE_MAX),
}
ref = raw.get("prompt_ref")
if isinstance(ref, dict) and ref.get("name"):
box["prompt_ref"] = {"category": str(ref.get("category") or ""), "name": str(ref["name"])}
if box_type == "character":
if raw.get("krea_tag") in KREA_CHARACTER_TAGS:
box["krea_tag"] = raw["krea_tag"]
char_id = str(raw.get("char_id") or "").strip().lower()
if KREA_CHARACTER_ID.fullmatch(char_id):
box["char_id"] = char_id
return box
def _find_layout(text):
# LLM output may wrap the JSON in prose or a code fence: take the first layout-shaped value.
decoder = json.JSONDecoder()
for match in re.finditer(r"[{\[]", text):
try:
value, _ = decoder.raw_decode(text, match.start())
except json.JSONDecodeError:
continue
if isinstance(value, dict) and isinstance(value.get("items"), list):
return value
if isinstance(value, list) and value and all(isinstance(v, dict) and "bbox" in v and "type" in v for v in value):
return {"items": value, "bbox_coord_space": "relative_1000"}
raise ValueError('Prompt Layout Builder: import_json has no layout (an object with "items", or a list of elements).')
KREA_ELEMENT = re.compile(r"(p|o|t|pe|ac|fc)(?::([a-z0-9_]+))?\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]\s*(.*)")
KREA_TEXT = re.compile(r'"((?:[^"\\]|\\.)*)"\s*(.*)')
KREA_BOX_TYPES = {"p": "panel", "o": "object", "t": "text", "pe": "character", "ac": "character", "fc": "character"}
def _parse_krea(text):
# Krea 2 grounding lines (krea2-turbo-bbox); None when the text has no element, @ or ~ line.
fence = re.search(r"```[^\n]*\n(.*?)```", text, re.S)
lines = [line.strip() for line in (fence.group(1) if fence else text).splitlines() if line.strip()]
summary, fields, boxes, grounded = "", {}, [], False
for line in lines:
element = KREA_ELEMENT.fullmatch(line)
if element:
tag, char_id, rest = element.group(1), element.group(2), element.group(7)
x0, y0, x1, y1 = (float(element.group(i)) / 1000 for i in range(3, 7))
box = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "type": KREA_BOX_TYPES[tag], "desc": rest}
if tag == "t":
quoted = KREA_TEXT.match(rest)
if quoted:
box["text"] = re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), quoted.group(1))
box["desc"] = quoted.group(2)
if box["type"] == "character":
box.update(krea_tag=tag, char_id=char_id)
boxes.append(_clean_box(box))
grounded = True
elif line.startswith("@"):
head, sep, tail = line[1:].rpartition(";")
fields["style"], fields["medium"] = (head.strip(), tail.strip()) if sep else (tail.strip(), "")
grounded = True
elif line.startswith("~"):
fields["background"] = line[1:].strip()
grounded = True
elif not summary and not grounded:
summary = line
return {"prompt": summary, "krea": fields, "boxes": boxes} if grounded else None
def _parse_ideogram(text):
# Ideogram 4 JSON caption (Build JSON Prompt (Ideogram)); None when the text has none.
decoder = json.JSONDecoder()
for match in re.finditer(r"\{", text):
try:
caption, _ = decoder.raw_decode(text, match.start())
except json.JSONDecodeError:
continue
if isinstance(caption, dict) and isinstance(caption.get("compositional_deconstruction"), dict):
break
else:
return None
scene = caption["compositional_deconstruction"]
style = caption.get("style_description") if isinstance(caption.get("style_description"), dict) else {}
text_of = lambda value: str(value or "").strip()
fields = {"background": text_of(scene.get("background"))}
if style:
kind = "art_style" if "art_style" in style else "photo" if "photo" in style else (
"photo" if text_of(style.get("medium")).lower() == "photograph" else "art_style")
fields.update(style=kind, style_detail=text_of(style.get(kind)), aesthetics=text_of(style.get("aesthetics")),
lighting=text_of(style.get("lighting")), medium=text_of(style.get("medium")))
elements = [e for e in scene.get("elements") or [] if isinstance(e, dict)]
return {
"prompt": text_of(caption.get("high_level_description")),
"ideogram": fields,
"palette": _palette(style.get("color_palette"), SUMMARY_PALETTE_MAX),
"boxes": _import_boxes({"items": elements, "bbox_coord_space": "relative_1000"}, 1, 1),
}
def _parse_text_layout(text, width, height, label):
parsed = _parse_krea(text) or _parse_ideogram(text)
if parsed:
return parsed
try:
layout = _find_layout(text)
except ValueError:
received = " ".join(text.split())
raise ValueError(f"{label} has no layout. Expected layout JSON (an object with \"items\" or a list of elements), "
"an Ideogram 4 caption or Krea 2 grounding lines; check the Prompt Generator system prompt. "
f"Received: {received[:200]!r}{'...' if len(received) > 200 else ''}") from None
return {"layout": layout, "boxes": _import_boxes(layout, width, height)}
def _boxes_from_bboxes(bboxes, width, height):
boxes = []
for raw in boxes_from_input(bboxes, width, height):
metadata = raw.get("metadata") or {}
box_type = "text" if metadata.get("type") == "text" else "character" if metadata.get("is_character") else "object"
boxes.append(_clean_box({
**pixels_to_fractions(raw, width, height),
"type": box_type,
"text": metadata.get("text"),
"desc": metadata.get("desc"),
"palette": metadata.get("palette"),
}))
return boxes
def _import_boxes(layout, width, height):
space = str(layout.get("bbox_coord_space") or "abs_centralized")
if space != "abs_centralized" and space not in RELATIVE_SPACES:
raise ValueError(f"Prompt Layout Builder: unsupported bbox_coord_space {space!r} "
"(expected percent, relative_1000 or abs_centralized).")
if str(layout.get("bbox_format") or "yxyx") != "yxyx":
raise ValueError('Prompt Layout Builder: bbox_format must be "yxyx" (top, left, bottom, right).')
boxes = []
for index, item in enumerate(layout["items"], 1):
if not isinstance(item, dict):
continue
try:
top, left, bottom, right = (float(v) for v in item.get("bbox"))
except (TypeError, ValueError):
raise ValueError(f"Prompt Layout Builder: item {index} needs a bbox [top, left, bottom, right].")
if space == "abs_centralized":
top, bottom = ((v + height // 2) / height for v in (top, bottom))
left, right = ((v + width // 2) / width for v in (left, right))
else:
top, left, bottom, right = (v / RELATIVE_SPACES[space] for v in (top, left, bottom, right))
boxes.append(_clean_box({
"x": left, "y": top, "w": right - left, "h": bottom - top,
"type": item.get("label", item.get("type")),
"text": item.get("text"),
"desc": item.get("caption", item.get("desc")),
"palette": item.get("palette", item.get("color_palette")),
}))
return boxes
def _moss_bbox(box, width, height):
# Same rounding as MOSS-Image Layout Prompt: pixel edges enclosing the box, origin at the canvas centre.
hx, hy = width // 2, height // 2
return [math.floor(round(box["y"] * height, 9)) - hy, math.floor(round(box["x"] * width, 9)) - hx,
math.ceil(round((box["y"] + box["h"]) * height, 9)) - hy, math.ceil(round((box["x"] + box["w"]) * width, 9)) - hx]
def _layout_prompt(prompt, meta, canvas, palette, boxes, width, height):
items = []
for box in boxes:
item = {"label": "object" if box["type"] == "panel" else box["type"], "caption": box["desc"]}
if box["type"] == "text":
item["text"] = box["text"]
if box["palette"]:
item["palette"] = box["palette"]
item["bbox"] = _moss_bbox(box, width, height)
items.append(item)
if not items:
return prompt
summary = {}
if meta:
summary["meta"] = meta
if canvas in CANVASES:
summary["canvas"] = canvas
summary["caption"] = prompt.strip()
if palette:
summary["palette"] = palette
layout = {"summary": summary, "items": items, "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"}
return json.dumps(layout, ensure_ascii=False, separators=(",", ":"))
def _ideogram_prompt(prompt, palette, boxes, fields):
# Same caption as Ideogram 4 Prompt Builder KJ: compact JSON, and every style key in order once a style is set.
fields = fields if isinstance(fields, dict) else {}
text = lambda key: str(fields.get(key) or "")
caption = {}
if prompt.strip():
caption["high_level_description"] = prompt.strip()
style = fields.get("style")
if style in ("photo", "art_style"):
style_description = {"aesthetics": text("aesthetics"), "lighting": text("lighting")}
if style == "photo":
style_description.update(photo=text("style_detail"), medium=text("medium"))
else:
style_description.update(medium=text("medium"), art_style=text("style_detail"))
if palette:
style_description["color_palette"] = palette
caption["style_description"] = style_description
caption["compositional_deconstruction"] = {"background": text("background"), "elements": build_elements(boxes)}
return json.dumps(caption, ensure_ascii=False, separators=(",", ":"))
def _format_prompt(output_format, prompt, meta, canvas, palette, boxes, width, height, ideogram=None, krea=None):
if output_format == "Ideogram":
return _ideogram_prompt(prompt, palette, boxes, ideogram)
if output_format == "Krea 2":
return _krea_prompt(prompt, boxes, krea)
if not boxes:
return prompt
return _layout_prompt(prompt, meta, canvas, palette, boxes, width, height)
def _one_line(text):
return " ".join(str(text or "").split())
def _krea_prompt(prompt, boxes, fields):
# Grounding DSL from jimmycarter/krea2-turbo-bbox PROMPTING.md: summary, @style; medium, ~background, one line per box.
fields = fields if isinstance(fields, dict) else {}
lines = []
if _one_line(prompt):
lines.append(_one_line(prompt))
style_line = "; ".join(part for part in (_one_line(fields.get("style")), _one_line(fields.get("medium"))) if part)
if style_line:
lines.append("@" + style_line)
if _one_line(fields.get("background")):
lines.append("~" + _one_line(fields.get("background")))
# Panels first, as in the training data; the rest keep the editor order.
for box in sorted(boxes, key=lambda b: b["type"] != "panel"):
bbox = ",".join(str(round(v * 1000)) for v in (box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))
if box["type"] == "character":
head = box.get("krea_tag", "pe") + (f":{box['char_id']}" if box.get("char_id") else "")
else:
head = {"panel": "p", "text": "t"}.get(box["type"], "o")
line = f"{head}[{bbox}]"
if box["type"] == "text":
escaped = box["text"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
line += f'"{escaped}"'
if _one_line(box["desc"]):
line += " " + _one_line(box["desc"])
lines.append(line)
return "\n".join(lines)
def _fit_background(image, width, height):
samples = image[:1, :, :, :3].movedim(-1, 1)
return comfy.utils.common_upscale(samples, width, height, "lanczos", "center").movedim(1, -1)
def _manager_data(layout_prompt, state, width, height):
data = build_v2_recipe_data_from_prompt(prompt_text=layout_prompt, source="PromptLayoutBuilder")
data["models"]["model_a"]["resolution"].update(width=width, height=height)
data[LAYOUT_RECIPE_KEY] = {
**state,
"width": width,
"height": height,
"composer_prompts": [
{"box": index, **box["prompt_ref"]} for index, box in enumerate(state["boxes"], 1) if box.get("prompt_ref")
],
}
return data
def _pixel_frame(boxes, width, height):
# Pixel boxes carrying the metadata Create Bounding Boxes and Vantage read back.
frame = []
for box in boxes:
metadata = {"type": "text" if box["type"] == "text" else "obj", "text": box["text"], "desc": box["desc"],
"palette": box["palette"]}
if box["type"] == "character":
metadata["is_character"] = True
frame.append({**fractions_to_pixels(box, width, height), "metadata": metadata})
return [frame] if frame else []
def _percent_item(box):
item = {"label": box["type"], "caption": box["desc"]}
if box["type"] == "text":
item["text"] = box["text"]
if box["palette"]:
item["palette"] = box["palette"]
item["bbox"] = [round(v * 100, 1) for v in (box["y"], box["x"], box["y"] + box["h"], box["x"] + box["w"])]
return item
_SIZE_INPUT = {"default": 1024, "min": 16, "max": 16384, "step": 8,
"tooltip": "Canvas size the pixel boxes refer to, e.g. the layout builder's width/height outputs."}
class BboxConverter:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"width": ("INT", _SIZE_INPUT),
"height": ("INT", _SIZE_INPUT),
"use_bboxes": ("BOOLEAN", {
"default": False,
"label_on": "bboxes",
"label_off": "layout_json",
"tooltip": "Input to convert when both are connected (shown only then).",
}),
},
"optional": {
"layout_json": ("STRING", {
"forceInput": True,
"tooltip": "Layout JSON (MOSS-native, percent or 0-1000 boxes), an Ideogram 4 caption or Krea 2 "
"grounding lines. Passed through to the layout_json output.",
}),
"bboxes": ("BOUNDING_BOX,ARRAY,STRING", {
"forceInput": True,
"tooltip": "Bounding boxes, Create Bounding Boxes elements, or their JSON.",
}),
},
}
RETURN_TYPES = ("STRING", "BOUNDING_BOX", "ARRAY")
RETURN_NAMES = ("layout_json", "bboxes", "elements")
FUNCTION = "convert"
CATEGORY = "Prompt Manager"
DESCRIPTION = ("Convert between a layout JSON and bounding boxes. Outputs the layout JSON (percent boxes when "
"converting bboxes), pixel bounding boxes and Create Bounding Boxes elements.")
def convert(self, width, height, use_bboxes=False, layout_json=None, bboxes=None):
if bboxes is not None and (use_bboxes or layout_json is None):
boxes = _boxes_from_bboxes(bboxes, width, height)
layout_json = json.dumps({"items": [_percent_item(box) for box in boxes], "bbox_coord_space": "percent",
"bbox_format": "yxyx"}, ensure_ascii=False, indent=2)
elif layout_json is not None:
boxes = _parse_text_layout(layout_json, width, height, "Bbox Converter: layout_json")["boxes"]
else:
raise ValueError("Bbox Converter: connect layout_json or bboxes.")
return (layout_json, _pixel_frame(boxes, width, height), build_elements(boxes))
class PromptLayoutBuilder:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"aspect_ratio": ([REF_RATIO, *(ratio.value for ratio in ASPECT_RATIOS)], {
"default": "1:1 (Square)",
"tooltip": "Canvas aspect ratio. 'Use Reference Ratio' follows a layout restored from manager_data, "
"otherwise the connected image.",
}),
"megapixels": ("FLOAT", {
"default": 1.0, "min": 0.1, "max": 16.0, "step": 0.1,
"tooltip": "Target canvas size; width and height are rounded to multiples of 16.",
}),
"prompt": ("STRING", {
"multiline": True,
"default": "",
"placeholder": "Scene description (summary caption)",
"dynamicPrompts": False,
"tooltip": "Description of the whole image and its style.",
}),
"meta": ("STRING", {
"default": "",
"tooltip": "Comma-separated style tags for summary.meta, e.g. \"poster, graphic design\" (blank = omitted).",
}),
"canvas": (["none", *CANVASES], {
"default": "none",
"tooltip": "summary.canvas: single image, multi_panel or collage (none = omitted).",
}),
"use_import_json": ("BOOLEAN", {
"default": False,
"tooltip": "Read the layout from import_json and lock the editor. Turn off to edit the imported boxes.",
}),
"layout_data": ("STRING", {"default": "{}", "tooltip": "Editor boxes (managed by the node UI)."}),
"output_format": (list(OUTPUT_FORMATS), {
"default": "MOSS",
"tooltip": "Prompt format: MOSS-Image layout JSON, Ideogram 4 JSON caption or Krea 2 grounding lines.",
}),
},
"optional": {
"image": ("IMAGE", {"tooltip": "Background for the editor; also sets the ratio with 'Use Reference Ratio'."}),
"import_json": ("STRING,MANAGER_DATA", {
"forceInput": True,
"lazy": True,
"tooltip": "Layout JSON (e.g. from Prompt Generator: percent, 0-1000 or MOSS-native boxes), an "
"Ideogram 4 caption, Krea 2 grounding lines, or a saved "
"layout's manager_data from Library Manager. Only evaluated when use_import_json is on.",
}),
},
}
RETURN_TYPES = ("STRING", "IMAGE", "INT", "INT", "MANAGER_DATA")
RETURN_NAMES = ("prompt", "preview", "width", "height", "manager_data")
FUNCTION = "build"
CATEGORY = "Prompt Manager"
OUTPUT_NODE = True
DESCRIPTION = ("Draw layout boxes over a scene prompt, or load them from an LLM layout. "
"Outputs a MOSS-Image, Ideogram 4 or Krea 2 prompt.")
def check_lazy_status(self, use_import_json, **kwargs):
return ["import_json"] if use_import_json else []
def build(self, aspect_ratio, megapixels, prompt, meta, canvas, use_import_json, layout_data,
image=None, import_json=None, output_format="MOSS"):
saved = None
if use_import_json and isinstance(import_json, dict):
saved = import_json.get(LAYOUT_RECIPE_KEY)
if not isinstance(saved, dict):
raise ValueError("Prompt Layout Builder: this manager_data has no layout (it comes from Prompt Manager or Prompt Composer).")
text_import = use_import_json and isinstance(import_json, str) and import_json.strip()
if saved and saved.get("width") and saved.get("height"):
ref_size = (int(saved["width"]), int(saved["height"]))
elif image is not None:
ref_size = (int(image.shape[2]), int(image.shape[1]))
else:
ref_size = None
width, height = _resolution(aspect_ratio, megapixels, ref_size)
state = saved if saved else json.loads(layout_data or "{}")
boxes = [_clean_box(box) for box in state.get("boxes", []) if isinstance(box, dict)]
palette = _palette(state.get("palette"), SUMMARY_PALETTE_MAX)
ideogram = state.get("ideogram") if isinstance(state.get("ideogram"), dict) else {}
krea = state.get("krea") if isinstance(state.get("krea"), dict) else {}
meta_tags = _strs(meta)
ui = {}
if saved:
prompt = str(saved.get("prompt") or "")
meta_tags = _strs(saved.get("meta"))
canvas = saved.get("canvas") if saved.get("canvas") in CANVASES else "none"
elif text_import:
parsed = _parse_text_layout(import_json, width, height, "Prompt Layout Builder: import_json")
prompt, boxes = parsed.get("prompt", prompt), parsed["boxes"]
krea = parsed.get("krea", krea)
ideogram = parsed.get("ideogram", ideogram)
palette = parsed.get("palette", palette)
summary = (parsed.get("layout") or {}).get("summary")
if isinstance(summary, dict):
prompt = str(summary.get("caption") or "")
meta_tags = _strs(summary.get("meta"))
canvas = summary.get("canvas") if summary.get("canvas") in CANVASES else "none"
palette = _palette(summary.get("palette"), SUMMARY_PALETTE_MAX)
if saved or text_import:
ui["pm_layout_import"] = [{
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": ", ".join(meta_tags), "canvas": canvas,
**({"ideogram": ideogram} if ideogram and (saved or text_import) else {}),
**({"krea": krea} if krea and (saved or text_import) else {}),
}]
ui["pm_layout_ref_size"] = list(ref_size) if ref_size else []
if image is None:
preview_bg = None
ui["pm_layout_background"] = []
else:
background = _fit_background(image, width, height)
preview_bg = Image.fromarray((background[0].cpu().numpy() * 255).clip(0, 255).astype(np.uint8))
ui["pm_layout_background"] = nodes.PreviewImage().save_images(background, "pm.layout.background")["ui"]["images"]
layout_prompt = _format_prompt(output_format, prompt, meta_tags, canvas, palette, boxes, width, height, ideogram, krea)
editor_state = {
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": meta_tags, "canvas": canvas,
"aspect_ratio": aspect_ratio, "megapixels": megapixels, "ideogram": ideogram, "krea": krea,
}
return {
"ui": ui,
"result": (
layout_prompt,
render_preview(boxes, width, height, preview_bg),
width,
height,
_manager_data(layout_prompt, editor_state, width, height),
),
}
+302
View File
@@ -0,0 +1,302 @@
"""Routes on the prompt library the Prompt Manager nodes share (py/prompt_store.py), each served under both the
Basic (/prompt-manager) and the full node's (/prompt-manager-advanced) prefix. Each node's own save route stays in
its module."""
import json
import os
import server
from ..py.backup_manager import atomic_save
from ..py.prompt_store import is_hidden_key, load_prompts, save_prompts
PREFIXES = ("/prompt-manager", "/prompt-manager-advanced")
def _route(method, name):
"""Serve the handler at `name` under both prefixes. A failure answers as JSON, which the frontend shows."""
def register(handler):
async def respond(request):
try:
return await handler(request)
except Exception as e:
print(f"[PromptManager] {name} failed: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
for prefix in PREFIXES:
getattr(server.PromptServer.instance.routes, method)(f"{prefix}/{name}")(respond)
return handler
return register
def _fail(error, status=200):
return server.web.json_response({"success": False, "error": error}, status=status)
def _text(data, key):
return str(data.get(key) or "").strip()
def _find(entries, name):
"""The prompt in `entries` named `name`, whatever its case (hidden category keys are not prompts)."""
return next((key for key in entries if not is_hidden_key(key) and key.lower() == name.lower()), None)
def _safe_abspath(path):
return os.path.abspath(os.path.expanduser(path or ""))
@_route("get", "get-prompts")
async def get_prompts(request):
return server.web.json_response(load_prompts())
@_route("post", "save-category")
async def save_category(request):
data = await request.json()
category = _text(data, "category_name")
if not category:
return _fail("Category name is required")
prompts = load_prompts()
existing = {key.lower(): key for key in prompts}
if category.lower() in existing:
return _fail(f"Category already exists as '{existing[category.lower()]}'")
prompts[category] = {"__meta__": {"nsfw": True}} if data.get("nsfw") else {}
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
@_route("post", "rename-category")
async def rename_category(request):
data = await request.json()
old_category = _text(data, "old_category")
new_category = _text(data, "new_category")
if not old_category or not new_category:
return _fail("Both old and new category names are required")
prompts = load_prompts()
if old_category not in prompts:
return _fail(f"Category '{old_category}' not found")
others = {key.lower(): key for key in prompts if key.lower() != old_category.lower()}
if new_category.lower() in others:
return _fail(f"Category already exists as '{others[new_category.lower()]}'")
prompts[new_category] = prompts.pop(old_category)
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts, "new_category": new_category})
@_route("post", "delete-category")
async def delete_category(request):
data = await request.json()
category = _text(data, "category")
if not category:
return _fail("Category name is required")
prompts = load_prompts()
if category not in prompts:
return _fail("Category not found")
del prompts[category]
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
@_route("post", "rename-prompt")
async def rename_prompt(request):
"""Rename a prompt, or move it to another category."""
data = await request.json()
category = _text(data, "category")
old_name = _text(data, "old_name")
new_name = _text(data, "new_name")
new_category = _text(data, "new_category") or category
if not category or not old_name or not new_name:
return _fail("Category, old name, and new name are required")
prompts = load_prompts()
if category not in prompts:
return _fail("Prompt not found")
if new_category not in prompts:
return _fail(f"Category '{new_category}' not found")
source, target = prompts[category], prompts[new_category]
current = _find(source, old_name)
if not current:
return _fail("Prompt not found")
clash = _find(target, new_name)
if clash and not (new_category == category and clash == current):
return _fail(f"A prompt named '{clash}' already exists in '{new_category}'")
target[new_name] = source.pop(current)
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
@_route("post", "delete-prompt")
async def delete_prompt(request):
data = await request.json()
category = _text(data, "category")
name = _text(data, "name")
if not category or not name:
return _fail("Category and prompt name are required")
prompts = load_prompts()
if category not in prompts or name not in prompts[category]:
return _fail("Prompt not found")
del prompts[category][name]
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
@_route("post", "save-thumbnail")
async def save_thumbnail(request):
"""Set a prompt's thumbnail, or remove it when none is sent."""
data = await request.json()
category = _text(data, "category")
name = _text(data, "name")
thumbnail = data.get("thumbnail")
if not category or not name:
return _fail("Category and name required")
prompts = load_prompts()
if category not in prompts or name not in prompts[category]:
return _fail("Prompt not found")
if thumbnail:
prompts[category][name]["thumbnail"] = thumbnail
else:
prompts[category][name].pop("thumbnail", None)
save_prompts(prompts)
return server.web.json_response({"success": True})
@_route("post", "toggle-nsfw")
async def toggle_nsfw(request):
"""Flip the NSFW flag of a category (type "category") or of a prompt (type "prompt")."""
data = await request.json()
kind = _text(data, "type")
category = _text(data, "category")
name = _text(data, "name")
if not category:
return _fail("Category is required")
prompts = load_prompts()
if category not in prompts:
return _fail("Category not found")
if kind == "category":
meta = prompts[category].get("__meta__", {})
meta["nsfw"] = not meta.get("nsfw", False)
prompts[category]["__meta__"] = meta
elif kind == "prompt":
if not name or name not in prompts[category]:
return _fail("Prompt not found")
prompts[category][name]["nsfw"] = not prompts[category][name].get("nsfw", False)
else:
return _fail("Invalid type, must be 'category' or 'prompt'")
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
@_route("post", "import-prompts")
async def import_prompts(request):
"""Import a library: "replace" starts from nothing, "skip_existing" keeps prompts already there, any other mode
overwrites them."""
data = await request.json()
imported_data = data.get("data", {})
mode = str(data.get("mode", "replace_existing") or "replace_existing").strip().lower()
if not isinstance(imported_data, dict):
return _fail("Invalid data format")
prompts = {} if mode == "replace" else load_prompts()
imported_prompts = skipped_prompts = created_categories = 0
for category, category_prompts in imported_data.items():
if not isinstance(category_prompts, dict):
continue
if category not in prompts:
prompts[category] = {}
created_categories += 1
for prompt_name, prompt_data in category_prompts.items():
# Hidden category metadata keys (not prompt entries); the base prompt and prefix are plain text.
if is_hidden_key(prompt_name):
if mode != "skip_existing" or prompt_name not in prompts[category]:
prompts[category][prompt_name] = prompt_data
continue
# Older exports stored a prompt as its text alone.
if isinstance(prompt_data, str):
prompt_data = {"prompt": prompt_data}
elif not isinstance(prompt_data, dict):
continue
if prompt_name in prompts[category] and mode == "skip_existing":
skipped_prompts += 1
continue
# Every field the entry carries (recipe data, negative prompt, thumbnail, flags) comes along; the lists
# a prompt always has default to empty.
prompts[category][prompt_name] = {
"prompt": "",
"loras_a": [],
"loras_b": [],
"loras_c": [],
"loras_d": [],
"trigger_words": [],
**prompt_data,
}
imported_prompts += 1
save_prompts(prompts)
return server.web.json_response({
"success": True,
"prompts": prompts,
"imported_prompts": imported_prompts,
"skipped_prompts": skipped_prompts,
"created_categories": created_categories,
})
@_route("post", "load-prompts-file")
async def load_prompts_file(request):
"""A library JSON file the user picked with the file browser."""
data = await request.json()
file_path = _safe_abspath(data.get("path", ""))
if not file_path:
return _fail("Path is required")
if not file_path.lower().endswith(".json"):
return _fail("Only JSON files can be opened", 400)
if not os.path.isfile(file_path):
return _fail("JSON file not found", 404)
with open(file_path, "r", encoding="utf-8") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
return _fail("Invalid JSON data format", 400)
return server.web.json_response({"success": True, "data": loaded, "path": file_path})
@_route("post", "export-prompts-file")
async def export_prompts_file(request):
"""Write a library to a JSON file the user picked with the file browser."""
data = await request.json()
raw_path = data.get("path", "")
export_path = _safe_abspath(raw_path) if raw_path else ""
if export_path and not export_path.lower().endswith(".json"):
export_path = f"{export_path}.json"
exported_data = data.get("data", {})
if not export_path:
return _fail("Export path is required")
if not isinstance(exported_data, dict):
return _fail("Invalid data format")
parent_dir = os.path.dirname(export_path)
if not parent_dir or not os.path.isdir(parent_dir):
return _fail("Target folder does not exist")
if not atomic_save(export_path, exported_data, "PromptManagerExport"):
return _fail("Failed to save export file", 500)
return server.web.json_response({"success": True, "path": export_path})
+984
View File
@@ -0,0 +1,984 @@
"""
ComfyUI Prompt Manager Advanced - Extended prompt management with LoRA stack support
Saves prompts along with associated LoRA configurations
"""
import os
import json
from datetime import datetime, timezone
import server
from ..py.lora_stacks import (
has_meaningful_workflow_data,
normalize_workflow_loras,
derive_prompt_fields,
combine_lora_inputs,
flatten_lora_slots,
merge_prompt_composer_input_data,
MODEL_SLOT_KEYS,
LORA_MODE_PROMPT_ONLY,
LORA_MODE_COMBINE,
LORA_MODE_INPUT_ONLY,
LORA_MODES,
PROMPT_MANAGER_RECIPE_KEY,
)
from ..py.lora_utils import (
get_available_loras,
normalize_path_separators,
strip_lora_extension,
get_lora_relative_path,
)
from ..py.prompt_metadata import record_prompt
from ..py.prompt_store import is_hidden_key, load_prompts, save_prompts
from ..py.workflow_data_utils import ensure_v2_recipe_data, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
class PromptManagerAdvanced:
"""
Advanced Prompt Manager with LoRA stack integration.
Supports saving/loading prompts with associated LoRA configurations.
Features two LoRA stack inputs/outputs for dual LoRA workflows (e.g., Wan video).
Legacy: kept for saved workflows; Prompt Manager (PromptManagerV2) replaces it.
"""
DEPRECATED = True
def __init__(self):
# Per node: the last run's prompt, input LoRA paths and input prompt, to tell when the frontend resets.
self._last_known_state = {}
@classmethod
def INPUT_TYPES(s):
prompts_data = load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(k for k in category_prompts.keys() if not is_hidden_key(k))
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
first_category = categories[0] if categories else "Default"
# Get first prompt from first category
# Keep new node instances empty until the user explicitly selects a prompt.
first_prompt = ""
first_prompt_text = ""
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"use_prompt_input": ("BOOLEAN", {
"default": False,
"tooltip": "Toggle to use connected prompt input instead of internal text"}),
"use_lora_input": (LORA_MODES, {
"default": LORA_MODE_PROMPT_ONLY,
"tooltip": (
"LoRA mode. Prompt LoRAs Only = use saved prompt stacks only. "
"Combine LoRAs = merge connected stacks with prompt stacks. "
"Input LoRAs Only = use only connected input stacks."
),
}),
"text": ("STRING", {
"multiline": True,
"default": first_prompt_text,
"placeholder": "Enter prompt text",
"dynamicPrompts": False,
"tooltip": "Enter prompt text directly"
}),
},
"optional": {
"prompt": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect prompt text input here"}),
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "Optional saved recipe or composer payload."}),
"lora_stack_a": ("LORA_STACK,MULTI_LORA_STACK", {"forceInput": True, "tooltip": "First LoRA stack input. Accepts LORA_STACK or MULTI_LORA_STACK."}),
"lora_stack_b": ("LORA_STACK,MULTI_LORA_STACK", {"forceInput": True, "tooltip": "Second LoRA stack input. Accepts LORA_STACK or MULTI_LORA_STACK."}),
"trigger_words": ("STRING", {"forceInput": True, "tooltip": "Comma-separated trigger words to append to prompt"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"loras_a_toggle": "STRING",
"loras_b_toggle": "STRING",
"loras_c_toggle": "STRING",
"loras_d_toggle": "STRING",
"trigger_words_toggle": "STRING",
"extra_pnginfo": "EXTRA_PNGINFO",
"api_prompt": "PROMPT",
}
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Full-featured prompt manager with multi-slot LoRA stack support, trigger words, and thumbnail browser."
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK", "MULTI_LORA_STACK", "MANAGER_DATA")
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b", "multi_lora_stack", "manager_data")
OUTPUT_TOOLTIPS = ("", "", "", "", "Prompt, LoRAs and saved recipe data; connect to Library Manager to save it.")
FUNCTION = "get_prompt"
OUTPUT_NODE = True
@staticmethod
def _normalize_lora_input_mode(mode_value):
"""Normalize legacy bool/new string modes to canonical dropdown values."""
if mode_value is False:
return LORA_MODE_PROMPT_ONLY
if mode_value is True:
return LORA_MODE_COMBINE
value = str(mode_value or "").strip()
if value in LORA_MODES:
return value
lowered = value.lower()
if lowered in ("off", "false", "0", "prompt", "prompt only", "prompt loras", "prompt loras only"):
return LORA_MODE_PROMPT_ONLY
if lowered in ("on", "true", "1", "combine", "combine loras"):
return LORA_MODE_COMBINE
if lowered in ("2", "input", "input only", "input loras", "input loras only"):
return LORA_MODE_INPUT_ONLY
return LORA_MODE_PROMPT_ONLY
@staticmethod
def _should_use_combined_loras(mode_value):
return PromptManagerAdvanced._normalize_lora_input_mode(mode_value) == LORA_MODE_COMBINE
@staticmethod
def _should_use_input_only_loras(mode_value):
return PromptManagerAdvanced._normalize_lora_input_mode(mode_value) == LORA_MODE_INPUT_ONLY
@classmethod
def IS_CHANGED(cls, category, name, use_prompt_input, use_lora_input=LORA_MODE_PROMPT_ONLY, text="", **kwargs):
"""
Track changes to the node's inputs to determine if re-execution is needed.
Returns a tuple of relevant values that should trigger re-execution when changed.
"""
# Get optional inputs
prompt_input = kwargs.get('prompt', None)
lora_stack_a = kwargs.get('lora_stack_a', None)
lora_stack_b = kwargs.get('lora_stack_b', None)
trigger_words = kwargs.get('trigger_words', None)
# Return tuple of all values that should trigger re-execution when changed
# Convert lists/objects to strings for hashable comparison
return (
category,
name,
use_prompt_input,
cls._normalize_lora_input_mode(use_lora_input),
text,
str(prompt_input) if prompt_input else None,
str(lora_stack_a) if lora_stack_a else None,
str(lora_stack_b) if lora_stack_b else None,
trigger_words,
)
@classmethod
def VALIDATE_INPUTS(cls, name, input_types=None, **kwargs):
"""Allow any name and validate optional LoRA input socket types."""
for key in ("lora_stack_a", "lora_stack_b"):
t = (input_types or {}).get(key) if isinstance(input_types, dict) else None
if t is None:
continue
if t not in ("LORA_STACK", "MULTI_LORA_STACK"):
return f"Unsupported type for {key}: {t}"
return True
def _merge_lora_stacks(self, preset_stack, connected_stack):
"""
Merge preset loras with connected loras, avoiding duplicates.
Preset loras come first, then connected loras that aren't already in preset.
Args:
preset_stack: List of tuples from saved preset
connected_stack: List of tuples from connected input
Returns:
Combined lora stack with no duplicates (by lora name, case-insensitive)
"""
if not connected_stack:
return preset_stack if preset_stack else []
if not preset_stack:
return list(connected_stack)
# Build set of lora names from preset (case-insensitive)
preset_names = set()
for lora_path, _, _ in preset_stack:
# Normalize path separators for OS-aware basename extraction
normalized_path = normalize_path_separators(lora_path)
lora_name = strip_lora_extension(os.path.basename(normalized_path)).lower()
preset_names.add(lora_name)
# Start with preset, add non-duplicate connected loras
merged = list(preset_stack)
for lora_path, model_strength, clip_strength in connected_stack:
# Normalize path separators for OS-aware basename extraction
normalized_path = normalize_path_separators(lora_path)
lora_name = strip_lora_extension(os.path.basename(normalized_path)).lower()
if lora_name not in preset_names:
merged.append((lora_path, model_strength, clip_strength))
preset_names.add(lora_name) # Prevent duplicates within connected too
return merged
def _process_lora_toggle(self, lora_stack, toggle_data):
"""
Process lora stack with toggle data to filter active loras and apply strength adjustments.
Also attempts to resolve LoRA paths that may not exist locally by searching by name.
Args:
lora_stack: List of tuples (lora_path, model_strength, clip_strength)
toggle_data: JSON string or list of toggle states [{name, active, strength}, ...]
Returns:
Filtered lora stack with adjusted strengths and resolved paths
"""
if not lora_stack:
return []
if not toggle_data:
# Even without toggle data, still try to resolve paths (skip unfound)
resolved_stack = []
lora_files = get_available_loras()
for lora_path, model_strength, clip_strength in lora_stack:
resolved_path, found = self._resolve_lora_path_with_status(lora_path, lora_files)
if found:
resolved_stack.append((resolved_path, model_strength, clip_strength))
else:
print(f"[PromptManagerAdvanced] Skipping unfound LoRA: {lora_path}")
return resolved_stack
# Parse toggle data if it's a string
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
except (json.JSONDecodeError, TypeError):
return list(lora_stack)
if not isinstance(toggle_data, list):
return list(lora_stack)
# Create a map of toggle states by lora name (case-insensitive)
toggle_map = {}
for item in toggle_data:
if isinstance(item, dict):
name = item.get('name', '')
toggle_map[name.lower()] = {
'active': item.get('active', True),
'strength': item.get('strength'),
'original_name': name # Keep original for debugging
}
# Filter and adjust lora stack
filtered_stack = []
lora_files = get_available_loras()
for lora_path, model_strength, clip_strength in lora_stack:
# Extract lora name from path - normalize separators for OS-aware basename extraction
normalized_path = normalize_path_separators(lora_path)
lora_name = strip_lora_extension(os.path.basename(normalized_path))
# Check toggle state (case-insensitive lookup)
toggle_state = toggle_map.get(lora_name.lower(), {'active': True, 'strength': None})
if not toggle_state['active']:
continue # Skip inactive loras
# Apply strength adjustment if provided
if toggle_state['strength'] is not None:
adjusted_strength = float(toggle_state['strength'])
# Scale both model and clip strength proportionally
ratio = adjusted_strength / model_strength if model_strength != 0 else 1.0
model_strength = adjusted_strength
clip_strength = clip_strength * ratio
# Try to resolve the path to a local LoRA - skip if not found
resolved_path, found = self._resolve_lora_path_with_status(lora_path, lora_files)
if found:
filtered_stack.append((resolved_path, model_strength, clip_strength))
return filtered_stack
def _resolve_lora_path_with_status(self, lora_path, lora_files):
"""
Try to resolve a LoRA path to an available local LoRA.
First checks if the exact path exists, then searches by name.
Args:
lora_path: The original path from the stack
lora_files: List of available LoRA files
Returns:
Tuple of (resolved_path, found) - path and whether it was found
"""
# Check if exact path exists
if lora_path in lora_files:
return lora_path, True
# Try to find by name
lora_name = strip_lora_extension(os.path.basename(lora_path))
found_path, found = get_lora_relative_path(lora_name)
if found:
return found_path, True
# Not found
return lora_path, False
def get_prompt(self, category, name, use_prompt_input, use_lora_input=LORA_MODE_PROMPT_ONLY,
text="", prompt=None, manager_data=None, lora_stack_a=None, lora_stack_b=None,
trigger_words=None,
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, loras_c_toggle=None, loras_d_toggle=None, trigger_words_toggle=None,
extra_pnginfo=None, api_prompt=None):
"""Return the prompt text and filtered lora stacks based on toggle states"""
toggles = {"a": loras_a_toggle, "b": loras_b_toggle, "c": loras_c_toggle, "d": loras_d_toggle}
inputs = combine_lora_inputs(lora_stack_a, lora_stack_b)
input_paths = {slot: [path for path, _, _ in inputs.get(slot, [])] for slot in MODEL_SLOT_KEYS}
prompt_input_text = prompt if prompt else ""
# Tell the frontend to reset its toggles when the prompt changed, when the input LoRAs and the input prompt
# changed together (a new extraction), or when the input LoRAs were cleared; not when only toggles changed.
node_key = str(unique_id) if unique_id else "default"
last = self._last_known_state.get(node_key, {"prompt_key": "", "input_paths": {slot: [] for slot in MODEL_SLOT_KEYS}, "prompt_input_text": ""})
prompt_key = f"{category}|{name}"
input_loras_changed = input_paths != last["input_paths"]
loras_were_cleared = any(last["input_paths"].values()) and not any(input_paths.values())
should_reset = (prompt_key != last["prompt_key"]
or (input_loras_changed and prompt_input_text != last["prompt_input_text"])
or loras_were_cleared)
self._last_known_state[node_key] = {"prompt_key": prompt_key, "input_paths": input_paths, "prompt_input_text": prompt_input_text}
lora_input_mode = self._normalize_lora_input_mode(use_lora_input)
use_combined_loras = self._should_use_combined_loras(lora_input_mode)
use_input_only_loras = self._should_use_input_only_loras(lora_input_mode)
prompt_entry = load_prompts().get(category, {}).get(name, {})
if not isinstance(prompt_entry, dict):
prompt_entry = {}
stored_prompt_wf = prompt_entry.get("workflow_data")
connected_recipe_data = ensure_v2_recipe_data(manager_data, source="PromptManagerAdvanced") if isinstance(manager_data, dict) else None
resolved_workflow_data = connected_recipe_data or (ensure_v2_recipe_data(stored_prompt_wf, source="PromptManagerAdvanced") if isinstance(stored_prompt_wf, dict) else None)
workflow_fields = derive_prompt_fields(resolved_workflow_data)
# The prompt input when it is on and has text, else the typed text, else the recipe's prompt.
if use_prompt_input and prompt:
output_text = prompt
else:
output_text = text if text else ""
if not output_text.strip() and workflow_fields.get("prompt"):
output_text = workflow_fields.get("prompt", "")
trigger_words_display = self._process_trigger_words(trigger_words, trigger_words_toggle)
active_trigger_words = self._get_active_trigger_words(trigger_words_toggle, trigger_words)
update = {}
out_stacks = {}
for slot in MODEL_SLOT_KEYS:
toggle = toggles[slot]
connected = inputs.get(slot)
# The connected LoRAs as they came in, for the frontend to notice an input change.
input_display = self._format_loras_for_display(connected) if connected else []
# Strengths before any adjustment, for "Reset Strength": the saved prompt's, then the inputs'.
original_strengths = {}
for lora in prompt_entry.get(f"loras_{slot}", []) if category and name else []:
if lora.get("name"):
original_strengths[lora["name"]] = lora.get("strength", lora.get("model_strength", 1.0))
for lora in input_display:
if lora.get("name") and lora["name"] not in original_strengths:
original_strengths[lora["name"]] = lora.get("strength", lora.get("model_strength", 1.0))
# The prompt's own LoRAs: the saved toggle payload, else the recipe's LoRAs.
recipe_loras = [lora for lora in workflow_fields.get(f"loras_{slot}", []) if isinstance(lora, dict) and lora.get("name")]
preset_stack = self._build_stack_from_toggle(toggle) if toggle else []
all_preset_loras = self._get_all_loras_from_toggle(toggle) if toggle else []
if not toggle:
preset_stack = [
(lora.get("name", ""), lora.get("strength", lora.get("model_strength", 1.0)),
lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0))))
for lora in recipe_loras
]
all_preset_loras = [
{
"name": lora.get("name", ""),
"strength": float(lora.get("strength", lora.get("model_strength", 1.0))),
"clip_strength": float(lora.get("clip_strength", lora.get("strength", lora.get("model_strength", 1.0)))),
"active": lora.get("active", True),
"available": bool(lora.get("available", True)),
}
for lora in recipe_loras
]
if use_input_only_loras:
stack = connected or []
elif use_combined_loras and connected:
stack = self._merge_lora_stacks(preset_stack, connected)
else:
stack = preset_stack
out_stacks[slot] = self._process_lora_toggle(stack, None if use_input_only_loras else toggle) or []
if use_input_only_loras:
display = self._format_loras_for_display(stack)
unavailable = [lora.get("name") for lora in display if lora.get("available") is False]
else:
display = self._format_loras_for_display_with_unavailable(stack, all_preset_loras)
unavailable = [lora["name"] for lora in all_preset_loras if not lora.get("available", False)]
update[f"loras_{slot}"] = display
update[f"input_loras_{slot}"] = input_display
update[f"unavailable_loras_{slot}"] = unavailable
update[f"original_strengths_{slot}"] = original_strengths
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
"node_id": unique_id,
"prompt": output_text,
"use_prompt_input": use_prompt_input,
"prompt_input": prompt,
**update,
"trigger_words": trigger_words_display,
"connected_thumbnail": None,
"should_reset": should_reset,
"lora_input_mode": lora_input_mode,
"use_lora_input": use_combined_loras,
"use_input_only_loras": use_input_only_loras,
"has_multi_lora_input": bool(inputs.get("c") or inputs.get("d")),
})
final_output = self._append_trigger_words_to_prompt(output_text, active_trigger_words)
# Saver nodes embed the final prompt as typed text, not the link that fed it.
record_prompt(unique_id, final_output, extra_pnginfo, api_prompt, toggle="use_prompt_input", link_input="prompt", text_index=4)
out_workflow_data = build_v2_recipe_data_from_prompt(
prompt_text=final_output,
negative_prompt=str(workflow_fields.get("negative_prompt", "") or ""),
**{f"loras_{slot}": update[f"loras_{slot}"] for slot in MODEL_SLOT_KEYS},
source="PromptManagerAdvanced",
base_recipe_data=resolved_workflow_data,
)
out_workflow_data = merge_prompt_composer_input_data(
out_workflow_data,
input_prompt=prompt_input_text,
prompt_enabled=bool(use_prompt_input and prompt_input_text),
input_lora_stack=flatten_lora_slots(out_stacks),
)
out_workflow_data[PROMPT_MANAGER_RECIPE_KEY] = {"category": category, "name": name}
return (final_output, out_stacks["a"], out_stacks["b"], out_stacks, out_workflow_data)
def check_lazy_status(self, category, name, use_prompt_input, use_lora_input=LORA_MODE_PROMPT_ONLY,
text="", prompt=None, lora_stack_a=None, lora_stack_b=None,
trigger_words=None,
unique_id=None, loras_a_toggle=None, loras_b_toggle=None, loras_c_toggle=None, loras_d_toggle=None,
trigger_words_toggle=None, extra_pnginfo=None, api_prompt=None,
**kwargs):
"""Tell ComfyUI which lazy inputs are needed based on current settings.
When use_prompt_input is enabled, we need to request the prompt_input
so ComfyUI will evaluate any connected nodes.
"""
needed = []
if use_prompt_input:
needed.append("prompt")
return needed
def _build_stack_from_toggle(self, toggle_data):
"""
Build a lora stack from toggle data by resolving paths at runtime.
This is used when no input stack is connected but we have saved lora data.
"""
if not toggle_data:
return []
# Parse toggle data if it's a string
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
except (json.JSONDecodeError, TypeError):
return []
if not isinstance(toggle_data, list):
return []
stack = []
missing_loras = []
for item in toggle_data:
if not isinstance(item, dict):
continue
lora_name = item.get('name', '')
if not lora_name:
continue
# Skip inactive loras
if item.get('active', True) is False:
continue
# Resolve the path at runtime
relative_path, found = get_lora_relative_path(lora_name)
if not found:
missing_loras.append(lora_name)
continue # Skip missing loras
strength = float(item.get('strength', 1.0))
clip_strength = float(item.get('clip_strength', strength))
stack.append((relative_path, strength, clip_strength))
# Log warning for missing loras
if missing_loras:
print(f"[PromptManagerAdvanced] Warning: Could not find LoRAs: {', '.join(missing_loras)}")
return stack
def _format_loras_for_display(self, lora_stack):
"""Format lora stack for frontend display, checking availability and deduplicating by name"""
if not lora_stack:
return []
display_list = []
seen_names = set() # Track seen LoRA names (case-insensitive) to avoid duplicates
lora_files = get_available_loras()
for lora_path, model_strength, clip_strength in lora_stack:
# Normalize path separators for OS-aware basename extraction
normalized_path = normalize_path_separators(lora_path)
lora_name = strip_lora_extension(os.path.basename(normalized_path))
lora_name_lower = lora_name.lower()
# Skip if we've already added this LoRA (case-insensitive)
if lora_name_lower in seen_names:
continue
# Check if LoRA is available locally
# First try exact path match, then try name-based search
available = False
resolved_path = lora_path
# Check if exact path exists in available loras
if lora_path in lora_files:
available = True
resolved_path = lora_path
else:
# Try to find by name
found_path, found = get_lora_relative_path(lora_name)
if found:
available = True
resolved_path = found_path
display_list.append({
"name": lora_name,
"path": resolved_path,
"model_strength": model_strength,
"clip_strength": clip_strength,
"active": True,
"strength": model_strength,
"available": available,
})
seen_names.add(lora_name_lower)
return display_list
def _get_all_loras_from_toggle(self, toggle_data):
"""
Get ALL loras from toggle data including unavailable ones.
Returns list of dicts with name, strength, active, and available status.
Used for building complete display list.
"""
if not toggle_data:
return []
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
except (json.JSONDecodeError, TypeError):
return []
if not isinstance(toggle_data, list):
return []
all_loras = []
for item in toggle_data:
if not isinstance(item, dict):
continue
lora_name = item.get('name', '')
if not lora_name:
continue
# Check availability using same fuzzy matching as actual loading
# UI should match what Python will actually do
_, found = get_lora_relative_path(lora_name)
all_loras.append({
"name": lora_name,
"strength": float(item.get('strength', 1.0)),
"clip_strength": float(item.get('clip_strength', item.get('strength', 1.0))),
"active": item.get('active', True),
"available": found,
})
return all_loras
def _format_loras_for_display_with_unavailable(self, lora_stack, all_preset_loras):
"""
Format lora stack for frontend display, including unavailable preset loras.
This ensures the UI shows all saved loras even if they're not found locally.
"""
# Start with the available loras from the stack
display_list = self._format_loras_for_display(lora_stack) if lora_stack else []
preset_by_name = {
str(item.get('name', '')).lower(): item
for item in (all_preset_loras or [])
if isinstance(item, dict) and item.get('name')
}
# Preserve active state from preset/toggle/workflow payload for rows
# that are already present in the display list.
for row in display_list:
row_name_lower = str(row.get('name', '')).lower()
preset = preset_by_name.get(row_name_lower)
if preset is not None:
row['active'] = preset.get('active', True)
seen_names = set(item['name'].lower() for item in display_list)
# Add any unavailable preset loras that aren't already in the list
for lora in all_preset_loras:
lora_name_lower = lora['name'].lower()
if lora_name_lower not in seen_names:
display_list.append({
"name": lora['name'],
"path": lora['name'], # Just use name as path for unavailable
"model_strength": lora['strength'],
"clip_strength": lora['clip_strength'],
"active": lora['active'],
"strength": lora['strength'],
"available": lora['available'],
})
seen_names.add(lora_name_lower)
return display_list
def _process_trigger_words(self, connected_trigger_words, toggle_data):
"""
Process trigger words from connected input and saved toggle states.
Connected-origin words are pruned when missing, while prompt-saved words remain.
"""
connected_words = []
connected_word_set = set()
if connected_trigger_words and isinstance(connected_trigger_words, str):
connected_words = [w.strip() for w in connected_trigger_words.split(',,') if w.strip()]
connected_word_set = {w.lower() for w in connected_words}
# Parse saved toggle data
saved_words = {}
if toggle_data:
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
if isinstance(toggle_data, list):
for item in toggle_data:
if isinstance(item, dict) and item.get('text'):
word = item['text'].strip()
word_lower = word.lower()
from_input = item.get('fromInput') is True
if from_input and word_lower not in connected_word_set:
continue
saved_words[word.lower()] = {
'text': word,
'active': item.get('active', True),
'fromInput': from_input,
}
except (json.JSONDecodeError, TypeError):
pass
# Merge: saved words + new connected words (no duplicates)
result = []
seen = set()
# First, add all saved words (preserving their state)
for word_lower, data in saved_words.items():
if word_lower not in seen:
result.append({
'text': data['text'],
'active': data['active'],
'source': 'connected' if data.get('fromInput') else 'saved',
'fromInput': data.get('fromInput', False),
})
seen.add(word_lower)
# Then add connected words that aren't already saved
for word in connected_words:
word_lower = word.lower()
if word_lower not in seen:
result.append({
'text': word,
'active': True,
'source': 'connected',
'fromInput': True,
})
seen.add(word_lower)
return result
def _get_active_trigger_words(self, toggle_data, connected_trigger_words=None):
"""
Get list of active trigger word strings from toggle data and connected input.
Connected-origin words are pruned when missing, while prompt-saved words remain.
"""
active_words = []
active_seen = set()
saved_seen = set()
has_authoritative_toggle_data = False
connected_word_set = set()
if connected_trigger_words and isinstance(connected_trigger_words, str):
connected_word_set = {
word.strip().lower()
for word in connected_trigger_words.split(',,')
if word.strip()
}
# First, get active words from saved toggle data
if toggle_data is not None:
try:
if isinstance(toggle_data, str):
toggle_data = json.loads(toggle_data)
if isinstance(toggle_data, list):
has_authoritative_toggle_data = True
for item in toggle_data:
if not isinstance(item, dict):
continue
word = item.get('text', '').strip()
if not word:
continue
word_lower = word.lower()
if item.get('fromInput') is True and word_lower not in connected_word_set:
continue
saved_seen.add(word_lower)
if item.get('active', True) and word_lower not in active_seen:
active_words.append(word)
active_seen.add(word_lower)
except (json.JSONDecodeError, TypeError):
pass
# Also include connected trigger words that aren't already in the saved data
# but only when no authoritative toggle payload exists yet.
if (not has_authoritative_toggle_data) and connected_trigger_words and isinstance(connected_trigger_words, str):
for word in connected_trigger_words.split(',,'):
word = word.strip()
word_lower = word.lower()
if word and word_lower not in saved_seen and word_lower not in active_seen:
active_words.append(word)
active_seen.add(word_lower)
return active_words
def _append_trigger_words_to_prompt(self, prompt, trigger_words):
"""
Prepend trigger words before the prompt.
Ensures the trigger-word block ends with punctuation; if it doesn't end with
period/comma/colon, append a comma.
"""
if not trigger_words:
return prompt
trigger_block = ', '.join(trigger_words).strip()
if not trigger_block:
return prompt
if not trigger_block.endswith(('.', ',', ':')):
trigger_block += ','
prompt = str(prompt or '').strip()
if not prompt:
return trigger_block
return f"{trigger_block} {prompt}"
# API Routes for Advanced Prompt Manager
def _normalize_saved_loras(loras):
"""LoRAs from the frontend in the saved schema; the path is kept when present for a lossless restore."""
return [
{
"name": lora.get("name"),
"path": lora.get("path", lora.get("name")),
"strength": lora.get("strength", lora.get("model_strength", 1.0)),
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
"active": lora.get("active", True),
"available": bool(lora.get("available", True)),
}
for lora in loras
if isinstance(lora, dict) and lora.get("name")
]
def _normalize_trigger_words(words):
"""Trigger words as {text, active}, each once whatever its case."""
normalized = []
seen = set()
for word in words:
if isinstance(word, dict) and word.get("text"):
text, active = word["text"].strip(), word.get("active", True)
elif isinstance(word, str):
text, active = word.strip(), True
else:
continue
if text and text.lower() not in seen:
normalized.append({"text": text, "active": active})
seen.add(text.lower())
return normalized
# Keys the save route writes; any other key on a saved prompt (workflow_config from RecipeManager, future fields)
# is kept as it was.
_SAVED_KEYS = {"prompt", "negative_prompt", "loras_a", "loras_b", "loras_c", "loras_d", "trigger_words", "thumbnail", "nsfw", "workflow_data", "saved_from", "saved_at"}
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/save-prompt")
async def save_prompt_advanced(request):
"""Save a prompt with its LoRAs, trigger words and recipe data; old_category / old_name rename or move it."""
try:
data = await request.json()
category = data.get("category", "").strip()
name = data.get("name", "").strip()
text = data.get("text", "").strip()
old_category = data.get("old_category", "").strip() or category
old_name = data.get("old_name", "").strip() or name
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name are required"})
prompts = load_prompts()
if category not in prompts:
prompts[category] = {}
source_prompts = prompts.get(old_category, {}) if isinstance(prompts.get(old_category), dict) else {}
target_prompts = prompts[category]
existing_old_name = None
existing_prompt = {}
if old_category in prompts:
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
if existing_old_name:
existing_prompt = source_prompts.get(existing_old_name, {})
existing_target_name = next((key for key in target_prompts.keys() if str(key).lower() == name.lower() and not is_hidden_key(key)), None)
if existing_target_name:
same_entry = (
existing_old_name is not None
and old_category == category
and str(existing_target_name).lower() == str(existing_old_name).lower()
)
if not same_entry:
return server.web.json_response({
"success": False,
"error": f"A prompt named '{existing_target_name}' already exists in '{category}'"
})
if existing_old_name and (old_category != category or existing_old_name != name):
existing_prompt = source_prompts.pop(existing_old_name, existing_prompt)
# The same prompt under another casing is replaced by this one.
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys() if not is_hidden_key(k)}
if name.lower() in existing_prompts_lower:
casing_name = existing_prompts_lower[name.lower()]
existing_prompt = prompts[category].get(casing_name, existing_prompt)
if casing_name != name:
del prompts[category][casing_name]
thumbnail = data.get("thumbnail")
if thumbnail is None:
thumbnail = existing_prompt.get("thumbnail")
workflow_data = data.get("workflow_data")
if isinstance(workflow_data, str) and workflow_data.strip():
try:
workflow_data = json.loads(workflow_data)
except json.JSONDecodeError:
workflow_data = None
wf_to_save = to_json_safe_workflow_data(ensure_v2_recipe_data(workflow_data, source="PromptManagerAdvanced")) if isinstance(workflow_data, dict) else None
wf_models = wf_to_save.get("models", {}) if wf_to_save and isinstance(wf_to_save.get("models"), dict) else {}
recipe_is_authored = bool(wf_to_save) and has_meaningful_workflow_data(wf_to_save)
prompt_data = {"prompt": text}
for slot in MODEL_SLOT_KEYS:
loras = _normalize_saved_loras(data.get(f"loras_{slot}", []))
# An authored recipe's LoRAs are authoritative, as in Workflow Saver.
recipe_loras = normalize_workflow_loras((wf_models.get(f"model_{slot}") or {}).get("loras", []))
if recipe_is_authored and recipe_loras:
loras = recipe_loras
# A side sent with no LoRAs keeps the saved ones: transient UI state must not erase them.
if not loras and isinstance(existing_prompt.get(f"loras_{slot}"), list):
loras = existing_prompt[f"loras_{slot}"]
prompt_data[f"loras_{slot}"] = loras
prompt_data["trigger_words"] = _normalize_trigger_words(data.get("trigger_words", []))
if wf_to_save:
model_a_block = wf_models.get("model_a") if isinstance(wf_models.get("model_a"), dict) else {}
if isinstance(model_a_block.get("positive_prompt"), str) and model_a_block.get("positive_prompt", "").strip():
prompt_data["prompt"] = model_a_block["positive_prompt"]
if isinstance(model_a_block.get("negative_prompt"), str):
prompt_data["negative_prompt"] = model_a_block["negative_prompt"]
prompt_data["saved_from"] = str(wf_to_save.get("_source") or "RecipeManager")
prompt_data["saved_at"] = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
prompt_data["workflow_data"] = wf_to_save
elif isinstance(existing_prompt.get("workflow_data"), dict):
# Prompt or LoRA edits saved without a connected recipe keep the saved recipe.
prompt_data["workflow_data"] = to_json_safe_workflow_data(ensure_v2_recipe_data(existing_prompt["workflow_data"], source="PromptManagerAdvanced"))
if thumbnail:
prompt_data["thumbnail"] = thumbnail
nsfw = data.get("nsfw")
if nsfw is not None:
prompt_data["nsfw"] = bool(nsfw)
elif existing_prompt.get("nsfw"):
prompt_data["nsfw"] = existing_prompt["nsfw"]
for extra_key, extra_val in existing_prompt.items():
if extra_key not in _SAVED_KEYS and extra_key not in prompt_data:
prompt_data[extra_key] = extra_val
prompts[category][name] = prompt_data
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManagerAdvanced] Error in save_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/check-loras")
async def check_loras_advanced(request):
"""API endpoint to check which LoRAs are available in the system"""
try:
data = await request.json()
lora_names = data.get("lora_names", [])
results = {}
for lora_name in lora_names:
_, found = get_lora_relative_path(lora_name)
results[lora_name] = found
return server.web.json_response({"success": True, "results": results})
except Exception as e:
print(f"[PromptManagerAdvanced] Error in check_loras API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/available-loras")
async def get_available_loras_api(request):
"""API endpoint to get list of all available LoRA names"""
try:
lora_files = get_available_loras()
# Return just the names without extensions for easier matching
lora_names = [strip_lora_extension(os.path.basename(f)) for f in lora_files]
return server.web.json_response({"success": True, "loras": sorted(set(lora_names))})
except Exception as e:
print(f"[PromptManagerAdvanced] Error in available_loras API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
+159
View File
@@ -0,0 +1,159 @@
import server
from ..py.prompt_metadata import record_prompt
from ..py.prompt_store import is_hidden_key, load_prompts, save_prompts
class PromptManager:
"""Legacy: kept for saved workflows; Prompt Manager (PromptManagerV2) replaces it."""
DEPRECATED = True
@classmethod
def INPUT_TYPES(s):
prompts_data = load_prompts()
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
all_prompts = set()
for category_prompts in prompts_data.values():
all_prompts.update(k for k in category_prompts.keys() if not is_hidden_key(k))
all_prompts.add("")
all_prompts_list = sorted(list(all_prompts))
first_category = categories[0] if categories else "Character"
# Get first prompt from first category
first_prompt = ""
first_prompt_text = ""
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
first_category_prompts = [k for k in prompts_data[first_category].keys() if not is_hidden_key(k)]
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
if first_prompt:
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
return {
"required": {
"category": (categories, {"default": first_category}),
"name": (all_prompts_list, {"default": first_prompt}),
"use_external": ("BOOLEAN", {"default": False, "tooltip": "Toggle to use LLM input instead of internal text"}),
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
},
"optional": {
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
"api_prompt": "PROMPT",
}
}
CATEGORY = "Prompt Manager"
DESCRIPTION = "Simple prompt manager for saving and loading prompts by category. Prompt-only, no LoRA support."
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("prompt",)
FUNCTION = "get_prompt"
OUTPUT_NODE = True
@classmethod
def VALIDATE_INPUTS(cls, name, **kwargs):
"""Allow any name value, including temporary unsaved prompts"""
# Return True to accept any value - this allows new prompts to be tested before saving
return True
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None, extra_pnginfo=None, api_prompt=None):
"""Return the appropriate text based on use_external toggle and broadcast update"""
# Choose which text to use based on the toggle
if use_external and llm_input:
output_text = llm_input
else:
output_text = text
# Broadcast the current prompt text to the frontend
if unique_id is not None:
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
"node_id": unique_id,
"prompt": output_text,
"use_external": use_external,
"llm_input": llm_input if use_external else ""
})
# Save resolved runtime prompt into execution metadata so saver nodes
# embed the final prompt value, not the unresolved linked input state.
record_prompt(unique_id, output_text, extra_pnginfo, api_prompt, toggle="use_external", link_input="llm_input", text_index=3)
return (output_text,)
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None,
extra_pnginfo=None, api_prompt=None, **kwargs):
needed = []
if use_external:
needed.append("llm_input")
return needed
@server.PromptServer.instance.routes.post("/prompt-manager/save-prompt")
async def save_prompt(request):
"""API endpoint to save a prompt"""
try:
data = await request.json()
category = data.get("category", "").strip()
name = data.get("name", "").strip()
text = data.get("text", "").strip()
old_category = data.get("old_category", "").strip() or category
old_name = data.get("old_name", "").strip() or name
if not category or not name:
return server.web.json_response({"success": False, "error": "Category and name are required"})
prompts = load_prompts()
if category not in prompts:
prompts[category] = {}
source_prompts = prompts.get(old_category, {}) if isinstance(prompts.get(old_category), dict) else {}
target_prompts = prompts[category]
existing_data = {}
existing_old_name = None
if old_category in prompts:
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
if existing_old_name:
existing_data = source_prompts.get(existing_old_name, {})
target_conflict_name = next((key for key in target_prompts.keys() if str(key).lower() == name.lower()), None)
if target_conflict_name:
same_entry = (
existing_old_name is not None
and old_category == category
and str(target_conflict_name).lower() == str(existing_old_name).lower()
)
if not same_entry:
return server.web.json_response({
"success": False,
"error": f"A prompt named '{target_conflict_name}' already exists in '{category}'"
})
if existing_old_name and (old_category != category or existing_old_name != name):
existing_data = source_prompts.pop(existing_old_name, existing_data)
# Case-insensitive check - find if name exists with different casing
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys()}
if name.lower() in existing_prompts_lower:
casing_name = existing_prompts_lower[name.lower()]
if casing_name != name:
# Delete the old casing version
print(f"[PromptManager] Removing old casing '{casing_name}' before saving as '{name}'")
del prompts[category][casing_name]
# Only the text changes: LoRAs, trigger words, recipe data, thumbnail and flags saved by the full
# Prompt Manager stay with the prompt.
prompts[category][name] = {**existing_data, "prompt": text} if isinstance(existing_data, dict) else {"prompt": text}
save_prompts(prompts)
return server.web.json_response({"success": True, "prompts": prompts})
except Exception as e:
print(f"[PromptManager] Error in save_prompt API: {e}")
return server.web.json_response({"success": False, "error": str(e)}, status=500)
+256
View File
@@ -0,0 +1,256 @@
"""Prompt Manager: a saved prompt, typed or taken from the prompt input, with the LoRA stacks and trigger words that
go with it. The node face only shows what is in use: one LoRA panel per slot that has LoRAs, trigger words when there
are any. On/off and strength edits live in the `state` widget, as overrides by slot and LoRA name; the rows the panels
show go back to the frontend as the node's UI output."""
import json
import os
from ..py.lora_stacks import (
LORA_MODE_COMBINE,
LORA_MODE_INPUT_ONLY,
LORA_MODE_PROMPT_ONLY,
LORA_MODES,
MODEL_SLOT_KEYS,
PROMPT_MANAGER_RECIPE_KEY,
derive_prompt_fields,
flatten_lora_slots,
merge_prompt_composer_input_data,
normalize_lora_slots,
)
from ..py.lora_utils import get_available_loras, get_lora_relative_path, normalize_path_separators, strip_lora_extension
from ..py.prompt_metadata import record_prompt
from ..py.prompt_store import is_hidden_key, load_prompts
from ..py.workflow_data_utils import build_v2_recipe_data_from_prompt, ensure_v2_recipe_data
def _saved_entry(category, name):
entry = load_prompts().get(category, {}).get(name, {})
return entry if isinstance(entry, dict) else {}
def _parse_state(state):
"""The node's edits: {"loras": {slot: {name: {"active", "strength", "removed"}}}, "order": {slot: [name]},
"trigger_words": {text: {"active", "removed"}}}, names and texts in lower case."""
try:
parsed = json.loads(state) if isinstance(state, str) and state else {}
except json.JSONDecodeError:
return {}
return parsed if isinstance(parsed, dict) else {}
def _lora_name(path):
return strip_lora_extension(os.path.basename(normalize_path_separators(path)))
def _saved_row(lora):
"""A LoRA saved with the prompt (or in its recipe), as a panel row; found among the local LoRAs by name."""
name = str(lora.get("name", "")).strip()
strength = float(lora.get("strength", lora.get("model_strength", 1.0)))
path, available = get_lora_relative_path(name)
return {
"name": name,
"path": path if available else name,
"strength": strength,
"clip_strength": float(lora.get("clip_strength", strength)),
"active": lora.get("active", True) is not False,
"available": available,
"from_input": False,
}
def _input_row(path, model_strength, clip_strength, lora_files):
"""A LoRA from the lora_stacks input, as a panel row."""
name = _lora_name(path)
available = path in lora_files
if not available:
found_path, available = get_lora_relative_path(name)
if available:
path = found_path
return {
"name": name,
"path": path,
"strength": float(model_strength),
"clip_strength": float(clip_strength),
"active": True,
"available": available,
"from_input": True,
}
def _apply_override(row, override):
"""The row with the node's on/off, strength and removal edits; clip strength follows the strength by the same
ratio. The row keeps its own strength and state as base_strength and base_active, for the frontend's reset."""
row["base_strength"] = row["strength"]
row["base_active"] = row["active"]
row["removed"] = override.get("removed") is True
if "active" in override:
row["active"] = override["active"] is not False
if isinstance(override.get("strength"), (int, float)):
strength = float(override["strength"])
row["clip_strength"] *= strength / row["strength"] if row["strength"] else 1.0
row["strength"] = strength
return row
def _slot_rows(prompt_loras, input_stack, mode, overrides, order, lora_files):
"""One slot's panel rows: the prompt's LoRAs, the input's, or both (the prompt's first, an input LoRA of the same
name left out), with the node's edits, in the node's order (LoRAs it does not name after, as they came)."""
rows = []
if mode != LORA_MODE_INPUT_ONLY:
rows += [_saved_row(lora) for lora in prompt_loras if isinstance(lora, dict) and str(lora.get("name", "")).strip()]
if mode != LORA_MODE_PROMPT_ONLY:
rows += [_input_row(*item, lora_files) for item in input_stack]
unique, seen = [], set()
for row in rows:
key = row["name"].lower()
if key not in seen:
seen.add(key)
unique.append(_apply_override(row, overrides.get(key, {})))
unique.sort(key=lambda row: order.index(row["name"].lower()) if row["name"].lower() in order else len(order))
return unique
def _trigger_rows(saved_words, connected_words, overrides):
"""Trigger words saved with the prompt, then the connected ones not already there, with the node's on/off and
removal edits. Connected words come as one string, groups split by ",," (as LoRA Manager sends them)."""
rows, seen = [], set()
candidates = [(word.get("text", "") if isinstance(word, dict) else word, word.get("active", True) if isinstance(word, dict) else True, False)
for word in saved_words or []]
if isinstance(connected_words, str):
candidates += [(word, True, True) for word in connected_words.split(",,")]
for text, active, from_input in candidates:
text = str(text or "").strip()
if text and text.lower() not in seen:
seen.add(text.lower())
override = overrides.get(text.lower(), {})
rows.append({"text": text, "active": override.get("active", active is not False) is not False, "base_active": active is not False,
"removed": override.get("removed") is True, "from_input": from_input})
return rows
def _with_trigger_words(prompt, words):
"""Trigger words before the prompt, the block ending in punctuation."""
block = ", ".join(words).strip()
if not block:
return prompt
if not block.endswith((".", ",", ":")):
block += ","
prompt = str(prompt or "").strip()
return f"{block} {prompt}" if prompt else block
class PromptManagerV2:
CATEGORY = "Prompt Manager"
DESCRIPTION = "A saved prompt, typed or from the prompt input, with its LoRA stacks and trigger words. LoRA stacks go out as a plain LoRA stack when one slot has LoRAs, as a multi LoRA stack when several do."
@classmethod
def INPUT_TYPES(cls):
prompts = load_prompts()
categories = list(prompts) or ["Default"]
names = sorted({key for entries in prompts.values() for key in entries if not is_hidden_key(key)} | {""}, key=str.lower)
return {
"required": {
"category": (categories, {"default": categories[0]}),
"name": (names, {"default": ""}),
"use_prompt_input": ("BOOLEAN", {"default": False, "tooltip": "Use the connected prompt instead of the typed one."}),
"lora_mode": (list(LORA_MODES), {"default": LORA_MODE_COMBINE, "tooltip": "Which LoRAs go out: the prompt's, both (the prompt's first), or the input's."}),
"text": ("STRING", {"multiline": True, "default": "", "dynamicPrompts": False}),
},
"optional": {
"prompt": ("STRING", {"forceInput": True, "lazy": True, "tooltip": "A prompt to use instead of the typed one."}),
"lora_stacks": ("LORA_STACK,MULTI_LORA_STACK", {"forceInput": True, "tooltip": "LoRA stacks to combine with the prompt's; a plain LoRA stack is slot A."}),
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "A recipe: its LoRAs are the prompt's, its prompt is used when none is typed."}),
"trigger_words": ("STRING", {"forceInput": True, "tooltip": "Trigger words to put before the prompt, groups separated by ,,"}),
"state": ("STRING", {"default": "{}"}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
"api_prompt": "PROMPT",
},
}
RETURN_TYPES = ("STRING", "LORA_STACK,MULTI_LORA_STACK", "MANAGER_DATA")
RETURN_NAMES = ("prompt", "lora_stacks", "manager_data")
OUTPUT_TOOLTIPS = (
"The prompt, its active trigger words first.",
"The active LoRAs: a plain LoRA stack when one slot has LoRAs, a multi LoRA stack (slots A-D) when several do.",
"The prompt and its LoRAs as a recipe.",
)
FUNCTION = "get_prompt"
# Runs on its own (ComfyUI's run-node button) to pull in a prompt from a generator upstream.
OUTPUT_NODE = True
@classmethod
def VALIDATE_INPUTS(cls, category, name):
# A prompt or category renamed or deleted since the workflow was saved still runs, from its typed text.
return True
@classmethod
def IS_CHANGED(cls, category, name, **kwargs):
# The prompt's saved LoRAs and trigger words can change in the library without any input changing.
return json.dumps(_saved_entry(category, name), sort_keys=True, default=str)
def check_lazy_status(self, use_prompt_input, prompt=None, **kwargs):
return ["prompt"] if use_prompt_input else []
def get_prompt(self, category, name, use_prompt_input, lora_mode, text, prompt=None, lora_stacks=None, manager_data=None,
trigger_words=None, state="{}", unique_id=None, extra_pnginfo=None, api_prompt=None):
overrides = _parse_state(state)
entry = _saved_entry(category, name)
stored_recipe = entry.get("workflow_data")
recipe = (ensure_v2_recipe_data(manager_data, source="PromptManager") if isinstance(manager_data, dict)
else ensure_v2_recipe_data(stored_recipe, source="PromptManager") if isinstance(stored_recipe, dict) else None)
fields = derive_prompt_fields(recipe)
# The prompt input when it is on and has text, else the typed text, else the recipe's prompt.
if use_prompt_input and prompt:
output_text = prompt
else:
output_text = text if text.strip() else fields["prompt"]
inputs = normalize_lora_slots(lora_stacks, "a")
lora_files = get_available_loras()
lora_overrides = overrides.get("loras") if isinstance(overrides.get("loras"), dict) else {}
orders = overrides.get("order") if isinstance(overrides.get("order"), dict) else {}
shown, rows, stacks = {}, {}, {}
for slot in MODEL_SLOT_KEYS:
# The prompt's LoRAs: the connected recipe's, else the saved prompt's, else its saved recipe's.
prompt_loras = fields[f"loras_{slot}"] if isinstance(manager_data, dict) else (entry.get(f"loras_{slot}") or fields[f"loras_{slot}"])
slot_overrides = lora_overrides.get(slot) if isinstance(lora_overrides.get(slot), dict) else {}
order = orders.get(slot) if isinstance(orders.get(slot), list) else []
shown[slot] = _slot_rows(prompt_loras, inputs[slot], lora_mode, slot_overrides, order, lora_files)
rows[slot] = [row for row in shown[slot] if not row["removed"]]
stacks[slot] = [(row["path"], row["strength"], row["clip_strength"]) for row in rows[slot] if row["active"] and row["available"]]
word_overrides = overrides.get("trigger_words") if isinstance(overrides.get("trigger_words"), dict) else {}
shown_words = _trigger_rows(entry.get("trigger_words"), trigger_words, word_overrides)
final_output = _with_trigger_words(output_text, [word["text"] for word in shown_words if word["active"] and not word["removed"]])
# Saver nodes embed the final prompt as typed text, not the link that fed it.
record_prompt(unique_id, final_output, extra_pnginfo, api_prompt, toggle="use_prompt_input", link_input="prompt", text_index=4)
filled = [slot for slot in MODEL_SLOT_KEYS if stacks[slot]]
lora_output = stacks if len(filled) > 1 else (stacks[filled[0]] if filled else [])
recipe_out = build_v2_recipe_data_from_prompt(
prompt_text=final_output,
negative_prompt=fields["negative_prompt"],
**{f"loras_{slot}": rows[slot] for slot in MODEL_SLOT_KEYS},
source="PromptManager",
base_recipe_data=recipe,
)
prompt_input_text = prompt or ""
recipe_out = merge_prompt_composer_input_data(
recipe_out,
input_prompt=prompt_input_text,
prompt_enabled=bool(use_prompt_input and prompt_input_text),
input_lora_stack=flatten_lora_slots(stacks),
)
recipe_out[PROMPT_MANAGER_RECIPE_KEY] = {"category": category, "name": name}
# The panels' rows for the frontend (onExecuted), for the prompt they were made for; removed rows included,
# so undoing a removal needs no new run.
panels = {"category": category, "name": name, "lora_mode": lora_mode, "loras": shown, "trigger_words": shown_words, "prompt_input": prompt if use_prompt_input else None}
return {"ui": {"prompt_manager": [panels]}, "result": (final_output, lora_output, recipe_out)}
File diff suppressed because it is too large Load Diff
+534
View File
@@ -0,0 +1,534 @@
import os
import sys
import inspect
import folder_paths
import nodes
import comfy.sd
import comfy.utils
import torch
from comfy_execution.graph import ExecutionBlocker
# =========================================================
# GGUF support
# =========================================================
def _get_gguf_module():
"""Get the ComfyUI-GGUF module if available, otherwise None."""
try:
gguf_cls = nodes.NODE_CLASS_MAPPINGS.get("UnetLoaderGGUF")
if gguf_cls is None:
return None
mod = sys.modules.get(gguf_cls.__module__)
if mod is None:
return None
package = gguf_cls.__module__.rsplit(".", 1)[0]
ops_mod = sys.modules.get(f"{package}.ops")
loader_mod = sys.modules.get(f"{package}.loader")
if ops_mod is None or loader_mod is None:
return None
return {
"GGMLOps": ops_mod.GGMLOps,
"gguf_sd_loader": loader_mod.gguf_sd_loader,
"GGUFModelPatcher": mod.GGUFModelPatcher,
}
except Exception:
return None
def _load_gguf_unet(unet_path):
"""Load a GGUF diffusion model and return MODEL."""
gguf = _get_gguf_module()
if gguf is None:
raise RuntimeError(
"[RecipeModelLoader] This workflow requires ComfyUI-GGUF, "
"but UnetLoaderGGUF is not available."
)
ops = gguf["GGMLOps"]()
sd, extra = gguf["gguf_sd_loader"](unet_path)
kwargs = {}
valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
if "metadata" in valid_params:
kwargs["metadata"] = extra.get("metadata", {})
model = comfy.sd.load_diffusion_model_state_dict(
sd,
model_options={"custom_operations": ops},
**kwargs,
)
if model is None:
raise RuntimeError(
f"[RecipeModelLoader] Could not detect model type of GGUF: {unet_path}"
)
model = gguf["GGUFModelPatcher"].clone(model)
model.patch_on_device = False
return model
# =========================================================
# Generic loading helpers
# =========================================================
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
WEIGHT_DTYPE_OPTIONS = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"]
def _short_display_name(name):
"""Return basename without known model extension for compact UI/text output."""
raw = str(name or "").strip()
if not raw:
return ""
base = os.path.basename(raw.replace("\\", "/"))
lower = base.lower()
for ext in MODEL_EXTENSIONS:
if lower.endswith(ext):
return base[:-len(ext)]
return os.path.splitext(base)[0]
def _build_model_options(weight_dtype):
"""Build model_options dict from weight_dtype selection."""
model_options = {}
if weight_dtype == "fp8_e4m3fn":
model_options["dtype"] = torch.float8_e4m3fn
elif weight_dtype == "fp8_e4m3fn_fast":
model_options["dtype"] = torch.float8_e4m3fn
model_options["fp8_optimizations"] = True
elif weight_dtype == "fp8_e5m2":
model_options["dtype"] = torch.float8_e5m2
return model_options
def _is_runtime_object(value):
"""True when value looks like a live Comfy runtime object, not workflow metadata."""
return value is not None and not isinstance(value, (str, int, float, bool, list, tuple, dict))
def _extract_preloaded_assets(workflow_data, selected_model_slot):
"""
Reuse already-loaded assets carried in workflow_data (e.g. from RecipeRenderer).
Returns (model, clip, vae) or None when passthrough is unavailable.
"""
if not isinstance(workflow_data, dict):
return None
# v2 recipe_data: runtime assets are model-scoped.
if int(workflow_data.get("version", 0) or 0) >= 2 and isinstance(workflow_data.get("models"), dict):
block = workflow_data.get("models", {}).get(selected_model_slot)
if isinstance(block, dict):
model = block.get("MODEL")
clip = block.get("CLIP")
vae = block.get("VAE")
if _is_runtime_object(model) and _is_runtime_object(clip) and _is_runtime_object(vae):
return (model, clip, vae)
model_key = "MODEL_B" if selected_model_slot == "model_b" else "MODEL_A"
model = workflow_data.get(model_key)
clip = workflow_data.get("CLIP")
vae = workflow_data.get("VAE")
if not _is_runtime_object(model):
return None
if not _is_runtime_object(clip):
return None
if not _is_runtime_object(vae):
return None
return (model, clip, vae)
def _resolve_path(name, folder_key_candidates):
"""
Resolve a model filename against one or more Comfy folder keys.
Tries get_full_path first (exact / relative path), then falls back to
scanning get_filename_list and matching by basename (with or without
extension). This handles models stored in subdirectories.
Returns full path or None.
"""
if not name:
return None
raw = str(name).strip()
if not raw:
return None
normalized = raw.replace("\\", "/")
base = os.path.basename(normalized).lower()
# Strip extension for fuzzy matching
base_no_ext = base
for ext in MODEL_EXTENSIONS:
if base_no_ext.endswith(ext):
base_no_ext = base_no_ext[:-len(ext)]
break
# Pass 1: try get_full_path (works when name is already a valid relative path)
for candidate in (raw, os.path.basename(normalized)):
for key in folder_key_candidates:
try:
path = folder_paths.get_full_path(key, candidate)
if path:
return path
except Exception:
pass
# Pass 2: scan filename lists and match by basename (handles subdirectories)
for key in folder_key_candidates:
try:
file_list = folder_paths.get_filename_list(key)
except Exception:
continue
for f in file_list:
f_normalized = f.replace("\\", "/")
# Exact relative-path match
if f_normalized == normalized:
return folder_paths.get_full_path(key, f)
f_base = os.path.basename(f_normalized).lower()
# Basename match (with extension)
if f_base == base:
return folder_paths.get_full_path(key, f)
# Basename match (without extension)
f_no_ext = f_base
for ext in MODEL_EXTENSIONS:
if f_no_ext.endswith(ext):
f_no_ext = f_no_ext[:-len(ext)]
break
if f_no_ext == base_no_ext:
return folder_paths.get_full_path(key, f)
return None
def _load_checkpoint_by_name(ckpt_name):
"""
Load checkpoint and return (MODEL, CLIP, VAE).
Uses standard checkpoint loading semantics.
"""
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
if not ckpt_path:
raise FileNotFoundError(f"[RecipeModelLoader] Checkpoint not found: {ckpt_name}")
out = comfy.sd.load_checkpoint_guess_config(
ckpt_path,
output_vae=True,
output_clip=True,
embedding_directory=folder_paths.get_folder_paths("embeddings"),
)
model, clip, vae = out[:3]
return model, clip, vae
def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
"""
Load a diffusion/UNet model and return MODEL.
If the name ends with .gguf, use the GGUF loader path.
"""
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
if not model_path:
raise FileNotFoundError(f"[RecipeModelLoader] Diffusion model not found: {model_name}")
if model_name.lower().endswith(".gguf"):
return _load_gguf_unet(model_path)
model_options = _build_model_options(weight_dtype)
model = comfy.sd.load_diffusion_model(model_path, model_options=model_options)
if model is None:
raise RuntimeError(f"[RecipeModelLoader] Could not load diffusion model: {model_name}")
return model
def _load_vae_by_name(vae_name):
"""
Load a VAE and return VAE.
"""
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
if not vae_path:
raise FileNotFoundError(f"[RecipeModelLoader] VAE not found: {vae_name}")
sd = comfy.utils.load_torch_file(vae_path)
return comfy.sd.VAE(sd=sd)
def _load_clip_by_names(clip_names, clip_type=""):
"""
Load CLIP from one or more filenames.
clip_names should be a list[str].
"""
if not clip_names:
return None
clip_paths = []
for name in clip_names:
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
if not clip_path:
raise FileNotFoundError(f"[RecipeModelLoader] CLIP not found: {name}")
clip_paths.append(clip_path)
clip_type = (clip_type or "").strip().lower()
# Map a few common values. If unknown, let Comfy infer/default.
clip_type_map = {
"stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sd": comfy.sd.CLIPType.STABLE_DIFFUSION,
"sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
"wan": comfy.sd.CLIPType.WAN,
"flux": comfy.sd.CLIPType.FLUX,
"hunyuan_video": comfy.sd.CLIPType.HUNYUAN_VIDEO,
}
load_kwargs = {
"ckpt_paths": clip_paths,
"embedding_directory": folder_paths.get_folder_paths("embeddings"),
}
if clip_type in clip_type_map:
load_kwargs["clip_type"] = clip_type_map[clip_type]
return comfy.sd.load_clip(**load_kwargs)
# =========================================================
# Node
# =========================================================
class WorkflowModelLoader:
CATEGORY = "Prompt Manager"
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
RETURN_NAMES = ("model", "clip", "vae")
FUNCTION = "get_model"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"manager_data": ("MANAGER_DATA", {
"tooltip": "manager_data containing model name strings to load.",
"forceInput": True,
}),
"model": (["model_a", "model_b", "model_c", "model_d"], {
"default": "model_a",
"tooltip": "Which model slot to load from recipe_data.",
}),
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
"default": "default",
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
}),
}
}
def get_model(self, manager_data, model="model_a", weight_dtype="default"):
workflow_data = manager_data
selected_model_slot = model
if selected_model_slot not in ("model_a", "model_b", "model_c", "model_d"):
selected_model_slot = "model_a"
# Initialize selected slot before normalization so v2 parsing can
# safely resolve per-slot loader/clip/vae fields.
self._model_key = selected_model_slot
self._weight_dtype = weight_dtype
passthrough_assets = _extract_preloaded_assets(workflow_data, selected_model_slot)
spec = self._normalize_spec(workflow_data)
loader_type = spec.get("loader_type", "").lower()
selected_name = spec.get(selected_model_slot, "")
selected_display_name = _short_display_name(selected_name)
if passthrough_assets is not None:
model_obj, clip_obj, vae_obj = passthrough_assets
clip_names = spec.get("clip") or []
vae_name = spec.get("vae", "")
ui_info = {
"model": selected_model_slot,
"model_name": selected_display_name or _short_display_name(spec.get("model_name", "")),
"loader_type": loader_type or "passthrough",
"model_kind": "passthrough",
"vae_name": vae_name,
"clip_names": clip_names,
"status": "ok",
"error_message": "",
"missing_name": "",
"uses_checkpoint_vae": False,
"uses_checkpoint_clip": False,
}
return {
"ui": {"workflow_model_loader_info": [ui_info]},
"result": (model_obj, clip_obj, vae_obj),
}
if loader_type == "checkpoint":
core_result = self._load_checkpoint_mode(spec)
elif loader_type in ("unet", "diffusion"):
core_result = self._load_unet_mode(spec)
else:
raise ValueError(
f"[RecipeModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
)
result = core_result
clip_names = spec.get("clip") or []
vae_name = spec.get("vae", "")
selected_lower = selected_name.lower()
if loader_type == "checkpoint":
model_kind = "checkpoint"
elif selected_lower.endswith(".gguf"):
model_kind = "gguf"
else:
model_kind = "diffusion"
ui_info = {
"model": selected_model_slot,
"model_name": selected_display_name,
"loader_type": loader_type,
"model_kind": model_kind,
"vae_name": vae_name,
"clip_names": clip_names,
"status": "ok",
"error_message": "",
"missing_name": "",
"uses_checkpoint_vae": (loader_type == "checkpoint" and not vae_name),
"uses_checkpoint_clip": (loader_type == "checkpoint" and len(clip_names) == 0),
}
return {
"ui": {"workflow_model_loader_info": [ui_info]},
"result": result,
}
@staticmethod
def _is_placeholder(value):
"""True for display-only strings like '(Default)', '(none)', etc."""
return isinstance(value, str) and value.startswith("(")
def _normalize_spec(self, spec):
spec = dict(spec or {})
spec["model_a"] = (spec.get("model_a") or "").strip()
spec["model_b"] = (spec.get("model_b") or "").strip()
spec["model_c"] = (spec.get("model_c") or "").strip()
spec["model_d"] = (spec.get("model_d") or "").strip()
spec["loader_type"] = (spec.get("loader_type") or "").strip()
spec["clip_type"] = (spec.get("clip_type") or "").strip()
# v2 recipe_data stores model config in per-slot blocks.
if int(spec.get("version", 0) or 0) >= 2 and isinstance(spec.get("models"), dict):
models = spec.get("models", {})
for key in ("model_a", "model_b", "model_c", "model_d"):
block = models.get(key)
if isinstance(block, dict):
model_name = (block.get("model") or "").strip() if isinstance(block.get("model"), str) else ""
if model_name:
spec[key] = model_name
selected_key = getattr(self, "_model_key", "model_a")
if selected_key not in ("model_a", "model_b", "model_c", "model_d"):
selected_key = "model_a"
selected_block = models.get(selected_key) if isinstance(models.get(selected_key), dict) else None
if isinstance(selected_block, dict):
loader_type = (selected_block.get("loader_type") or "").strip() if isinstance(selected_block.get("loader_type"), str) else ""
clip_type = (selected_block.get("clip_type") or "").strip() if isinstance(selected_block.get("clip_type"), str) else ""
vae_name = (selected_block.get("vae") or "").strip() if isinstance(selected_block.get("vae"), str) else ""
clip_names = selected_block.get("clip")
if loader_type:
spec["loader_type"] = loader_type
if clip_type:
spec["clip_type"] = clip_type
if vae_name:
spec["vae"] = vae_name
if isinstance(clip_names, list):
spec["clip"] = clip_names
elif isinstance(clip_names, str) and clip_names.strip():
spec["clip"] = [clip_names.strip()]
# VAE / CLIP: placeholders like '(Default)' mean "use what
# the checkpoint already provides" — normalise to empty.
vae = (spec.get("vae") or "").strip()
spec["vae"] = "" if self._is_placeholder(vae) else vae
clip = spec.get("clip") or []
spec["clip"] = [c for c in clip if c and not self._is_placeholder(c)]
return spec
def _load_checkpoint_mode(self, spec):
ckpt_name = spec.get(self._model_key, "")
if not ckpt_name:
return (
ExecutionBlocker(f"Missing checkpoint in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model, clip, vae = _load_checkpoint_by_name(ckpt_name)
clip_override = self._maybe_load_clip_override(spec)
if clip_override is not None:
clip = clip_override
vae_override = self._maybe_load_vae_override(spec)
if vae_override is not None:
vae = vae_override
if clip is None:
clip = ExecutionBlocker(f"No CLIP available for checkpoint '{ckpt_name}'")
if vae is None:
vae = ExecutionBlocker(f"No VAE available for checkpoint '{ckpt_name}'")
return (model, clip, vae)
def _load_unet_mode(self, spec):
model_name = spec.get(self._model_key, "")
if not model_name:
return (
ExecutionBlocker(f"Missing model in '{self._model_key}'"),
ExecutionBlocker("No CLIP available"),
ExecutionBlocker("No VAE available"),
)
model = _load_diffusion_model_by_name(model_name, self._weight_dtype)
clip = self._maybe_load_clip_override(spec)
vae = self._maybe_load_vae_override(spec)
if clip is None:
clip = ExecutionBlocker(
f"No explicit CLIP provided for diffusion model '{model_name}'"
)
if vae is None:
vae = ExecutionBlocker(
f"No explicit VAE provided for diffusion model '{model_name}'"
)
return (model, clip, vae)
def _maybe_load_clip_override(self, spec):
clip_list = spec.get("clip") or []
if len(clip_list) == 0:
return None
return _load_clip_by_names(clip_list, spec.get("clip_type", ""))
def _maybe_load_vae_override(self, spec):
vae_name = spec.get("vae", "")
if not vae_name:
return None
return _load_vae_by_name(vae_name)

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