Compare commits

..

4 Commits

Author SHA1 Message Date
Will Miao
7f51812c1e feat(nodes): add LoRA Syntax → Path node (#1015) 2026-07-16 19:57:29 +08:00
Will Miao
a9dc4d7b9d fix(widgets): reuse orphaned DOM containers after undo/redo in Vue render mode
In ComfyUI Vue render mode, WidgetDOM.vue reuses its component instance
during undo/redo without re-calling mountWidgetElement(), leaving newly
created widget containers detached from the DOM.

- AutocompleteTextWidget: scan for empty containers by ID prefix and reuse
- Loras widget: scan for empty .lm-loras-container elements and reuse
- Prevent duplicate event listeners by guarding listener setup on new
  containers only
- Keep container in DOM on cleanup (clearChildren instead of remove)
  so it can be found and reused by the next factory invocation
2026-07-16 18:54:00 +08:00
Will Miao
5d50ddb5d4 fix(ui): exit bulk mode after send-to-workflow completes 2026-07-16 18:54:00 +08:00
Will Miao
f86198d234 fix(loras): include folder prefix in context menu and bulk send-to-workflow
When using full path lora syntax, the context menu (single/bulk)
and bulk copy actions were passing only the file basename to
buildLoraSyntax(), ignoring the folder prefix. This caused the
output to look like legacy A1111 format even when full path mode
was enabled.

Aligns all entry points with ModelCard.handleSendToWorkflow(),
which correctly includes the folder prefix.

Also fixes selectAllVisibleModels() to cache the folder field,
preventing missing prefix on select-all-then-send flows.
2026-07-16 18:54:00 +08:00
11 changed files with 204 additions and 74 deletions

View File

@@ -16,6 +16,7 @@ try: # pragma: no cover - import fallback for pytest collection
from .py.nodes.lora_randomizer import LoraRandomizerLM
from .py.nodes.lora_cycler import LoraCyclerLM
from .py.nodes.lora_info import LoraInfoLM
from .py.nodes.lora_syntax_to_path import LoraSyntaxToPath
from .py.metadata_collector import init as init_metadata_collector
except (
ImportError
@@ -58,6 +59,9 @@ except (
).LoraRandomizerLM
LoraCyclerLM = importlib.import_module("py.nodes.lora_cycler").LoraCyclerLM
LoraInfoLM = importlib.import_module("py.nodes.lora_info").LoraInfoLM
LoraSyntaxToPath = importlib.import_module(
"py.nodes.lora_syntax_to_path"
).LoraSyntaxToPath
init_metadata_collector = importlib.import_module("py.metadata_collector").init
NODE_CLASS_MAPPINGS = {
@@ -78,6 +82,7 @@ NODE_CLASS_MAPPINGS = {
LoraRandomizerLM.NAME: LoraRandomizerLM,
LoraCyclerLM.NAME: LoraCyclerLM,
LoraInfoLM.NAME: LoraInfoLM,
LoraSyntaxToPath.NAME: LoraSyntaxToPath,
}
WEB_DIRECTORY = "./web/comfyui"

View File

@@ -1,6 +1,5 @@
import importlib
import logging
import re
import comfy.sd # type: ignore
import comfy.utils # type: ignore
@@ -14,6 +13,7 @@ from .utils import (
extract_lora_name,
get_loras_list,
nunchaku_load_lora,
parse_lora_syntax,
)
logger = logging.getLogger(__name__)
@@ -189,25 +189,10 @@ class LoraTextLoaderLM:
RETURN_NAMES = ("MODEL", "CLIP", "trigger_words", "loaded_loras")
FUNCTION = "load_loras_from_text"
def parse_lora_syntax(self, text):
"""Parse LoRA syntax from text input."""
pattern = r"<lora:([^:>]+):([^:>]+)(?::([^:>]+))?>"
matches = re.findall(pattern, text, re.IGNORECASE)
loras = []
for match in matches:
model_strength = float(match[1])
loras.append({
"name": match[0],
"model_strength": model_strength,
"clip_strength": float(match[2]) if match[2] else model_strength,
})
return loras
def load_loras_from_text(self, model, lora_syntax, clip=None, lora_stack=None):
"""Load LoRAs based on text syntax input."""
lora_entries = _collect_stack_entries(lora_stack)
for lora in self.parse_lora_syntax(lora_syntax):
for lora in parse_lora_syntax(lora_syntax):
lora_path, trigger_words = get_lora_info_absolute(lora["name"])
lora_entries.append({
"name": lora["name"],

View File

@@ -0,0 +1,62 @@
"""Node to resolve `<lora:name:strength>` syntax to absolute file system paths.
Takes the loaded_loras / active_loras STRING output from LoraLoaderLM or
LoraStackerLM and resolves each lora name to its absolute path on disk via
the scanner cache. Unknown names are returned as-is.
"""
import logging
from ..utils.utils import get_lora_info_absolute
from .utils import parse_lora_syntax
logger = logging.getLogger(__name__)
class LoraSyntaxToPath:
NAME = "LoRA Syntax → Path (LoraManager)"
CATEGORY = "Lora Manager/utils"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"lora_syntax": (
"STRING",
{
"forceInput": True,
"multiline": True,
"tooltip": (
"<lora:name:strength> formatted text from "
"loaded_loras / active_loras output"
),
},
),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("paths",)
FUNCTION = "resolve"
def resolve(self, lora_syntax: str) -> tuple[str]:
"""Parse <lora:...> syntax and resolve each name to its absolute path."""
if not lora_syntax or not lora_syntax.strip():
logger.info("Received empty lora_syntax input")
return ("",)
parsed = parse_lora_syntax(lora_syntax)
if not parsed:
logger.info("No valid <lora:...> entries found in input")
return ("",)
paths: list[str] = []
for entry in parsed:
try:
absolute_path, _ = get_lora_info_absolute(entry["name"])
paths.append(absolute_path)
except Exception:
logger.warning("Failed to resolve lora '%s', skipping", entry["name"])
continue
return ("\n".join(paths),)

View File

@@ -36,6 +36,7 @@ any_type = AnyType("*")
# Common methods extracted from lora_loader.py and lora_stacker.py
import os
import re
import logging
import copy
import sys
@@ -69,6 +70,25 @@ def extract_lora_name(lora_path):
return apply_lora_syntax_format(name_no_ext)
def parse_lora_syntax(text: str) -> list[dict]:
"""Parse <lora:name:strength> syntax from text input into a list of dicts.
Each entry contains: name, model_strength, clip_strength.
Supports both ``<lora:name:strength>`` and ``<lora:name:model_strength:clip_strength>``.
"""
pattern = r"<lora:([^:>]+):([^:>]+)(?::([^:>]+))?>"
matches = re.findall(pattern, text, re.IGNORECASE)
loras = []
for match in matches:
model_strength = float(match[1])
loras.append({
"name": match[0],
"model_strength": model_strength,
"clip_strength": float(match[2]) if match[2] else model_strength,
})
return loras
def get_loras_list(kwargs):
"""Helper to extract loras list from either old or new kwargs format"""
if "loras" not in kwargs:

View File

@@ -152,7 +152,9 @@ export class LoraContextMenu extends BaseContextMenu {
sendLoraToWorkflow(replaceMode) {
const card = this.currentCard;
const usageTips = JSON.parse(card.dataset.usage_tips || '{}');
const loraSyntax = buildLoraSyntax(card.dataset.file_name, usageTips);
const folder = card.dataset.folder || '';
const loraName = folder ? `${folder}/${card.dataset.file_name}` : card.dataset.file_name;
const loraSyntax = buildLoraSyntax(loraName, usageTips);
sendLoraToWorkflow(loraSyntax, replaceMode, 'lora');
}

View File

@@ -397,6 +397,7 @@ export class BulkManager {
const updated = {
...existing,
fileName: card.dataset.file_name ?? existing.fileName,
folder: card.dataset.folder ?? existing.folder,
usageTips: card.dataset.usage_tips ?? existing.usageTips,
modelName: card.dataset.name ?? existing.modelName,
};
@@ -494,7 +495,8 @@ export class BulkManager {
if (metadata) {
const usageTips = JSON.parse(metadata.usageTips || '{}');
loraSyntaxes.push(buildLoraSyntax(metadata.fileName, usageTips));
const loraName = metadata.folder ? `${metadata.folder}/${metadata.fileName}` : metadata.fileName;
loraSyntaxes.push(buildLoraSyntax(loraName, usageTips));
} else {
missingLoras.push(filepath);
}
@@ -537,7 +539,8 @@ export class BulkManager {
if (metadata) {
const usageTips = JSON.parse(metadata.usageTips || '{}');
loraSyntaxes.push(buildLoraSyntax(metadata.fileName, usageTips));
const loraName = metadata.folder ? `${metadata.folder}/${metadata.fileName}` : metadata.fileName;
loraSyntaxes.push(buildLoraSyntax(loraName, usageTips));
} else {
missingLoras.push(filepath);
}
@@ -553,7 +556,8 @@ export class BulkManager {
return;
}
await sendLoraToWorkflow(loraSyntaxes.join(', '), replaceMode, 'lora');
const exitBulkMode = () => { if (state.bulkMode) this.toggleBulkMode(); };
await sendLoraToWorkflow(loraSyntaxes.join(', '), replaceMode, 'lora', exitBulkMode);
}
async _sendAllEmbeddingsToWorkflow() {
@@ -575,7 +579,8 @@ export class BulkManager {
}
const joinedCode = embeddingCodes.join(', ');
await sendEmbeddingToWorkflow(joinedCode);
const exitBulkMode = () => { if (state.bulkMode) this.toggleBulkMode(); };
await sendEmbeddingToWorkflow(joinedCode, exitBulkMode);
}
showBulkDeleteModal() {
@@ -674,6 +679,7 @@ export class BulkManager {
const modelId = this.parseModelId(item?.civitai?.modelId);
metadataCache.set(item.file_path, {
fileName: item.file_name,
folder: item.folder || '',
usageTips: item.usage_tips || '{}',
modelName: item.name || item.file_name,
...(modelId !== null ? { modelId } : {})

View File

@@ -656,7 +656,7 @@ async function ensureRelativeModelPath(modelPath, collectionType) {
* @param {string} syntaxType - The type of syntax ('lora' or 'recipe')
* @returns {Promise<boolean>} - Whether the operation was successful
*/
export async function sendLoraToWorkflow(loraSyntax, replaceMode = false, syntaxType = 'lora') {
export async function sendLoraToWorkflow(loraSyntax, replaceMode = false, syntaxType = 'lora', onComplete = null) {
const registry = await fetchWorkflowRegistry();
if (!registry) {
return false;
@@ -681,7 +681,9 @@ export async function sendLoraToWorkflow(loraSyntax, replaceMode = false, syntax
}
if (nodeKeys.length === 1) {
return await sendLoraToNodes([nodeKeys[0]], loraNodes, loraSyntax, replaceMode, syntaxType);
const result = await sendLoraToNodes([nodeKeys[0]], loraNodes, loraSyntax, replaceMode, syntaxType);
if (result && typeof onComplete === 'function') onComplete();
return result;
}
const actionType =
@@ -695,8 +697,11 @@ export async function sendLoraToWorkflow(loraSyntax, replaceMode = false, syntax
showNodeSelector(loraNodes, {
actionType,
actionMode,
onSend: (selectedNodeIds) =>
sendLoraToNodes(selectedNodeIds, loraNodes, loraSyntax, replaceMode, syntaxType),
onSend: async (selectedNodeIds) => {
const result = await sendLoraToNodes(selectedNodeIds, loraNodes, loraSyntax, replaceMode, syntaxType);
if (result && typeof onComplete === 'function') onComplete();
return result;
},
});
return true;
}
@@ -967,7 +972,7 @@ async function sendTextToNodes(nodeIds, nodesMap, text, mode, messages = {}) {
}
}
export async function sendEmbeddingToWorkflow(embeddingCode) {
export async function sendEmbeddingToWorkflow(embeddingCode, onComplete = null) {
const registry = await fetchWorkflowRegistry();
if (!registry) {
return false;
@@ -995,8 +1000,11 @@ export async function sendEmbeddingToWorkflow(embeddingCode) {
missingTargetMessage: translate('uiHelpers.workflow.noTargetNodeSelected', {}, 'No target node selected'),
};
const handleSend = (selectedNodeIds) =>
sendTextToNodes(selectedNodeIds, textNodes, embeddingCode, 'append', messages);
const handleSend = async (selectedNodeIds) => {
const result = await sendTextToNodes(selectedNodeIds, textNodes, embeddingCode, 'append', messages);
if (result && typeof onComplete === 'function') onComplete();
return result;
};
if (nodeKeys.length === 1) {
return await handleSend([nodeKeys[0]]);

View File

@@ -74,7 +74,7 @@ function forwardMiddleMouseToCanvas(container: HTMLElement) {
})
}
const vueApps = new Map<number, VueApp>()
const vueApps = new Map<number | string, VueApp>()
let autocompleteTextWidgetInstanceId = 0
export function createAutocompleteTextWidgetInstanceId() {
@@ -405,7 +405,6 @@ function createJsonDisplayWidget(node) {
return { widget }
}
// Store nodeData options per widget type for autocomplete widgets
const widgetInputOptions: Map<string, { placeholder?: string }> = new Map()
function getSerializableWidgetNames(node: any): string[] {
@@ -722,16 +721,30 @@ function createAutocompleteTextWidgetFactory(
inputOptions: { placeholder?: string } = {}
) {
const metadataWidgetName = `__lm_autocomplete_meta_${widgetName}`
const instanceId = createAutocompleteTextWidgetInstanceId()
const container = document.createElement('div')
container.id = `autocomplete-text-widget-${instanceId}`
container.style.width = '100%'
container.style.height = '100%'
container.style.display = 'flex'
container.style.flexDirection = 'column'
container.style.overflow = 'hidden'
forwardMiddleMouseToCanvas(container)
let container: HTMLElement | null = null
const existingContainers = document.querySelectorAll<HTMLElement>(
'[id^="autocomplete-text-widget-"]'
)
for (const el of existingContainers) {
if (el.children.length === 0) {
container = el
break
}
}
if (!container) {
const instanceId = String(createAutocompleteTextWidgetInstanceId())
container = document.createElement('div')
container.id = `autocomplete-text-widget-${instanceId}`
container.style.width = '100%'
container.style.height = '100%'
container.style.display = 'flex'
container.style.flexDirection = 'column'
container.style.overflow = 'hidden'
forwardMiddleMouseToCanvas(container)
}
// Store textarea reference on the container element so cloned widgets can access it
// This is necessary because when widgets are promoted to subgraph nodes,
@@ -810,15 +823,10 @@ function createAutocompleteTextWidgetFactory(
})
vueApp.mount(container)
const appKey = instanceId
const appKey = container.id
vueApps.set(appKey, vueApp)
if (maxHeight) {
// Set only minHeight as a true minimum — remove maxHeight so the
// textarea can grow when the user resizes it in app mode (where
// [&_textarea]:resize-y applies). Graph mode (canvas & Vue render)
// is unaffected because LiteGraph's layout system still governs
// the widget area size.
container.style.minHeight = `${AUTOCOMPLETE_TEXT_WIDGET_MIN_HEIGHT}px`
}
@@ -830,10 +838,14 @@ function createAutocompleteTextWidgetFactory(
)
}
widget.onRemove = createVueWidgetCleanup(vueApp, () => {
const vueCleanup = createVueWidgetCleanup(vueApp, () => {
vueApps.delete(appKey)
})
widget.onRemove = () => {
vueCleanup()
}
// Return minWidth/minHeight hints so ComfyUI's _initialMinSize mechanism
// sets a sensible initial node width (and height for prompt/embeddings).
// loras modelType retains its existing height constraints (getMaxHeight: 100).
@@ -1007,9 +1019,7 @@ app.registerExtension({
info.widgets_values = [...(info.widgets_values ?? []), null]
}
const result = originalConfigure?.apply(this, arguments)
return result
return originalConfigure?.apply(this, arguments)
}
}

View File

@@ -14,12 +14,31 @@ import { getStrengthStepPreference } from "./settings.js";
export function addLorasWidget(node, name, opts, callback) {
ensureLmStyles();
// Create container for loras
const container = document.createElement("div");
container.className = "lm-loras-container";
// Create container for loras — search for an empty container already
// in the DOM first. During undo/redo in ComfyUI Vue render mode,
// WidgetDOM.vue reuses its component without re-calling
// mountWidgetElement(), so we must reuse the existing DOM element
// instead of creating an orphaned replacement.
let container = null;
let reuseExisting = false;
const existingContainers = document.querySelectorAll('.lm-loras-container');
for (const el of existingContainers) {
if (el.children.length === 0) {
container = el;
reuseExisting = true;
break;
}
}
forwardMiddleMouseToCanvas(container);
forwardWheelToCanvas(container);
if (!container) {
container = document.createElement("div");
container.className = "lm-loras-container";
}
if (!reuseExisting) {
forwardMiddleMouseToCanvas(container);
forwardWheelToCanvas(container);
}
// Set initial height using CSS variables approach
const defaultHeight = 200;
@@ -29,10 +48,8 @@ export function addLorasWidget(node, name, opts, callback) {
// scrolls when content exceeds the allocated space.
container.style.setProperty('--comfy-widget-min-height', `${defaultHeight}px`);
if (typeof LiteGraph !== 'undefined' && LiteGraph.vueNodesMode) {
if (!reuseExisting && typeof LiteGraph !== 'undefined' && LiteGraph.vueNodesMode) {
container.classList.add('lm-vue-node');
// Window capture-phase hook: scroll the widget instead of zooming the canvas
// when the wheel is over a scrollable loras list.
enableListWheelScroll(container);
}
@@ -732,9 +749,10 @@ export function addLorasWidget(node, name, opts, callback) {
widget.callback = callback;
widget.onRemove = () => {
container.remove();
while (container.firstChild) {
container.removeChild(container.firstChild);
}
previewTooltip.cleanup();
// Remove keyboard event listener
container.removeEventListener('keydown', handleKeyboardNavigation);
};

View File

@@ -16081,15 +16081,27 @@ function createLoraInfoWidget(node) {
function createAutocompleteTextWidgetFactory(node, widgetName, modelType, inputOptions = {}) {
var _a2, _b, _c;
const metadataWidgetName = `__lm_autocomplete_meta_${widgetName}`;
const instanceId = createAutocompleteTextWidgetInstanceId();
const container = document.createElement("div");
container.id = `autocomplete-text-widget-${instanceId}`;
container.style.width = "100%";
container.style.height = "100%";
container.style.display = "flex";
container.style.flexDirection = "column";
container.style.overflow = "hidden";
forwardMiddleMouseToCanvas(container);
let container = null;
const existingContainers = document.querySelectorAll(
'[id^="autocomplete-text-widget-"]'
);
for (const el of existingContainers) {
if (el.children.length === 0) {
container = el;
break;
}
}
if (!container) {
const instanceId = String(createAutocompleteTextWidgetInstanceId());
container = document.createElement("div");
container.id = `autocomplete-text-widget-${instanceId}`;
container.style.width = "100%";
container.style.height = "100%";
container.style.display = "flex";
container.style.flexDirection = "column";
container.style.overflow = "hidden";
forwardMiddleMouseToCanvas(container);
}
const widgetElementRef = { inputEl: void 0 };
container.__widgetInputEl = widgetElementRef;
const metadataWidget = node.addWidget("text", metadataWidgetName, {
@@ -16154,7 +16166,7 @@ function createAutocompleteTextWidgetFactory(node, widgetName, modelType, inputO
ripple: false
});
vueApp.mount(container);
const appKey = instanceId;
const appKey = container.id;
vueApps.set(appKey, vueApp);
if (maxHeight) {
container.style.minHeight = `${AUTOCOMPLETE_TEXT_WIDGET_MIN_HEIGHT}px`;
@@ -16166,9 +16178,12 @@ function createAutocompleteTextWidgetFactory(node, widgetName, modelType, inputO
typeof LiteGraph !== "undefined" && LiteGraph.vueNodesMode
);
}
widget.onRemove = createVueWidgetCleanup(vueApp, () => {
const vueCleanup = createVueWidgetCleanup(vueApp, () => {
vueApps.delete(appKey);
});
widget.onRemove = () => {
vueCleanup();
};
const minWidth = AUTOCOMPLETE_TEXT_MIN_WIDTH_DEFAULT;
const minHeight = modelType === "loras" ? void 0 : AUTOCOMPLETE_TEXT_MIN_HEIGHT_DEFAULT;
return { widget, minWidth, minHeight };
@@ -16315,8 +16330,7 @@ app$1.registerExtension({
if (bypassResult) {
info.widgets_values = [...info.widgets_values ?? [], null];
}
const result = originalConfigure == null ? void 0 : originalConfigure.apply(this, arguments);
return result;
return originalConfigure == null ? void 0 : originalConfigure.apply(this, arguments);
};
}
if (LORA_CHAIN_NODE_TYPES$1.includes(comfyClass)) {

File diff suppressed because one or more lines are too long