Vendor complete MiniMax H3 upstream packs

This commit is contained in:
2026-10-20 13:44:50 +00:00
parent 559178f639
commit ba78f2be9d
25 changed files with 6920 additions and 2 deletions
+22 -2
View File
@@ -1,9 +1,29 @@
# DumasNodes
## Vendored MiniMax H3 packs
DumasNodes contains complete, license-preserving source copies of the three
upstream packs used by the MiniMax H3 workflow:
- `vendor/dumas_h3_continuum/`
- `vendor/dumas_minimax_h3_refmod/`
- `vendor/dumas_h3_refmod_picker/`
Their registrations and browser extensions are loaded by DUMAS, and their
display names are prefixed with `DUMAS`. The upstream node IDs are retained so
the full upstream UI and saved workflows remain compatible. Do not install the
three original packs at the same time as this vendored copy, or ComfyUI will
load duplicate node IDs and duplicate server routes.
The upstream source is imported as git subtrees, making future reviews and
selective updates possible without losing provenance. DUMAS-specific changes
belong outside `vendor/` unless an upstream implementation is intentionally
being amended.
Generic ComfyUI utility nodes under the Dumas brand. MiniMax H3-specific
nodes are grouped under `Dumas/MiniMax H3/...` so they can be installed
alongside the maintained upstream `ComfyUI-H3-Continuum` pack without
overriding its node IDs.
as the self-contained H3 installation; do not install the separate upstream
packs alongside this vendored copy.
## Sequential video assembly
+6
View File
@@ -35,6 +35,10 @@ from .dumas_h3_refmod_picker import (
NODE_CLASS_MAPPINGS as H3_REFMOD_PICKER_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as H3_REFMOD_PICKER_NODE_DISPLAY_NAME_MAPPINGS,
)
from .dumas_vendored_nodes import (
NODE_CLASS_MAPPINGS as VENDORED_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as VENDORED_NODE_DISPLAY_NAME_MAPPINGS,
)
NODE_CLASS_MAPPINGS = {}
NODE_CLASS_MAPPINGS.update(JSON_NODE_CLASS_MAPPINGS)
@@ -45,6 +49,7 @@ NODE_CLASS_MAPPINGS.update(H3_PROMPT_NODE_CLASS_MAPPINGS)
NODE_CLASS_MAPPINGS.update(H3_UPSCALE_NODE_CLASS_MAPPINGS)
NODE_CLASS_MAPPINGS.update(H3_REFMOD_NODE_CLASS_MAPPINGS)
NODE_CLASS_MAPPINGS.update(H3_REFMOD_PICKER_NODE_CLASS_MAPPINGS)
NODE_CLASS_MAPPINGS.update(VENDORED_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS.update(JSON_NODE_DISPLAY_NAME_MAPPINGS)
@@ -55,6 +60,7 @@ NODE_DISPLAY_NAME_MAPPINGS.update(H3_PROMPT_NODE_DISPLAY_NAME_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(H3_UPSCALE_NODE_DISPLAY_NAME_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(H3_REFMOD_NODE_DISPLAY_NAME_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(H3_REFMOD_PICKER_NODE_DISPLAY_NAME_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(VENDORED_NODE_DISPLAY_NAME_MAPPINGS)
WEB_DIRECTORY = "./js"
+51
View File
@@ -0,0 +1,51 @@
"""Namespaced registrations for the complete vendored H3 upstream packs.
The source is kept under ``vendor/`` with its licenses and upstream layout
intact. This module is the only integration point: every upstream node gets a
DUMAS-prefixed ComfyUI id so the original packs can remain installed without
node-id collisions.
"""
from __future__ import annotations
import importlib
import logging
_PACKAGES = (
("vendor.dumas_h3_continuum", "H3 Continuum"),
("vendor.dumas_minimax_h3_refmod", "MiniMax H3 RefMod"),
("vendor.dumas_h3_refmod_picker", "H3 RefMod Picker"),
)
def _load_pack(package_name):
try:
return importlib.import_module(package_name)
except Exception:
logging.getLogger("DumasNodes").exception(
"Could not load vendored upstream pack %s", package_name,
)
return None
def _namespaced_mappings():
mappings = {}
display = {}
for package_name, label in _PACKAGES:
pack = _load_pack(package_name)
if pack is None:
continue
source_mappings = getattr(pack, "NODE_CLASS_MAPPINGS", {}) or {}
source_display = getattr(pack, "NODE_DISPLAY_NAME_MAPPINGS", {}) or {}
for node_id, node_class in source_mappings.items():
# Keep upstream IDs so the complete upstream web UI and saved
# workflows remain functional. The original packs must not also be
# installed, otherwise ComfyUI will see duplicate node IDs.
mappings[node_id] = node_class
original_name = source_display.get(node_id, node_id)
display[node_id] = f"DUMAS {label} · {original_name}"
return mappings, display
NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = _namespaced_mappings()
+28
View File
@@ -0,0 +1,28 @@
// Load the complete vendored upstream web extensions through DUMAS's single
// ComfyUI WEB_DIRECTORY. The source files remain under vendor/ with their
// original licenses; this file only makes their UI available from DumasNodes.
const modules = [
"./vendor/dumas_h3_continuum/decode_cache_helper.js",
"./vendor/dumas_h3_continuum/easy_bypass_toggle.js",
"./vendor/dumas_h3_continuum/easy_load_audio.js",
"./vendor/dumas_h3_continuum/easy_load_image.js",
"./vendor/dumas_h3_continuum/easy_load_video.js",
"./vendor/dumas_h3_continuum/easy_v38.js",
"./vendor/dumas_h3_continuum/project_id.js",
"./vendor/dumas_h3_continuum/reference_audio_ui.js",
"./vendor/dumas_h3_continuum/reference_image_ui.js",
"./vendor/dumas_h3_continuum/reference_images_v39.js",
"./vendor/dumas_h3_continuum/storage_settings.js",
"./vendor/dumas_h3_continuum/video_reference_mode_ui.js",
"./vendor/dumas_minimax_h3_refmod/library_dialog.js",
"./vendor/dumas_minimax_h3_refmod/refmod_apply.js",
"./vendor/dumas_minimax_h3_refmod/refmod_creation_labels.js",
"./vendor/dumas_minimax_h3_refmod/refmod_library.js",
"./vendor/dumas_minimax_h3_refmod/refmod_slots.js",
"./vendor/dumas_h3_refmod_picker/refmod_create.js",
"./vendor/dumas_h3_refmod_picker/refmod_loader.js",
"./vendor/dumas_h3_refmod_picker/visual_refmod_picker.js",
];
for (const module of modules) import(module);
+105
View File
@@ -0,0 +1,105 @@
import { app } from "../../scripts/app.js";
const NODE_CLASS = "H3DecodeCacheHelper";
const MAX_TOKEN = 2147483647;
function isJapanese() {
let locale = "";
try {
locale = String(app?.ui?.settings?.getSettingValue?.("Comfy.Locale") || "");
} catch {}
if (!locale) {
locale = String(
globalThis.document?.documentElement?.lang
|| globalThis.navigator?.language
|| "en",
);
}
return /^ja(?:-|$)/i.test(locale);
}
function labels() {
if (isJapanese()) {
return {
button: "キャッシュをクリア",
tooltip: "次回QueueでこのHelperのキャッシュを破棄します。次回は通常Decodeとなります。普段は操作不要です。",
};
}
return {
button: "Clear cache",
tooltip: "Clear this Helper's cache on the next Queue. The next run uses normal Decode. Usually no action is needed.",
};
}
// Keep the backend widget in its original position. Only its presentation is
// hidden; Core still serializes and sends reset_token as an INT.
function hideToken(widget) {
widget.hidden = true;
widget.options ||= {};
widget.options.hidden = true;
widget.type = "converted-widget";
widget.computeSize = () => [0, -4];
}
function withoutButton(node, button, operation) {
const index = node.widgets?.indexOf(button) ?? -1;
if (index >= 0) node.widgets.splice(index, 1);
try {
return operation();
} finally {
if (index >= 0) node.widgets.splice(index, 0, button);
}
}
export function configureDecodeCacheHelper(node) {
if (node?.comfyClass !== NODE_CLASS && node?.type !== NODE_CLASS) return;
const token = node.widgets?.find((widget) => widget.name === "reset_token");
if (!token || typeof node.addWidget !== "function") return;
if (!node.__h3DecodeCacheClearButton) {
const text = labels();
// Create the control before hiding the numeric widget, so a failed
// control installation leaves the traditional input available.
const button = node.addWidget("button", text.button, null, () => {
const current = node.widgets?.find((widget) => widget.name === "reset_token");
if (!current) return;
const value = Number(current.value);
if (!Number.isInteger(value) || value < 0 || value > MAX_TOKEN) return;
// Wrap only at the backend's INT limit; never submit an invalid INT.
current.value = value === MAX_TOKEN ? 0 : value + 1;
node.setDirtyCanvas?.(true, true);
}, { serialize: false });
button.serialize = false;
button.options ||= {};
button.options.serialize = false;
button.tooltip = text.tooltip;
node.__h3DecodeCacheClearButton = button;
// Some frontend versions assign widgets_values by index even for
// non-serialized controls. Exclude the button from both operations.
const serialize = node.serialize;
if (typeof serialize === "function") {
node.serialize = function (...args) {
return withoutButton(this, button, () => serialize.apply(this, args));
};
}
const configure = node.configure;
if (typeof configure === "function") {
node.configure = function (...args) {
const result = withoutButton(this, button, () => configure.apply(this, args));
configureDecodeCacheHelper(this);
return result;
};
}
}
hideToken(token);
node.setDirtyCanvas?.(true, true);
}
app.registerExtension({
name: "H3Continuum.DecodeCacheHelper.ClearButton",
nodeCreated: configureDecodeCacheHelper,
loadedGraphNode: configureDecodeCacheHelper,
afterConfigureGraph() {
for (const node of app.graph?._nodes || []) configureDecodeCacheHelper(node);
},
});
+111
View File
@@ -0,0 +1,111 @@
// Convenience toggles delegate to Core node.mode; Core owns persistence/drawing.
const NODE_MODE_ALWAYS =
typeof LiteGraph !== "undefined" && Number.isInteger(LiteGraph.ALWAYS)
? LiteGraph.ALWAYS : 0;
const NODE_MODE_BYPASS =
typeof LiteGraph !== "undefined" && Number.isInteger(LiteGraph.BYPASS)
? LiteGraph.BYPASS : 4;
function isConfiguredNode(node, nodeClass) {
return node?.comfyClass === nodeClass || node?.type === nodeClass;
}
export function findEasyBypassWidget(node) {
const name = node.__h3EasyBypassToggle?.widgetName;
return name ? node.widgets?.find((widget) => widget.name === name) : undefined;
}
function syncWidgetFromMode(node) {
const widget = findEasyBypassWidget(node);
if (widget) widget.value = node.mode === NODE_MODE_ALWAYS;
}
function findModeDescriptor(node) {
for (let owner = node; owner; owner = Object.getPrototypeOf(owner)) {
const descriptor = Object.getOwnPropertyDescriptor(owner, "mode");
if (descriptor) return descriptor;
}
return undefined;
}
function installModeSourceOfTruth(node) {
if (node.__h3EasyBypassModeObserved) return true;
const own = Object.getOwnPropertyDescriptor(node, "mode");
if (own?.configurable === false) return false;
const descriptor = findModeDescriptor(node);
const accessor = descriptor && ("get" in descriptor || "set" in descriptor);
// Never replace a read-only property or manufacture a second store value.
if (accessor && (!descriptor.get || !descriptor.set)) return false;
if (descriptor && !accessor && descriptor.writable === false) return false;
let currentMode = Number(node.mode ?? NODE_MODE_ALWAYS);
Object.defineProperty(node, "mode", {
configurable: true,
enumerable: own?.enumerable ?? descriptor?.enumerable ?? true,
get() {
return accessor ? descriptor.get.call(this) : currentMode;
},
set(value) {
if (accessor) descriptor.set.call(this, value);
else currentMode = Number(value);
syncWidgetFromMode(this);
},
});
node.__h3EasyBypassModeObserved = true;
return true;
}
function setModeFromToggle(node, enabled) {
node.mode = enabled ? NODE_MODE_ALWAYS : NODE_MODE_BYPASS;
syncWidgetFromMode(node);
node.graph?.change?.();
node.setDirtyCanvas?.(true, true);
}
export function configureEasyBypassToggleNode(
node, { nodeClass, widgetName, tooltip },
) {
if (!isConfiguredNode(node, nodeClass)) return;
node.__h3EasyBypassToggle = { nodeClass, widgetName };
let widget = findEasyBypassWidget(node);
if (!widget) {
widget = node.addWidget(
"toggle", widgetName, node.mode === NODE_MODE_ALWAYS,
(value) => setModeFromToggle(node, Boolean(value)),
{ on: "ON", off: "OFF", serialize: false },
);
widget.serialize = false; // Workflow persistence.
widget.options ||= {};
widget.options.serialize = false; // API prompt serialization.
widget.tooltip = tooltip;
// Append only. Never splice/reassign widgets in draw/serialize/configure:
// newer Core uses a stable mutation view backed by its widget store.
}
if (!installModeSourceOfTruth(node)) {
console.warn(`${nodeClass}: native mode could not be observed; use Core Bypass.`);
}
syncWidgetFromMode(node);
node.setDirtyCanvas?.(true, true);
}
// Retained for existing callers; new Video Adapter has no Enable widget.
export function configureExistingEasyBypassWidgetNode(
node, { nodeClass, widgetNames },
) {
if (!isConfiguredNode(node, nodeClass)) return;
const names = Array.isArray(widgetNames) ? widgetNames : [widgetNames];
const widget = node.widgets?.find((item) => names.includes(item.name));
if (!widget) return;
node.__h3EasyBypassToggle = { nodeClass, widgetName: widget.name };
if (!widget.__h3EasyBypassCallbackObserved) {
const originalCallback = widget.callback;
widget.callback = function (value, ...args) {
const result = originalCallback?.call(this, value, ...args);
setModeFromToggle(node, Boolean(value));
return result;
};
widget.__h3EasyBypassCallbackObserved = true;
}
installModeSourceOfTruth(node);
if (node.mode === NODE_MODE_BYPASS) syncWidgetFromMode(node);
else setModeFromToggle(node, Boolean(widget.value));
}
+69
View File
@@ -0,0 +1,69 @@
import { app } from "../../scripts/app.js";
import { configureEasyBypassToggleNode } from "./easy_bypass_toggle.js";
const EASY_LOAD_AUDIO_CLASS = "H3EasyLoadAudio";
function configureEasyLoadAudioNode(node) {
if (
node?.comfyClass !== EASY_LOAD_AUDIO_CLASS &&
node?.type !== EASY_LOAD_AUDIO_CLASS
) {
return;
}
// A frontend-only convenience control must never make the Core loader
// itself unplaceable. Some ComfyUI frontend paths initialize upload
// widgets later than nodeCreated; fail open and keep the native node.
try {
configureEasyBypassToggleNode(node, {
nodeClass: EASY_LOAD_AUDIO_CLASS,
widgetName: "Enable Audio",
tooltip:
"ON runs Core Load Audio. OFF uses ComfyUI native Bypass and behaves like an unconnected optional audio input.",
});
} catch (error) {
console.warn(
"H3 Easy Load Audio bypass control was skipped; the Core audio loader remains available.",
error,
);
}
}
app.registerExtension({
name: "H3Continuum.EasyLoadAudio",
beforeRegisterNodeDef(nodeType, nodeData) {
if (
nodeType?.prototype?.comfyClass !== EASY_LOAD_AUDIO_CLASS &&
nodeData?.name !== EASY_LOAD_AUDIO_CLASS
) {
return;
}
const required = nodeData?.input?.required;
if (!required?.audio?.[1]?.audio_upload || required.audioUI) return;
// ComfyUI Frontend 1.49.x adds AUDIOUPLOAD to every audio_upload
// schema, but adds its required AUDIO_UI preview only to a hard-coded
// list containing Core LoadAudio. Insert the same Core preview widget
// before AUDIOUPLOAD so the upload callback always receives it.
const { upload, ...inputs } = required;
nodeData.input.required = {
...inputs,
audioUI: ["AUDIO_UI", {}],
...(upload ? { upload } : {}),
};
},
nodeCreated(node) {
configureEasyLoadAudioNode(node);
},
loadedGraphNode(node) {
configureEasyLoadAudioNode(node);
},
afterConfigureGraph() {
for (const node of app.graph?._nodes || []) configureEasyLoadAudioNode(node);
},
});
+29
View File
@@ -0,0 +1,29 @@
import { app } from "../../scripts/app.js";
import { configureEasyBypassToggleNode } from "./easy_bypass_toggle.js";
const EASY_LOAD_IMAGE_CLASS = "H3EasyLoadImage";
function configureEasyLoadImageNode(node) {
configureEasyBypassToggleNode(node, {
nodeClass: EASY_LOAD_IMAGE_CLASS,
widgetName: "Enable Image",
tooltip:
"ON runs Core Load Image. OFF uses ComfyUI native Bypass and behaves like an unconnected optional image input.",
});
}
app.registerExtension({
name: "H3Continuum.EasyLoadImage",
nodeCreated(node) {
configureEasyLoadImageNode(node);
},
loadedGraphNode(node) {
configureEasyLoadImageNode(node);
},
afterConfigureGraph() {
for (const node of app.graph?._nodes || []) configureEasyLoadImageNode(node);
},
});
+3
View File
@@ -0,0 +1,3 @@
// Legacy H3ContinuumLoadVideo keeps its saved backend enable_video input.
// Do not mirror it into node.mode or alter Core widget arrays/drawing.
// New workflows use Core LoadVideo -> H3ContinuumVideoAdapter (no Enable).
+135
View File
@@ -0,0 +1,135 @@
import { app } from "../../scripts/app.js";
const EASY_NODE_CLASS = "H3ContinuumEasyV38";
const CUSTOM_PRESET = "Custom";
const STORAGE_ENABLED = "Save + Auto Resume";
function findWidget(node, name) {
return node.widgets?.find((widget) => widget.name === name);
}
function setWidgetVisible(widget, visible) {
if (!widget) return;
if (!widget.__h3EasyOriginal) {
widget.__h3EasyOriginal = {
type: widget.type,
computeSize: widget.computeSize,
hidden: widget.hidden,
optionsHidden: widget.options?.hidden,
};
}
widget.options ||= {};
if (visible) {
const original = widget.__h3EasyOriginal;
widget.type = original.type;
widget.computeSize = original.computeSize;
widget.hidden = original.hidden;
if (original.optionsHidden === undefined) {
delete widget.options.hidden;
} else {
widget.options.hidden = original.optionsHidden;
}
return;
}
widget.hidden = true;
widget.type = "converted-widget";
widget.options.hidden = true;
widget.computeSize = () => [0, -4];
}
function attachRefresh(widget, key, refresh) {
if (!widget || widget[key]) return;
const previous = widget.callback;
widget.callback = function(value, ...args) {
const result = previous?.call(this, value, ...args);
refresh();
return result;
};
widget[key] = true;
}
function createProjectId() {
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
const bytes = new Uint8Array(16);
globalThis.crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
function seedControlWidget(node) {
return node.widgets?.find((widget) => (
widget.name === "control_after_generate"
|| widget.name === "seed_control_after_generate"
));
}
function configureEasyNode(node) {
if (node.comfyClass !== EASY_NODE_CLASS) return null;
const projectWidget = findWidget(node, "project_id");
const presetWidget = findWidget(node, "preset");
const customWidget = findWidget(node, "custom_mp");
const storageWidget = findWidget(node, "run_storage");
const runNameWidget = findWidget(node, "run_name");
const seedModeWidget = findWidget(node, "seed_mode");
const controlWidget = seedControlWidget(node);
if (projectWidget && !String(projectWidget.value || "").trim()) {
projectWidget.value = createProjectId();
}
const refresh = () => {
setWidgetVisible(customWidget, presetWidget?.value === CUSTOM_PRESET);
setWidgetVisible(runNameWidget, storageWidget?.value === STORAGE_ENABLED);
if (controlWidget) {
controlWidget.value = seedModeWidget?.value === "Fixed" ? "fixed" : "randomize";
controlWidget.callback?.(controlWidget.value);
}
setWidgetVisible(controlWidget, false);
setWidgetVisible(projectWidget, false);
node.setDirtyCanvas?.(true, true);
};
attachRefresh(presetWidget, "__h3EasyPresetCallback", refresh);
attachRefresh(storageWidget, "__h3EasyStorageCallback", refresh);
attachRefresh(seedModeWidget, "__h3EasySeedModeCallback", refresh);
refresh();
return projectWidget;
}
function configureEasyNodeAfterSetup(node) {
configureEasyNode(node);
setTimeout(() => configureEasyNode(node), 0);
setTimeout(() => configureEasyNode(node), 100);
}
app.registerExtension({
name: "H3Continuum.EasyV38",
nodeCreated(node) {
configureEasyNodeAfterSetup(node);
},
loadedGraphNode(node) {
configureEasyNodeAfterSetup(node);
},
afterConfigureGraph() {
for (const node of app.graph?._nodes || []) configureEasyNodeAfterSetup(node);
},
async beforeQueuePrompt(prompt) {
const seen = new Set();
for (const node of app.graph?._nodes || []) {
const projectWidget = configureEasyNode(node);
if (!projectWidget) continue;
let projectId = String(projectWidget.value || "").trim();
if (!projectId || seen.has(projectId)) {
projectId = createProjectId();
projectWidget.value = projectId;
}
seen.add(projectId);
const apiNode = prompt.output?.[String(node.id)];
if (apiNode?.inputs) apiNode.inputs.project_id = projectId;
}
},
});
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
const NORMALIZED_INPUT_LABELS = {
reference_video_1: "Video Guide Frames",
driving_audio: "Driving Audio",
audio_vae: "Driving Audio VAE",
audio_references: "Reference Audios (Optional)",
reference_audio_1: "Reference Audio (Legacy)",
reference_audio_vae: "Reference Audio VAE (Legacy)",
};
export function normalizeReferenceAudioLabels(node) {
if (!node) {
return false;
}
if (node.comfyClass === "H3ContinuumReferenceAudios") {
const output = node.outputs?.find((item) => item.name === "audio_references");
if (output) output.label = "Reference Audios";
return true;
}
for (const input of node.inputs || []) {
const label = input.name === "reference_video_1"
&& node.comfyClass === "H3ContinuumSamplerV38"
? "Timeline Video Frames"
: NORMALIZED_INPUT_LABELS[input.name];
if (label) {
input.label = label;
}
}
return true;
}
+71
View File
@@ -0,0 +1,71 @@
import { app } from "../../scripts/app.js";
const BUNDLE_NODE = "H3ContinuumReferenceImages";
const BUNDLE_INPUT = "image_references";
const BUNDLE_TYPE = "H3_CONTINUUM_IMAGE_REFERENCES";
export function migrateReferenceImageInputs(node) {
if (node.comfyClass !== "H3ContinuumSamplerV38") return;
const graph = node.graph || app.graph;
const legacy = (node.inputs || []).filter(
(input) => ["reference_image_4", "reference_image_5"].includes(input.name),
);
if (!node.inputs?.some((input) => input.name === BUNDLE_INPUT)) {
node.addInput(BUNDLE_INPUT, BUNDLE_TYPE, { label: "Reference Images (Optional)" });
}
if (!legacy.length) return;
const connected = legacy.filter((input) => input.link != null);
const bundleSlot = node.inputs.findIndex((input) => input.name === BUNDLE_INPUT);
const bundleLink = graph.links[node.inputs[bundleSlot].link];
let bundle = bundleLink && graph.getNodeById(bundleLink.origin_id);
if (connected.length) {
const sources = connected.map((input) => {
const link = graph.links[input.link];
const source = link && graph.getNodeById(link.origin_id);
return { input, link, source };
});
if (sources.some(({ source }) => !source)
|| (bundleLink && bundle?.comfyClass !== BUNDLE_NODE)) {
console.warn("H3 Continuum: legacy Reference Image links retained; their source or bundle cannot be migrated.");
return;
}
if (bundle && connected.some((input) => {
const slot = bundle.inputs.find((item) => item.name === input.name);
return !slot || slot.link != null;
})) {
console.warn("H3 Continuum: legacy Reference Image links retained; the matching bundle slots are occupied.");
return;
}
if (!bundle) {
bundle = globalThis.LiteGraph?.createNode(BUNDLE_NODE);
if (!bundle) {
console.warn("H3 Continuum: legacy Reference Image links retained; the Reference Images node is unavailable.");
return;
}
bundle.pos = [node.pos[0] - 360, node.pos[1] + 220];
graph.add(bundle);
bundle.connect(0, node, bundleSlot);
if (node.inputs[bundleSlot].link == null) {
graph.remove(bundle);
console.warn("H3 Continuum: legacy Reference Image links retained; bundle connection failed.");
return;
}
}
for (const { input, link, source } of sources) {
const slot = bundle.inputs.findIndex((item) => item.name === input.name);
source.connect(link.origin_slot, bundle, slot);
const moved = graph.links[bundle.inputs[slot].link];
if (!moved || moved.origin_id !== link.origin_id || moved.origin_slot !== link.origin_slot) {
console.warn("H3 Continuum: legacy Reference Image link retained; image connection failed.");
continue;
}
node.removeInput(node.inputs.indexOf(input));
}
}
for (const input of legacy) {
const slot = node.inputs.indexOf(input);
if (slot >= 0 && input.link == null) node.removeInput(slot);
}
node.setDirtyCanvas?.(true, true);
}
+264
View File
@@ -0,0 +1,264 @@
const CLASS = "H3ContinuumReferenceImagesV39";
const SAMPLER = "H3ContinuumSamplerV39";
const MAX = 16;
const LEGACY_SAMPLER_INPUTS = new Set([
...Array.from({ length: 5 }, (_, index) => `reference_image_${index + 1}`),
"image_references",
]);
const getWidget = (node, name) => node.widgets?.find((item) => item.name === name);
const element = (tag, value = "") => {
const item = document.createElement(tag);
item.textContent = value;
return item;
};
function savedChunks(value) {
const text = String(value ?? "off").trim().toLowerCase();
if (text === "off") return new Set();
if (text === "all") return new Set(Array.from({ length: MAX }, (_, i) => i + 1));
const result = new Set();
for (const token of text.split(",")) {
const match = token.trim().match(/^(\d+)(?:\s*-\s*(\d+))?$/);
if (!match) return null;
const first = Number(match[1]);
const last = Number(match[2] || match[1]);
if (first < 1 || last > MAX || first > last) return null;
for (let n = first; n <= last; n += 1) result.add(n);
}
return result;
}
function linkedSamplers(node) {
const output = node.outputs?.find((item) => item.name === "reference_images");
return (output?.links || []).map((id) => {
const link = node.graph?.links?.[id];
return node.graph?.getNodeById?.(link?.target_id);
}).filter((target) => target?.comfyClass === SAMPLER);
}
function destination(node) {
const targets = linkedSamplers(node);
const unknown = (reason) => ({ count: MAX, known: false, reason });
if (!targets.length) return unknown("no_sampler");
if (targets.some((target) => target.inputs?.some((input) => input.name === "chunks" && input.link != null))) {
return unknown("external_chunks");
}
const counts = targets.map((target) => Number(getWidget(target, "chunks")?.value));
if (!counts.every((n) => Number.isInteger(n) && n >= 1 && n <= MAX)) return unknown("unavailable_count");
if (!counts.every((n) => n === counts[0])) return unknown("different_counts");
return { count: counts[0], known: true, reason: "direct_count" };
}
function invalidate(node) {
for (const target of linkedSamplers(node)) {
target.__h3ContinuumReferencePlan = null;
target.__h3ContinuumIntuitiveUxRefresh?.();
target.setDirtyCanvas?.(true, true);
}
}
export function connectedV39LegacyReferenceInputs(node) {
if (node?.comfyClass !== SAMPLER) return [];
return (node.inputs || []).filter((input) =>
LEGACY_SAMPLER_INPUTS.has(input.name) && input.link != null
).map((input) => input.name);
}
export function pruneV39LegacyReferenceInputs(node) {
if (node?.comfyClass !== SAMPLER || typeof node.removeInput !== "function") return 0;
let removed = 0;
for (let index = (node.inputs?.length || 0) - 1; index >= 0; index -= 1) {
const input = node.inputs[index];
if (!LEGACY_SAMPLER_INPUTS.has(input.name) || input.link != null) continue;
node.removeInput(index);
removed += 1;
}
if (removed) {
node.__h3ContinuumReferencePlan = null;
node.setDirtyCanvas?.(true, true);
}
return removed;
}
export function configureV39ReferenceImages(node) {
if (node?.comfyClass !== CLASS || typeof document === "undefined") return;
const mode = getWidget(node, "reference_use");
const selectors = Array.from({ length: 9 }, (_, i) => getWidget(node, `reference_r${i + 1}_chunks`));
if (!mode || selectors.some((item) => !item)) return;
if (node.__h3ReferenceImagesRefresh) return node.__h3ReferenceImagesRefresh();
if (typeof node.addDOMWidget !== "function") return;
// The standard STRING widgets remain serializable; only their presentation is hidden.
for (const item of selectors) {
item.type = "hidden";
item.hidden = true;
item.options ||= {};
item.options.hidden = true;
item.computeSize = () => [0, 0];
item.draw = () => {};
}
const panel = element("div");
panel.style.cssText = "box-sizing:border-box;min-width:340px;max-height:360px;overflow:auto;padding:7px;color:#e7f4e9;background:#203827;font:12px Arial;pointer-events:auto";
const host = element("div");
host.style.cssText = "box-sizing:border-box;padding-top:8px;pointer-events:auto";
host.append(panel);
for (const name of ["pointerdown", "mousedown", "mouseup", "dblclick"]) {
host.addEventListener(name, (event) => event.stopPropagation());
}
const display = node.addDOMWidget("reference_assignment", "h3_reference_assignment", host, { serialize: false });
display.options ||= {};
display.options.serialize = false;
let panelHeight = 54;
display.computeSize = (width) => [Math.max(340, Number(width) || Number(node.size?.[0]) || 340), panelHeight + 8];
const reservePanelSpace = (height) => {
panelHeight = height;
panel.style.height = `${height}px`;
const computedHeight = Number(node.computeSize?.()[1]);
const width = Number(node.size?.[0]) || 340;
if (Number.isFinite(computedHeight) && typeof node.setSize === "function"
&& (Number(node.size?.[0]) !== width || Number(node.size?.[1]) !== computedHeight)) {
node.setSize([width, computedHeight]);
}
};
let page = 0;
let previousKey = null;
const setSelection = (slot, selection) => {
const target = selectors[slot - 1];
target.value = [...selection].sort((a, b) => a - b).join(",") || "off";
// The wrapped native callback owns invalidation and the immediate refresh.
target.callback?.(target.value);
};
const refresh = () => {
const { count, known, reason } = destination(node);
const rows = Array.from({ length: 9 }, (_, i) => i + 1).filter((slot) =>
node.inputs?.some((input) => input.name === `reference_image_${slot}` && input.link != null));
const key = JSON.stringify([mode.value, count, known, reason, rows, selectors.map((item) => item.value), page]);
if (key === previousKey) return;
previousKey = key;
panel.replaceChildren();
if (mode.value !== "Per chunk") {
panel.append(element("div", "Connected images are used in all chunks."));
reservePanelSpace(54);
return;
}
panel.append(element("div", known ? `Per-chunk assignments · ${count} chunks` : "Per-chunk assignments · range 1–16"));
if (!known) {
const explanation = {
no_sampler: "Connect this helper to a Sampler to determine its chunk count.",
external_chunks: "Chunk count is supplied by a connected node.",
unavailable_count: "The Sampler chunk count is not available.",
different_counts: "Connected Samplers have different chunk counts.",
};
panel.append(element("div", explanation[reason]));
panel.append(element("div", "Assignments apply only to chunks generated by the Sampler."));
}
if (!rows.length) {
panel.append(element("div", "Connect Reference Images to assign them."));
reservePanelSpace(known ? 64 : 104);
return;
}
page = Math.min(page, Math.ceil(count / 6) - 1);
const first = page * 6 + 1;
const last = Math.min(first + 5, count);
if (count > 6) {
const nav = element("div");
for (const [label, targetPage] of [["◀", page - 1], [`${first}–${last} / ${count}`, page], ["▶", page + 1]]) {
const button = element("button", label);
button.type = "button";
button.disabled = targetPage < 0 || targetPage >= Math.ceil(count / 6) || targetPage === page;
button.onclick = () => { page = targetPage; previousKey = null; refresh(); };
nav.append(button);
}
panel.append(nav);
}
const table = element("table");
table.style.cssText = "width:100%;border-collapse:collapse;text-align:center;color:#e7f4e9";
const header = element("tr");
header.append(element("th", "Image"));
for (let n = first; n <= last; n += 1) header.append(element("th", String(n)));
header.append(element("th", "All / Off"));
table.append(header);
for (const slot of rows) {
const selected = savedChunks(selectors[slot - 1].value);
const row = element("tr");
row.append(element("td", `Image ${slot} · @R${slot}`));
for (let n = first; n <= last; n += 1) {
const cell = element("td");
const checkbox = element("input");
checkbox.type = "checkbox";
checkbox.checked = selected?.has(n) || false;
checkbox.disabled = selected === null;
checkbox.setAttribute("aria-label", `Image ${slot}, Chunk ${n}`);
checkbox.onchange = () => {
const updated = new Set(selected);
if (checkbox.checked) updated.add(n); else updated.delete(n);
setSelection(slot, updated);
};
cell.append(checkbox);
row.append(cell);
}
const actions = element("td");
for (const [label, on] of [["All", true], ["Off", false]]) {
const button = element("button", known ? label : `${label} 1–16`);
button.type = "button";
button.disabled = selected === null;
button.onclick = () => {
const updated = new Set(selected);
for (let n = 1; n <= count; n += 1) {
if (on) updated.add(n); else updated.delete(n);
}
setSelection(slot, updated);
};
actions.append(button);
}
row.append(actions);
table.append(row);
}
panel.append(table);
for (const slot of rows) {
const selected = savedChunks(selectors[slot - 1].value);
if (selected === null) {
panel.append(element("div", `Image ${slot}: invalid saved selection.`));
continue;
}
if (!known) {
const saved = [...selected].sort((a, b) => a - b);
panel.append(element("div", `Image ${slot} → Saved assignments: ${saved.join(", ") || "none"}`));
continue;
}
const active = [...selected].filter((n) => n <= count).sort((a, b) => a - b);
const future = [...selected].filter((n) => n > count).sort((a, b) => a - b);
panel.append(element("div", `Image ${slot} → Chunks ${active.join(", ") || "none"}${future.length ? ` · saved beyond range: ${future.join(", ")}` : ""}`));
}
if (rows.every((slot) => ![...(savedChunks(selectors[slot - 1].value) || [])].some((n) => n <= count))) {
panel.append(element("div", known ? "No references assigned. Check the chunks to use." : "No saved assignments. Check the chunks to use."));
}
reservePanelSpace(Math.min(360, 77 + rows.length * 36 + (count > 6 ? 32 : 0) + (known ? 0 : 40)));
node.setDirtyCanvas?.(true, true);
};
node.__h3ReferenceImagesRefresh = refresh;
const oldConnections = node.onConnectionsChange;
node.onConnectionsChange = function(...args) {
const result = oldConnections?.apply(this, args);
invalidate(this);
refresh();
return result;
};
for (const control of [mode, ...selectors]) {
const previous = control.callback;
control.callback = function(...args) {
const result = previous?.apply(this, args);
invalidate(node);
refresh();
return result;
};
}
refresh();
}
export function refreshV39ReferenceImagesForSampler(node) {
if (node?.comfyClass !== SAMPLER) return;
const input = node.inputs?.find((item) => item.name === "reference_images");
const link = node.graph?.links?.[input?.link];
const source = node.graph?.getNodeById?.(link?.origin_id);
if (source?.comfyClass === CLASS) configureV39ReferenceImages(source);
}
+240
View File
@@ -0,0 +1,240 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
const words = {
en: {
title: "H3 Continuum — Temporary Storage", open: "Manage temporary storage", close: "Close",
path: "Scratch folder on the ComfyUI server", default: "Blank: keep existing temporary folders",
volumes: "Choose a server storage location…", validate: "Validate", save: "Save", refresh: "Refresh",
cleanup: "Delete unused temporary files", free: "Free", total: "Temporary files", in_use: "In use",
deletable: "Deletable", unknown: "Protected / unknown", current: "Current", previous: "Previous",
loading: "Loading…", saved: "Saved. New files will use this location; existing files stay where they are.",
valid: "The selected folder passed the write and memory-map checks.", removed: "Deleted",
files: "files", busy: "Wait until the running and pending queues are empty to change or clean storage.",
readonly: "Shared storage is read-only in multi-user mode. The server operator manages this setting.",
note: "This is the server's storage, not the browser device. File sizes are logical sizes, not SSD write totals. Moving to another folder on the same physical disk does not reduce its writes.",
modes: "Keep choosing Auto / RAM / Disk-backed in Finalize, and Auto / RAM / Off in Decode Cache Helper. They are independent. Deleting a cache can require decoding and writing it again.",
memory: "Available CPU RAM", last: "Last Finalize allocation", never: "No Finalize allocation in this process yet",
noVolumes: "No storage candidates found. Enter an absolute server folder above.",
unavailable: "Storage service unavailable (HTTP {status}). The old ComfyUI process may still be running, or the updated process failed to start. Check the startup log for a port already in use.",
invalidResponse: "Empty or invalid storage response (HTTP {status}). Click Refresh to retry; if it persists, check the ComfyUI startup log.",
networkError: "Cannot reach ComfyUI at the current address. Click Refresh to retry.",
unloaded: "Storage data unavailable — click Refresh",
},
ja: {
title: "H3 Continuum — 一時ストレージ", open: "一時ストレージを管理", close: "閉じる",
path: "ComfyUIサーバー側の一時保存先フォルダー", default: "空欄:従来の一時保存先を使用",
volumes: "サーバーのストレージ候補を選択…", validate: "検証", save: "保存", refresh: "更新",
cleanup: "未使用の一時ファイルを削除", free: "空き容量", total: "一時ファイル量", in_use: "使用中",
deletable: "削除可能", unknown: "保護中/判定不能", current: "現在", previous: "以前",
loading: "読み込み中…", saved: "保存しました。新規ファイルから適用し、既存ファイルは元の場所で保持します。",
valid: "指定先の書き込みとメモリマップの検証に成功しました。", removed: "削除済み",
files: "ファイル", busy: "保存先の変更・削除は、実行中と待機中のQueueが空になるまでお待ちください。",
readonly: "マルチユーザー運用では閲覧のみです。共有保存先はサーバー管理者が管理します。",
note: "対象はブラウザー端末ではなくComfyUIサーバーです。表示容量はファイルの論理サイズで、SSDの累計書き込み量ではありません。同じ物理ディスク内の移動では、そのディスクへの書き込みは減りません。",
modes: "使用方式は従来どおりFinalizeのAuto/RAM/Disk-backedと、Decode Cache HelperのAuto/RAM/Offで選びます。両者は独立しています。キャッシュ削除後は再デコード・再書き込みが必要になる場合があります。",
memory: "利用可能なCPU RAM", last: "直近のFinalize確保", never: "このプロセスではまだFinalizeを実行していません",
noVolumes: "候補を取得できません。上の欄にサーバー側の絶対パスを入力できます。",
unavailable: "一時ストレージ機能に接続できません(HTTP {status})。旧ComfyUIが残っているか、更新後の起動に失敗した可能性があります。起動ログのポート使用中エラーを確認してください。",
invalidResponse: "一時ストレージの応答が空か、不正な形式です(HTTP {status})。更新で再取得し、続く場合はComfyUI起動ログを確認してください。",
networkError: "現在のアドレスでComfyUIへ接続できません。更新で再取得してください。",
unloaded: "保存先の状態を取得できません — 更新で再取得",
},
};
function language() {
const locale = app.ui?.settings?.getSettingValue?.("Comfy.Locale") || navigator.language || "en";
return String(locale).startsWith("ja") ? words.ja : words.en;
}
function size(bytes) {
if (!Number.isFinite(bytes)) return "—";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(2)} KiB`;
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MiB`;
return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;
}
function element(tag, text, parent) {
const result = document.createElement(tag);
if (text != null) result.textContent = text;
parent?.append(result);
return result;
}
async function request(operation, body) {
const path = `/h3-continuum/storage/${operation}`;
const options = body === undefined
? { cache: "no-store" }
: { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
const t = language();
let response;
try {
// Core retains the UI address, base path and user/auth handling.
// Never replay a save or cleanup after an empty/failed response:
// it may already have run on the server.
response = await api.fetchApi(path, options);
} catch {
throw new Error(t.networkError);
}
let value;
try { value = JSON.parse(await response.text()); } catch { /* Report HTTP status instead of a JSON parser exception. */ }
if (!response.ok) {
const fallback = response.status === 404 ? t.unavailable : `HTTP ${response.status}`;
throw new Error(typeof value?.error === "string" ? value.error : fallback.replace("{status}", response.status));
}
if (!value || typeof value !== "object" || Array.isArray(value)
|| (operation === "status" && (typeof value.path !== "string" || !Number.isInteger(value.revision)
|| !Array.isArray(value.roots) || !Array.isArray(value.volumes) || !value.memory))) {
throw new Error(t.invalidResponse.replace("{status}", response.status));
}
return value;
}
let opened = null;
export function openStorageDialog(event) {
if (opened?.isConnected && opened.open) { opened.focus(); return; }
const t = language();
const dialog = element("dialog");
opened = dialog;
dialog.dataset.h3Storage = "true";
dialog.setAttribute("aria-label", t.title);
Object.assign(dialog.style, {
width: "min(760px, 92vw)", maxHeight: "88vh", overflow: "auto", padding: "20px",
background: "var(--comfy-menu-bg, #222)", color: "var(--fg-color, #ddd)",
border: "1px solid var(--border-color, #666)", borderRadius: "10px",
});
const abort = new AbortController();
element("h2", t.title, dialog);
element("p", t.note, dialog);
const label = element("label", t.path, dialog);
const input = element("input", null, label);
input.type = "text"; input.placeholder = t.default; input.setAttribute("aria-label", t.path);
Object.assign(input.style, { display: "block", width: "100%", margin: "8px 0", padding: "8px", boxSizing: "border-box" });
const volumeLabel = element("label", t.volumes, dialog);
const select = element("select", null, volumeLabel);
select.setAttribute("aria-label", t.volumes);
Object.assign(select.style, { display: "block", width: "100%", minHeight: "34px", margin: "8px 0", boxSizing: "border-box" });
const placeholder = element("option", t.loading, select); placeholder.value = "";
const actions = element("div", null, dialog);
Object.assign(actions.style, { display: "flex", gap: "8px", flexWrap: "wrap", margin: "12px 0" });
const buttons = {};
for (const action of ["validate", "save", "refresh", "cleanup", "close"]) {
const button = element("button", t[action], actions);
button.type = "button"; button.style.padding = "6px 10px"; buttons[action] = button;
}
const notice = element("p", null, dialog);
const message = element("p", t.loading, dialog); message.setAttribute("role", "status");
const memory = element("p", null, dialog);
const last = element("p", null, dialog);
const roots = element("div", null, dialog);
element("p", t.modes, dialog);
let state = null, pending = true, dirty = false, closed = false;
function controls() {
for (const name of ["validate", "save", "cleanup"]) buttons[name].disabled = pending || !state || state.busy || state.read_only;
buttons.refresh.disabled = pending;
input.disabled = pending || !state || !!state.read_only;
select.disabled = input.disabled || !state?.volumes?.length;
notice.textContent = state?.read_only ? t.readonly : state?.busy ? t.busy : "";
}
function render(value) {
state = value;
if (!dirty) input.value = value.path;
select.replaceChildren();
const option = element("option", value.volumes.length ? t.volumes : t.noVolumes, select); option.value = "";
for (const volume of value.volumes) {
const option = element("option", `${volume.path} (${t.free}: ${size(volume.free_bytes)})`, select);
option.value = volume.path;
}
memory.textContent = `${t.memory}: ${size(value.memory.available_bytes)}`;
last.textContent = value.last_backend
? `${t.last}: ${value.last_backend.backend}, ${size(value.last_backend.image_bytes)}${value.last_backend.path ? ` — ${value.last_backend.path}` : ""}`
: t.never;
roots.replaceChildren();
for (const root of value.roots) {
const section = element("section", null, roots);
Object.assign(section.style, { borderTop: "1px solid #666", padding: "10px 0", overflowWrap: "anywhere" });
element("strong", `${root.kind === "finalize" ? "Finalize" : "Decode Cache"} — ${root.current ? t.current : t.previous}`, section);
element("div", root.path, section);
element("div", `${t.total}: ${size(root.bytes)} · ${t.free}: ${size(root.free_bytes)}`, section);
element("div", `${t.in_use}: ${size(root.in_use_bytes)} · ${t.deletable}: ${size(root.deletable_bytes)} · ${t.unknown}: ${size(root.unknown_bytes)}`, section);
for (const error of root.errors) element("p", error, section);
}
}
async function refresh() {
try {
const value = await request("status");
if (!closed) render(value);
} catch (error) {
if (!closed) {
state = null;
select.replaceChildren();
const option = element("option", t.unloaded, select); option.value = "";
}
throw error;
}
}
async function perform(action) {
if (pending) return;
pending = true; controls(); message.textContent = t.loading;
try {
if (action === "refresh") { await refresh(); message.textContent = ""; }
if (action === "validate") {
const result = await request("validate", { path: input.value });
message.textContent = result.path
? `${t.valid} ${result.path} (${t.free}: ${size(result.roots[0]?.free_bytes)})`
: t.default;
}
if (action === "save") {
await request("settings", { path: input.value, revision: state.revision });
dirty = false; await refresh(); message.textContent = t.saved;
}
if (action === "cleanup") {
const result = await request("cleanup", {});
const files = result.roots.reduce((sum, root) => sum + root.removed_files, 0);
const bytes = result.roots.reduce((sum, root) => sum + root.removed_bytes, 0);
const errors = result.roots.flatMap(root => root.errors);
await refresh(); message.textContent = `${t.removed}: ${files} ${t.files}, ${size(bytes)}${errors.length ? ` — ${errors.join("; ")}` : ""}`;
}
} catch (error) { if (!closed) message.textContent = error.message; }
finally { pending = false; if (!closed) controls(); }
}
input.addEventListener("input", () => { dirty = true; });
select.addEventListener("change", () => { if (select.value) { input.value = select.value; dirty = true; } });
for (const name of ["validate", "save", "refresh", "cleanup"]) buttons[name].addEventListener("click", () => perform(name));
buttons.close.addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => { closed = true; abort.abort(); dialog.remove(); if (opened === dialog) opened = null; }, { once: true });
dialog.addEventListener("keydown", event => { if (event.key === "Escape") event.stopPropagation(); });
api.addEventListener("status", event => {
const remaining = event.detail?.exec_info?.queue_remaining;
if (state && typeof remaining === "number") { state.busy = remaining > 0; controls(); }
}, { signal: abort.signal });
// Keep the native modal inside the settings dialog's DOM so Core's
// outside-click handling does not dismiss the underlying settings page.
const parent = event?.currentTarget?.closest?.('[role="dialog"], dialog') || document.body;
parent.append(dialog); dialog.showModal(); controls();
refresh().then(() => { if (!closed) message.textContent = ""; })
.catch(error => { if (!closed) message.textContent = error.message; })
.finally(() => { pending = false; if (!closed) controls(); });
}
app.registerExtension({
name: "H3Continuum.TemporaryStorage",
setup() {
app.ui.settings.addSetting({
id: "H3Continuum.Storage.Manager",
name: "H3 Continuum: Temporary Storage",
category: ["H3Continuum", "Storage", "Temporary Storage"],
type: () => {
const row = element("tr");
const cell = element("td", null, row); cell.colSpan = 2;
const button = element("button", language().open, cell);
button.type = "button"; button.addEventListener("click", openStorageDialog);
return row;
},
defaultValue: null,
});
},
});
+42
View File
@@ -0,0 +1,42 @@
import { app } from "../../scripts/app.js";
const NODE_CLASS = "H3ContinuumSamplerV38";
const MODE = "video_reference_mode";
const REPEAT = "Repeat Reference";
const FOLLOW = "Follow Timeline";
export function restoreVideoReferenceMode(node, info) {
const widget = node.widgets?.find((item) => item.name === MODE);
if (!widget) return;
const linked = info?.inputs?.some((input) => (
(input.name === MODE || input.widget?.name === MODE) && input.link != null
));
if (linked) return; // The connected input, not a hidden widget, owns its value.
let value;
const named = info?.widgets_values_named;
if (named && Object.prototype.hasOwnProperty.call(named, MODE)) {
value = named[MODE];
} else if (!named) {
// The existing V38X2 backend widgets occupy slots 0..29. This new
// optional scalar is appended; no upload/UI/transient row is inserted.
const values = info?.widgets_values;
if (Array.isArray(values) && values.length > 30) value = values[30];
}
// In particular A(Follow)->B(old workflow) must not inherit A's mode.
widget.value = value === FOLLOW ? FOLLOW : REPEAT;
node.__h3ContinuumIntuitiveUxRefresh?.();
}
app.registerExtension({
name: "H3Continuum.TimelineVideoModeExperimental",
beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name !== NODE_CLASS && nodeType?.prototype?.comfyClass !== NODE_CLASS) return;
const previous = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function(info, ...args) {
const result = previous?.call(this, info, ...args);
restoreVideoReferenceMode(this, info);
return result;
};
},
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+392
View File
@@ -0,0 +1,392 @@
import { app } from "../../scripts/app.js";
const TARGET_NODES = new Set([
"H3RefModCreateFromFolder",
]);
const MIN_NODE_WIDTH = 320;
const CREATE_FOLDER_INSTRUCTIONS = [
"Keep image count to a minimum; around six to ten well-chosen",
"images can suffice. Add audio if wanted. Videos are ignored.",
"",
"Folder: absolute path or folder inside ComfyUI's input/.",
"Connect the H3 video VAE; audio VAE is optional.",
"use_subfolders creates one RefMod per immediate subfolder.",
"include_images stores grounding pictures; off by default.",
"Saves to models/refmods/ when save is enabled.",
"Or use directly as a mod, by connecting to mods output.",
].join("\n");
function addAspectRatioReminder(node) {
let tooltip = null;
let tooltipStyle = null;
function hideTooltip() {
tooltip?.remove();
tooltip = null;
tooltipStyle?.remove();
tooltipStyle = null;
}
const onDrawForeground = node.onDrawForeground;
node.onDrawForeground = function (context) {
const result = onDrawForeground?.apply(this, arguments);
if (!this.flags?.collapsed) {
context.save();
context.fillStyle = "#facc15";
context.font = "bold 18px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText("?", this.size[0] - 18, -15);
context.restore();
}
return result;
};
const onMouseMove = node.onMouseMove;
node.onMouseMove = function (event, position) {
const result = onMouseMove?.apply(this, arguments);
const overReminder = !this.flags?.collapsed && position &&
Math.abs(position[0] - (this.size[0] - 18)) <= 12 &&
Math.abs(position[1] + 15) <= 12;
if (!overReminder) {
hideTooltip();
return result;
}
if (!tooltip) {
tooltip = document.createElement("div");
tooltip.setAttribute("role", "tooltip");
const warning = document.createElement("strong");
warning.textContent = "Warning: images should all have the same aspect ratio within each dataset folder.";
warning.style.cssText = "display:block;margin-bottom:8px;color:#facc15;";
tooltip.append(warning, document.createTextNode(CREATE_FOLDER_INSTRUCTIONS));
tooltip.style.cssText = "position:fixed;z-index:10000;pointer-events:none;box-sizing:border-box;max-width:min(480px,calc(100vw - 16px));padding:12px 14px;border:1px solid #facc15;border-radius:4px;background:#252525;color:#fff;font-size:15px;line-height:1.45;white-space:pre-line;overflow-wrap:anywhere;";
tooltipStyle = document.createElement("style");
tooltipStyle.textContent = ".node-tooltip { display: none !important; }";
document.body.append(tooltip, tooltipStyle);
}
const bounds = tooltip.getBoundingClientRect();
tooltip.style.left = `${Math.max(8, Math.min(event.clientX + 12, window.innerWidth - bounds.width - 8))}px`;
tooltip.style.top = `${Math.max(8, Math.min(event.clientY + 12, window.innerHeight - bounds.height - 8))}px`;
return result;
};
const onMouseLeave = node.onMouseLeave;
node.onMouseLeave = function () {
hideTooltip();
return onMouseLeave?.apply(this, arguments);
};
const onRemoved = node.onRemoved;
node.onRemoved = function () {
hideTooltip();
return onRemoved?.apply(this, arguments);
};
}
const COMMON_PRESET_FIELDS = [
"concept_type",
"audio_concept_type",
"mode",
"ref_resolution",
"pool_h",
"pool_w",
"max_tokens",
"identity",
"merge",
"multiplier",
"audio_max_seconds",
"audio_max_tokens",
"audio_budget_policy",
"max_total_tokens",
"budget_policy",
];
const PRESET_CONFIG = {
H3RefModCreateFromFolder: {
manual: {
values: {
concept_type: "identity",
audio_concept_type: "voice",
mode: "Full Reference",
ref_resolution: 1024,
pool_h: 16,
pool_w: 16,
max_tokens: 8192,
identity: 500,
merge: false,
multiplier: 1,
audio_max_seconds: 30.0,
audio_max_tokens: 5120,
audio_budget_policy: "error",
max_total_tokens: 0,
budget_policy: "truncate",
},
fields: [],
compactFields: [],
},
identity_encode: {
values: {
concept_type: "identity",
audio_concept_type: "voice",
mode: "Full Reference",
ref_resolution: 1024,
pool_h: 16,
pool_w: 16,
max_tokens: 8192,
identity: 0,
merge: false,
multiplier: 1,
audio_max_seconds: 30.0,
audio_max_tokens: 5120,
audio_budget_policy: "error",
max_total_tokens: 0,
budget_policy: "truncate",
},
fields: [
"concept_type",
"audio_concept_type",
"mode",
"ref_resolution",
"identity",
"merge",
],
compactFields: COMMON_PRESET_FIELDS,
},
style_experimental: {
values: {
concept_type: "style",
audio_concept_type: "voice",
mode: "Compressed Reference",
ref_resolution: 1024,
pool_h: 8,
pool_w: 8,
max_tokens: 8192,
identity: 150,
merge: false,
multiplier: 1,
audio_max_seconds: 30.0,
audio_max_tokens: 5120,
audio_budget_policy: "error",
max_total_tokens: 0,
budget_policy: "truncate",
},
fields: [
"concept_type",
"audio_concept_type",
"mode",
"pool_h",
"pool_w",
"identity",
"merge",
],
compactFields: COMMON_PRESET_FIELDS,
},
motion_sequence: {
values: {
concept_type: "pose_motion",
audio_concept_type: "voice",
mode: "Compressed Reference",
ref_resolution: 1024,
pool_h: 16,
pool_w: 16,
max_tokens: 8192,
identity: 500,
merge: false,
multiplier: 1,
audio_max_seconds: 30.0,
audio_max_tokens: 5120,
audio_budget_policy: "error",
max_total_tokens: 0,
budget_policy: "truncate",
},
fields: [
"concept_type",
"audio_concept_type",
"mode",
"pool_h",
"pool_w",
"merge",
],
compactFields: COMMON_PRESET_FIELDS,
},
},
};
function findWidget(node, name) {
return node.widgets?.find((widget) => widget?.name === name) || null;
}
function moveWidgetAfter(node, widgetName, afterName) {
if (!node.widgets) return;
const widget = findWidget(node, widgetName);
const after = findWidget(node, afterName);
if (!widget || !after) return;
const from = node.widgets.indexOf(widget);
const afterIndex = node.widgets.indexOf(after);
if (from < 0 || afterIndex < 0) return;
node.widgets.splice(from, 1);
const insertAt = node.widgets.indexOf(after) + 1;
node.widgets.splice(insertAt, 0, widget);
}
function setWidgetVisible(widget, visible) {
if (!widget) return;
if (!widget.__h3VisibilityWrapped) {
widget.__h3VisibilityWrapped = true;
widget.__h3BaseComputeSize = widget.computeSize;
widget.computeSize = function (...args) {
if (widget.__h3Hidden) {
return [0, -4];
}
if (typeof widget.__h3BaseComputeSize === "function") {
return widget.__h3BaseComputeSize.apply(this, args);
}
return [MIN_NODE_WIDTH, Number(LiteGraph?.NODE_WIDGET_HEIGHT || 24)];
};
}
if (typeof widget.__h3OriginalDisplay === "undefined" && widget.inputEl) {
widget.__h3OriginalDisplay = widget.inputEl.style.display;
}
widget.__h3Hidden = !visible;
widget.hidden = !visible;
if (widget.inputEl) {
widget.inputEl.style.display = visible ? (widget.__h3OriginalDisplay || "") : "none";
}
}
function refreshNodeLayout(node) {
if (Array.isArray(node.size)) {
node.size[0] = Math.max(Number(node.size[0]) || 0, MIN_NODE_WIDTH);
}
const nextWidth = Math.max(node.size?.[0] || 0, MIN_NODE_WIDTH);
const nextHeight = node.computeSize?.()?.[1] || node.size?.[1] || 0;
node.setSize?.([nextWidth, nextHeight]);
node.onResize?.(node.size);
node.setDirtyCanvas(true, true);
app.graph?.setDirtyCanvas(true, true);
}
function syncPresetValues(node) {
const presetWidget = findWidget(node, "extraction_preset");
const preset = String(presetWidget?.value || "manual");
const nodeType = String(node.comfyClass || "");
const nodePresets = PRESET_CONFIG[nodeType];
if (!nodePresets) return;
const config = nodePresets[preset] || nodePresets.manual;
for (const [name, value] of Object.entries(config.values)) {
const widget = findWidget(node, name);
if (!widget) continue;
widget.value = value;
if (widget.inputEl) {
widget.inputEl.value = String(value);
if (typeof widget.inputEl.checked === "boolean" && typeof value === "boolean") {
widget.inputEl.checked = value;
}
}
}
}
function applyFolderNamingVisibility(node) {
if (String(node.comfyClass || "") !== "H3RefModCreateFromFolder") return;
const useSubfoldersWidget = findWidget(node, "use_subfolders");
const useFolderAsNameWidget = findWidget(node, "use_folder_as_name");
const nameWidget = findWidget(node, "name");
const useSubfolders = Boolean(useSubfoldersWidget?.value);
const useFolderAsName = Boolean(useFolderAsNameWidget?.value);
setWidgetVisible(useFolderAsNameWidget, !useSubfolders);
setWidgetVisible(nameWidget, !useSubfolders && !useFolderAsName);
}
function applyPresetVisibility(node) {
const presetWidget = findWidget(node, "extraction_preset");
const advancedWidget = findWidget(node, "advanced");
const preset = String(presetWidget?.value || "manual");
const advanced = Boolean(advancedWidget?.value);
const nodeType = String(node.comfyClass || "");
const nodePresets = PRESET_CONFIG[nodeType];
if (!nodePresets) return;
const config = nodePresets[preset] || nodePresets.manual;
const active = new Set(advanced ? config.fields : (config.compactFields || config.fields));
const known = new Set(Object.values(nodePresets).flatMap((configEntry) => [
...(configEntry.fields || []),
...(configEntry.compactFields || []),
]));
for (const name of known) {
setWidgetVisible(findWidget(node, name), !(preset !== "manual" && active.has(name)));
}
setWidgetVisible(advancedWidget, preset !== "manual");
applyFolderNamingVisibility(node);
refreshNodeLayout(node);
}
function attachWidgetRefresh(node, widgetName, onAfterChange) {
const widget = findWidget(node, widgetName);
if (!widget || widget.__h3RefreshAttached) return;
widget.__h3RefreshAttached = true;
const originalCallback = widget.callback;
widget.callback = function () {
const result = originalCallback?.apply(this, arguments);
onAfterChange();
return result;
};
}
function enhanceCreateNode(node) {
if (node.__h3CreateUiEnhanced) return;
node.__h3CreateUiEnhanced = true;
const originalOnResize = node.onResize;
node.onResize = function (size) {
if (size) {
size[0] = Math.max(size[0] || 0, MIN_NODE_WIDTH);
}
return originalOnResize?.apply(this, arguments);
};
addAspectRatioReminder(node);
moveWidgetAfter(node, "extraction_preset", "name");
moveWidgetAfter(node, "advanced", "extraction_preset");
moveWidgetAfter(node, "budget_policy", "max_total_tokens");
syncPresetValues(node);
applyPresetVisibility(node);
attachWidgetRefresh(node, "extraction_preset", () => {
syncPresetValues(node);
applyPresetVisibility(node);
});
attachWidgetRefresh(node, "advanced", () => applyPresetVisibility(node));
attachWidgetRefresh(node, "use_subfolders", () => applyPresetVisibility(node));
attachWidgetRefresh(node, "use_folder_as_name", () => applyPresetVisibility(node));
const onConfigure = node.onConfigure;
node.onConfigure = function () {
const result = onConfigure?.apply(this, arguments);
moveWidgetAfter(this, "extraction_preset", "name");
moveWidgetAfter(this, "advanced", "extraction_preset");
moveWidgetAfter(this, "budget_policy", "max_total_tokens");
syncPresetValues(this);
applyPresetVisibility(this);
attachWidgetRefresh(this, "extraction_preset", () => {
syncPresetValues(this);
applyPresetVisibility(this);
});
attachWidgetRefresh(this, "advanced", () => applyPresetVisibility(this));
attachWidgetRefresh(this, "use_subfolders", () => applyPresetVisibility(this));
attachWidgetRefresh(this, "use_folder_as_name", () => applyPresetVisibility(this));
return result;
};
}
app.registerExtension({
name: "H3RefModPicker.RefModCreate",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (!TARGET_NODES.has(nodeData?.name)) return;
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
enhanceCreateNode(this);
return result;
};
},
});
console.log("[H3RefModPicker] RefModCreate extension loaded");
+116
View File
@@ -0,0 +1,116 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
function findWidget(node, name) {
return node.widgets?.find((widget) => widget?.name === name) || null;
}
function setWidgetVisible(widget, visible) {
if (!widget) return;
if (!widget.__h3LoaderVisibilityWrapped) {
widget.__h3LoaderVisibilityWrapped = true;
widget.__h3LoaderBaseComputeSize = widget.computeSize;
widget.computeSize = function (...args) {
if (widget.__h3LoaderHidden) {
return [0, -4];
}
if (typeof widget.__h3LoaderBaseComputeSize === "function") {
return widget.__h3LoaderBaseComputeSize.apply(this, args);
}
return [200, Number(LiteGraph?.NODE_WIDGET_HEIGHT || 24)];
};
}
if (typeof widget.__h3LoaderOriginalDisplay === "undefined" && widget.inputEl) {
widget.__h3LoaderOriginalDisplay = widget.inputEl.style.display;
}
widget.__h3LoaderHidden = !visible;
widget.hidden = !visible;
if (widget.inputEl) {
widget.inputEl.style.display = visible ? (widget.__h3LoaderOriginalDisplay || "") : "none";
}
}
function refreshNodeLayout(node) {
node.setDirtyCanvas(true, true);
app.graph?.setDirtyCanvas(true, true);
}
async function fetchLoaderCapabilities(mod) {
const query = mod ? `?mod=${encodeURIComponent(mod)}` : "";
const resp = await api.fetchApi(`/h3refmods/refmod-loader/capabilities${query}`);
if (!resp.ok) {
throw new Error(`Request failed (${resp.status})`);
}
return await resp.json();
}
function applyModalityVisibility(node, caps) {
const videoWidget = findWidget(node, "video_weight");
const audioWidget = findWidget(node, "audio_weight");
const hasVisual = typeof caps?.has_visual === "boolean" ? caps.has_visual : true;
const hasAudio = typeof caps?.has_audio === "boolean" ? caps.has_audio : true;
setWidgetVisible(videoWidget, hasVisual);
setWidgetVisible(audioWidget, hasAudio);
refreshNodeLayout(node);
}
async function refreshLoaderVisibility(node) {
const modWidget = findWidget(node, "mod");
const mod = String(modWidget?.value || "").trim();
if (!mod) {
applyModalityVisibility(node, { has_visual: true, has_audio: true });
return;
}
try {
const data = await fetchLoaderCapabilities(mod);
applyModalityVisibility(node, data.ok ? data : { has_visual: true, has_audio: true });
} catch (error) {
console.warn("[H3RefModLoader] Could not refresh capabilities:", error);
applyModalityVisibility(node, { has_visual: true, has_audio: true });
}
}
app.registerExtension({
name: "H3RefModPicker.RefModLoader",
async beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData?.name !== "H3RefModLoader") return;
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
const node = this;
const legacyWeightWidget = findWidget(node, "weight");
const modWidget = findWidget(node, "mod");
if (legacyWeightWidget) {
setWidgetVisible(legacyWeightWidget, false);
}
if (modWidget && !modWidget.__h3LoaderRefreshAttached) {
modWidget.__h3LoaderRefreshAttached = true;
const originalCallback = modWidget.callback;
modWidget.callback = function () {
const callbackResult = originalCallback?.apply(this, arguments);
void refreshLoaderVisibility(node);
return callbackResult;
};
}
const onConfigure = node.onConfigure;
node.onConfigure = function () {
const configureResult = onConfigure?.apply(this, arguments);
if (legacyWeightWidget) {
setWidgetVisible(legacyWeightWidget, false);
}
void refreshLoaderVisibility(this);
return configureResult;
};
void refreshLoaderVisibility(node);
return result;
};
},
});
console.log("[H3RefModPicker] RefModLoader extension loaded");
File diff suppressed because it is too large Load Diff
+128
View File
@@ -0,0 +1,128 @@
export function openRefModLibrary(node, fetchEntries) {
const previousFocus = document.activeElement;
const dialog = document.createElement("dialog");
dialog.className = "refmod-library";
dialog.setAttribute("aria-label", "RefMod library");
const style = document.createElement("style");
style.textContent = `
.refmod-library {box-sizing:border-box;width:min(1100px,96vw);height:90vh;max-height:90vh;padding:24px;border:1px solid #455266;border-radius:14px;background:#111820;color:#e8edf5;font:14px system-ui;}
.refmod-library::backdrop {background:#000b}
.refmod-library .layout {height:100%;display:flex;flex-direction:column;gap:16px;min-height:0}
.refmod-library header {display:flex;gap:12px;align-items:center;justify-content:space-between}
.refmod-library h2 {margin:0;font-size:23px}
.refmod-library .controls {display:flex;gap:10px;flex-wrap:wrap}
.refmod-library input,.refmod-library select,.refmod-library button {font:inherit;color:inherit;background:#222f3e;border:1px solid #455266;border-radius:7px;padding:9px 12px}
.refmod-library input {flex:1;min-width:180px}
.refmod-library button {cursor:pointer}
.refmod-library button:focus-visible,.refmod-library input:focus-visible,.refmod-library select:focus-visible {outline:2px solid #ffb257;outline-offset:2px}
.refmod-library .results {overflow:auto;min-height:0;flex:1;display:flex;flex-direction:column;gap:10px}
.refmod-library article {padding:16px;border:1px solid #334254;border-radius:9px;background:#18222d;display:grid;grid-template-columns:1fr auto;gap:8px 18px}
.refmod-library .description,.refmod-library .path {grid-column:1/-1;color:#afbed0;overflow-wrap:anywhere}
.refmod-library .path {font-size:12px}
.refmod-library .use {background:#ffb257;border-color:#ffb257;color:#171c22;font-weight:650}
.refmod-library .status {color:#afbed0;min-height:20px}
@media(max-width:600px){.refmod-library{padding:14px}.refmod-library article{grid-template-columns:1fr}.refmod-library header{flex-wrap:wrap}}
`;
const make = (tag, text, className) => {
const el = document.createElement(tag);
if (text !== undefined) el.textContent = text;
if (className) el.className = className;
return el;
};
const layout = make("div", undefined, "layout");
const header = make("header");
const close = make("button", "Close");
header.append(make("h2", "RefMod library"), close);
const controls = make("div", undefined, "controls");
const search = make("input");
search.placeholder = "Search name, folder or description";
search.setAttribute("aria-label", "Search RefMods");
const kind = make("select");
kind.setAttribute("aria-label", "Reference type");
for (const value of ["all", "image", "video", "audio", "bundle"]) {
const option = make("option", value === "all" ? "All reference types" : value);
option.value = value;
kind.append(option);
}
const slot = make("select");
slot.setAttribute("aria-label", "Loader slot");
const widgets = (node.widgets || []).filter(w => /^mod_(?:[ab]_)?\d+$/.test(w.name));
for (const widget of widgets) {
const option = make("option", widget.name);
option.value = widget.name;
slot.append(option);
}
const refresh = make("button", "Refresh");
controls.append(search, kind, slot, refresh);
const status = make("div", "Loading library…", "status");
status.setAttribute("role", "status");
const results = make("div", undefined, "results");
layout.append(header, controls, status, results);
dialog.append(style, layout);
document.body.append(dialog);
let entries = [], disposed = false, controller;
const cleanup = () => {
if (disposed) return;
disposed = true;
controller?.abort();
dialog.remove();
previousFocus?.focus();
};
close.onclick = () => dialog.close();
dialog.addEventListener("close", cleanup, {once:true});
const render = () => {
const query = search.value.trim().toLocaleLowerCase();
const filtered = entries.filter(e => (kind.value === "all" || e.kind === kind.value)
&& [e.name,e.concept,e.description].join(" ").toLocaleLowerCase().includes(query));
status.textContent = `${filtered.length} of ${entries.length} RefMods · choose a loader slot, then Use`;
results.replaceChildren();
for (const entry of filtered) {
const row = make("article");
const title = make("strong", entry.name);
const use = make("button", "Use", "use");
use.disabled = widgets.length === 0;
use.onclick = () => {
const widget = widgets.find(w => w.name === slot.value);
const linked = node.inputs?.find(i => i.name === slot.value)?.link;
if (linked != null) {
status.textContent = `${slot.value} is connected. Select an unconnected slot.`;
return;
}
if (!widget) return;
widget.value = entry.name;
widget.callback?.(entry.name);
node.setDirtyCanvas?.(true, true);
dialog.close();
};
const tokens = entry.tokens == null ? "tokens available after loading" : `${entry.tokens.toLocaleString()} tokens / copy`;
row.append(title, use, make("div", `${entry.kind} · ${entry.concept} · ${tokens}`, "description"),
make("div", entry.description || "No description saved", "description"),
make("div", entry.path, "path"));
results.append(row);
}
if (!filtered.length) results.append(make("p", "No matching RefMods. Try another search or Refresh after adding files."));
};
const load = async () => {
controller?.abort();
controller = new AbortController();
const signal = controller.signal;
refresh.disabled = true;
try {
const data = await fetchEntries(signal);
if (disposed || signal.aborted) return;
entries = data;
render();
} catch (error) {
if (!disposed && !signal.aborted) status.textContent = `Could not load library: ${error.message}`;
} finally {
if (!disposed && !signal.aborted) refresh.disabled = false;
}
};
search.oninput = render;
kind.onchange = render;
refresh.onclick = load;
dialog.showModal();
search.focus();
load();
return dialog;
}
+34
View File
@@ -0,0 +1,34 @@
import { app } from "../../scripts/app.js";
export function installRefModApply(nodeType) {
const created = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function(...args) {
const result = created?.apply(this, args);
// MatchType installs its callback on the instance during construction.
const connections = this.onConnectionsChange;
this.onConnectionsChange = function(...args) {
const index = this.inputs?.findIndex(input => input.name === "conditioning") ?? -1;
if (index >= 0) {
const input = this.inputs[index];
try {
// Frontend 1.39.2 proxies MatchType slots, but NodeSlot.node
// reads a #private field. That throws during canvas drawing.
void input.node;
} catch (error) {
if (!(error instanceof TypeError)) throw error;
this.inputs[index] = new input.constructor({...input}, this);
if (args[4] === input) args[4] = this.inputs[index];
}
}
return connections?.apply(this, args);
};
return result;
};
}
app.registerExtension({
name: "MiniMaxH3.ApplyCanvasCompatibility",
beforeRegisterNodeDef(nodeType, nodeData) {
if (nodeData.name === "MiniMaxH3RefModApply") installRefModApply(nodeType);
},
});
@@ -0,0 +1,28 @@
import { app } from "../../scripts/app.js";
const modes = { training: "Compressed Reference", encode: "Full Reference" };
function updateLabels(node) {
const mode = node.widgets?.find(widget => widget.name === "mode");
if (mode) {
mode.options.values = Object.values(modes);
mode.value = modes[mode.value] ?? mode.value;
}
const steps = node.widgets?.find(widget => widget.name === "identity");
if (steps) steps.label = "Refinement Steps";
}
app.registerExtension({
name: "MiniMaxH3.CreationLabels",
beforeRegisterNodeDef(nodeType, nodeData) {
if (!["MiniMaxH3RefModExtract", "MiniMaxH3RefModMasterExtract"].includes(nodeData.name)) return;
for (const hook of ["onNodeCreated", "onConfigure"]) {
const previous = nodeType.prototype[hook];
nodeType.prototype[hook] = function(...args) {
const result = previous?.apply(this, args);
updateLabels(this);
return result;
};
}
}
});
+67
View File
@@ -0,0 +1,67 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { openRefModLibrary } from "./library_dialog.js";
export function updateRefModChoices(node, entries) {
const names = ["(none)", ...new Set(entries.map(entry => entry.name))];
for (const widget of node.widgets || []) {
if (!/^mod_(?:[ab]_)?\d+$/.test(widget.name)) continue;
// Preserve selections, including missing files, for an explicit load
// error instead of silently switching the subject after a refresh.
widget.options.values = names.includes(widget.value) || !widget.value
? [...names] : [...names, widget.value];
}
node.setDirtyCanvas?.(true, true);
}
app.registerExtension({
name: "MiniMaxH3.RefModLibrary",
beforeRegisterNodeDef(nodeType, nodeData) {
if (!["MiniMaxH3RefModsLoader", "MiniMaxH3RefModsAxis"].includes(nodeData.name)) return;
const removed = nodeType.prototype.onRemoved;
nodeType.prototype.onRemoved = function(...args) {
this._refmodRefresh?.abort();
this._refmodDialog?.close();
return removed?.apply(this, args);
};
const previous = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function(...args) {
const result = previous?.apply(this, args);
const refresh = this.addWidget("button", "Refresh RefMods", null, async () => {
this._refmodRefresh?.abort();
const controller = new AbortController();
this._refmodRefresh = controller;
refresh.name = "Refreshing RefMods…";
this.setDirtyCanvas?.(true, true);
try {
const response = await api.fetchApi("/refmods/library", {signal: controller.signal, cache: "no-store"});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const entries = await response.json();
if (controller.signal.aborted) return;
updateRefModChoices(this, entries);
refresh.name = "Refresh RefMods";
} catch (error) {
if (controller.signal.aborted) return;
refresh.name = "Refresh failed — click to retry";
console.error("RefMod refresh failed:", error);
} finally {
if (!controller.signal.aborted) {
this._refmodRefresh = null;
this.setDirtyCanvas?.(true, true);
}
}
}, {serialize:false});
this.addWidget("button", "RefMod library", null, () => {
this._refmodDialog?.close();
this._refmodDialog = openRefModLibrary(this, async signal => {
const response = await api.fetchApi("/refmods/library", {signal});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const entries = await response.json();
if (!signal.aborted) updateRefModChoices(this, entries);
return entries;
});
}, {serialize:false});
return result;
};
}
});
+158
View File
@@ -0,0 +1,158 @@
import { app } from "../../scripts/app.js";
const SLOT = /^(?:mod_(?:[ab]_)?|strength_|copies_|value_|components_|visual_strength_|audio_strength_)(\d+)$/;
const NONE = new Set(["", "None", "(none)"]);
export function installRefModSlots(nodeType) {
const created = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function(...args) {
const result = created?.apply(this, args);
setupSlots(this);
return result;
};
// LiteGraph stores widget values by position. Keep the original schema
// order for saving/loading even though the canvas groups them by slot.
// ComfyUI frontend >= 1.5x saves via serializeFromStoreState() and never
// calls serialize(), so that path has to be covered as well or workflows
// get written in display order and shift on the next load.
for (const method of ["serialize", "serializeFromStoreState", "configure"]) {
const original = nodeType.prototype[method];
nodeType.prototype[method] = function(...args) {
const state = this._refmodSlots;
if (!state) return original?.apply(this, args);
// Nodes 2.0 exposes a stable array view: assigning widgets mutates
// that same view, so retain a snapshot rather than its reference.
const displayOrder = [...this.widgets];
state.schemaOrderDepth++;
this.widgets = [...state.originals, ...displayOrder.filter(w => !state.originals.includes(w))];
try {
return original?.apply(this, args);
} finally {
this.widgets = displayOrder;
state.schemaOrderDepth--;
if (method === "configure") state.sync();
}
};
}
const connections = nodeType.prototype.onConnectionsChange;
nodeType.prototype.onConnectionsChange = function(...args) {
const result = connections?.apply(this, args);
this._refmodSlots?.sync();
return result;
};
}
function setupSlots(node) {
if (node._refmodSlots) return;
const originals = [...(node.widgets || [])];
const groups = new Map();
for (const widget of originals) {
const match = widget.name.match(SLOT);
if (!match) continue;
const slot = Number(match[1]);
if (!groups.has(slot)) groups.set(slot, []);
groups.get(slot).push(widget);
}
const slots = [...groups.keys()].sort((a, b) => a - b);
if (!slots.length) return;
const defaults = new Map(originals.map(w => [w, w.value]));
const hidden = new Map();
const removers = new Map();
node.properties ??= {};
node.properties.refmod_visible_slots ??= [slots[0]];
const linked = slot => node.inputs?.some(input => Number(input.name.match(SLOT)?.[1]) === slot && input.link != null);
const used = slot => groups.get(slot).some(w => w.name.startsWith("mod_")
? w.value != null && !NONE.has(String(w.value).trim())
: w.value !== defaults.get(w));
function show(widget, visible) {
if (!visible && !hidden.has(widget)) {
hidden.set(widget, {computeSize: widget.computeSize,
draw: widget.draw, mouse: widget.mouse, hidden: widget.hidden,
optionsHidden: widget.options?.hidden});
// converted-widget means a socket row in Nodes 2.0, not a hidden
// widget. Its empty row was responsible for the large gaps.
widget.options = {...widget.options, hidden: true};
widget.computeSize = () => [0, -4];
widget.draw = () => {};
widget.mouse = () => false;
widget.hidden = true;
} else if (visible && hidden.has(widget)) {
const saved = hidden.get(widget);
widget.options = {...widget.options, hidden: saved.optionsHidden};
widget.computeSize = saved.computeSize;
widget.draw = saved.draw;
widget.mouse = saved.mouse;
widget.hidden = saved.hidden;
hidden.delete(widget);
}
}
function sync() {
// configure fires connection callbacks before assigning widget values.
// Keep schema order until the entire positional restore has finished.
if (node._refmodSlots.schemaOrderDepth) return;
const requested = node.properties.refmod_visible_slots;
// A saved workflow can bring this back as {0: 1, 1: 2, ...} rather than
// an array, so accept either shape before falling back to slot one.
const requestedSlots = Array.isArray(requested)
? requested
: requested && typeof requested === "object"
? Object.values(requested)
: [slots[0]];
const visible = new Set(requestedSlots.filter(slot => groups.has(slot)));
for (const slot of slots) if (used(slot) || linked(slot)) visible.add(slot);
node.properties.refmod_visible_slots = [...visible].sort((a, b) => a - b);
const grouped = [...groups.values()].flat();
const extras = node.widgets.filter(w => !originals.includes(w) && ![...removers.values(), add].includes(w));
const displayOrder = [];
for (const slot of slots) {
for (const widget of groups.get(slot)) {
show(widget, visible.has(slot));
displayOrder.push(widget);
}
const remove = removers.get(slot);
remove.disabled = !!linked(slot);
show(remove, visible.has(slot));
displayOrder.push(remove);
}
show(add, visible.size < slots.length);
displayOrder.push(add, ...originals.filter(w => !grouped.includes(w)), ...extras);
node.widgets = displayOrder;
node.setSize?.([node.size[0], node.computeSize()[1]]);
node.setDirtyCanvas?.(true, true);
}
for (const slot of slots) {
removers.set(slot, node.addWidget("button", `Remove RefMod ${slot}`, null, () => {
if (linked(slot)) return;
for (const widget of groups.get(slot)) widget.value = defaults.get(widget);
node.properties.refmod_visible_slots = node.properties.refmod_visible_slots.filter(i => i !== slot);
sync();
}, {serialize: false}));
for (const widget of groups.get(slot)) {
const callback = widget.callback;
widget.callback = function(...args) {
const result = callback?.apply(this, args);
sync();
return result;
};
}
}
const add = node.addWidget("button", "+ Add RefMod", null, () => {
const next = slots.find(slot => !node.properties.refmod_visible_slots.includes(slot));
if (next != null) node.properties.refmod_visible_slots.push(next);
sync();
}, {serialize: false});
node._refmodSlots = {originals, sync, schemaOrderDepth: 0};
sync();
}
app.registerExtension({
name: "MiniMaxH3.AdditiveSlots",
beforeRegisterNodeDef(nodeType, nodeData) {
if (["MiniMaxH3RefModsLoader", "MiniMaxH3RefModsAxis"].includes(nodeData.name)) {
installRefModSlots(nodeType);
}
},
});