From ba78f2be9d2588f4bd5eb8131c8d4e7f2a6d5b12 Mon Sep 17 00:00:00 2001 From: Chris Dumas Date: Tue, 20 Oct 2026 13:44:50 +0000 Subject: [PATCH] Vendor complete MiniMax H3 upstream packs --- README.md | 24 +- __init__.py | 6 + dumas_vendored_nodes.py | 51 + js/dumas_vendored_loader.js | 28 + .../dumas_h3_continuum/decode_cache_helper.js | 105 + .../dumas_h3_continuum/easy_bypass_toggle.js | 111 + .../dumas_h3_continuum/easy_load_audio.js | 69 + .../dumas_h3_continuum/easy_load_image.js | 29 + .../dumas_h3_continuum/easy_load_video.js | 3 + js/vendor/dumas_h3_continuum/easy_v38.js | 135 + js/vendor/dumas_h3_continuum/project_id.js | 3562 +++++++++++++++++ .../dumas_h3_continuum/reference_audio_ui.js | 29 + .../dumas_h3_continuum/reference_image_ui.js | 71 + .../reference_images_v39.js | 264 ++ .../dumas_h3_continuum/storage_settings.js | 240 ++ .../video_reference_mode_ui.js | 42 + .../dumas_h3_refmod_picker/placeholder.png | Bin 0 -> 30069 bytes .../dumas_h3_refmod_picker/refmod_create.js | 392 ++ .../dumas_h3_refmod_picker/refmod_loader.js | 116 + .../visual_refmod_picker.js | 1230 ++++++ .../dumas_minimax_h3_refmod/library_dialog.js | 128 + .../dumas_minimax_h3_refmod/refmod_apply.js | 34 + .../refmod_creation_labels.js | 28 + .../dumas_minimax_h3_refmod/refmod_library.js | 67 + .../dumas_minimax_h3_refmod/refmod_slots.js | 158 + 25 files changed, 6920 insertions(+), 2 deletions(-) create mode 100644 dumas_vendored_nodes.py create mode 100644 js/dumas_vendored_loader.js create mode 100644 js/vendor/dumas_h3_continuum/decode_cache_helper.js create mode 100644 js/vendor/dumas_h3_continuum/easy_bypass_toggle.js create mode 100644 js/vendor/dumas_h3_continuum/easy_load_audio.js create mode 100644 js/vendor/dumas_h3_continuum/easy_load_image.js create mode 100644 js/vendor/dumas_h3_continuum/easy_load_video.js create mode 100644 js/vendor/dumas_h3_continuum/easy_v38.js create mode 100644 js/vendor/dumas_h3_continuum/project_id.js create mode 100644 js/vendor/dumas_h3_continuum/reference_audio_ui.js create mode 100644 js/vendor/dumas_h3_continuum/reference_image_ui.js create mode 100644 js/vendor/dumas_h3_continuum/reference_images_v39.js create mode 100644 js/vendor/dumas_h3_continuum/storage_settings.js create mode 100644 js/vendor/dumas_h3_continuum/video_reference_mode_ui.js create mode 100755 js/vendor/dumas_h3_refmod_picker/placeholder.png create mode 100644 js/vendor/dumas_h3_refmod_picker/refmod_create.js create mode 100644 js/vendor/dumas_h3_refmod_picker/refmod_loader.js create mode 100644 js/vendor/dumas_h3_refmod_picker/visual_refmod_picker.js create mode 100644 js/vendor/dumas_minimax_h3_refmod/library_dialog.js create mode 100644 js/vendor/dumas_minimax_h3_refmod/refmod_apply.js create mode 100644 js/vendor/dumas_minimax_h3_refmod/refmod_creation_labels.js create mode 100644 js/vendor/dumas_minimax_h3_refmod/refmod_library.js create mode 100644 js/vendor/dumas_minimax_h3_refmod/refmod_slots.js diff --git a/README.md b/README.md index 3fe7dd0..c6bd5f8 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/__init__.py b/__init__.py index 24f11f5..01544e1 100644 --- a/__init__.py +++ b/__init__.py @@ -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" diff --git a/dumas_vendored_nodes.py b/dumas_vendored_nodes.py new file mode 100644 index 0000000..843b229 --- /dev/null +++ b/dumas_vendored_nodes.py @@ -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() diff --git a/js/dumas_vendored_loader.js b/js/dumas_vendored_loader.js new file mode 100644 index 0000000..75e8de5 --- /dev/null +++ b/js/dumas_vendored_loader.js @@ -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); diff --git a/js/vendor/dumas_h3_continuum/decode_cache_helper.js b/js/vendor/dumas_h3_continuum/decode_cache_helper.js new file mode 100644 index 0000000..42d5b4f --- /dev/null +++ b/js/vendor/dumas_h3_continuum/decode_cache_helper.js @@ -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); + }, +}); diff --git a/js/vendor/dumas_h3_continuum/easy_bypass_toggle.js b/js/vendor/dumas_h3_continuum/easy_bypass_toggle.js new file mode 100644 index 0000000..8cb85ca --- /dev/null +++ b/js/vendor/dumas_h3_continuum/easy_bypass_toggle.js @@ -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)); +} diff --git a/js/vendor/dumas_h3_continuum/easy_load_audio.js b/js/vendor/dumas_h3_continuum/easy_load_audio.js new file mode 100644 index 0000000..81c0180 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/easy_load_audio.js @@ -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); + }, +}); diff --git a/js/vendor/dumas_h3_continuum/easy_load_image.js b/js/vendor/dumas_h3_continuum/easy_load_image.js new file mode 100644 index 0000000..8a5b402 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/easy_load_image.js @@ -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); + }, +}); diff --git a/js/vendor/dumas_h3_continuum/easy_load_video.js b/js/vendor/dumas_h3_continuum/easy_load_video.js new file mode 100644 index 0000000..140c010 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/easy_load_video.js @@ -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). diff --git a/js/vendor/dumas_h3_continuum/easy_v38.js b/js/vendor/dumas_h3_continuum/easy_v38.js new file mode 100644 index 0000000..287b7a9 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/easy_v38.js @@ -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; + } + }, +}); diff --git a/js/vendor/dumas_h3_continuum/project_id.js b/js/vendor/dumas_h3_continuum/project_id.js new file mode 100644 index 0000000..5b08755 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/project_id.js @@ -0,0 +1,3562 @@ +import { app } from "../../scripts/app.js"; +import { api } from "../../scripts/api.js"; +import { normalizeReferenceAudioLabels } from "./reference_audio_ui.js"; +import { configureV39ReferenceImages, connectedV39LegacyReferenceInputs, pruneV39LegacyReferenceInputs, refreshV39ReferenceImagesForSampler } from "./reference_images_v39.js"; +import { migrateReferenceImageInputs } from "./reference_image_ui.js"; + +const PRODUCTION_NODE_CLASS = "H3ContinuumSamplerProduction"; +const TIMELINE_NODE_CLASS = "H3ContinuumSamplerTimelineVideo"; +const ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamExperimental"; +const V34_NODE_CLASS = "H3ContinuumSamplerV34"; +const V34_ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamV34"; +const V35_NODE_CLASS = "H3ContinuumSamplerV35"; +const V36_NODE_CLASS = "H3ContinuumSamplerV36"; +const V37_NODE_CLASS = "H3ContinuumSamplerV37"; +const V38_NODE_CLASS = "H3ContinuumSamplerV38"; +const V39_NODE_CLASS = "H3ContinuumSamplerV39"; +const isModernSamplerClass = (name) => name === V38_NODE_CLASS || name === V39_NODE_CLASS; +const V39_PLAN_WIDGET = "Reference Plan Inspector"; +const V39_UNVERIFIED_PLAN = "Configured only — Queue has not verified the effective Reference Plan."; +const V35_ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamV35"; +const PROJECT_WIDGET = "project_id"; +const LEGACY_RUN_NAME_WIDGET = "run_name"; +const CHUNKS_WIDGET = "chunks"; +const REGENERATE_WIDGET = "reroll_from_chunk"; +const REROLL_NONCE_WIDGET = "reroll_nonce"; +const REGENERATE_INTENT_PROPERTY = "h3_continuum_regenerate_from"; +const RUN_STORAGE_WIDGET = "run_storage"; +const REFERENCE_SIZE_WIDGET = "reference_size"; +const TIMELINE_SIZE_WIDGET = "timeline_video_size"; +const VIDEO_REFERENCE_SIZE_WIDGET = "video_reference_size"; +const PROMPT_OVERRIDES_INPUT = "prompt_overrides"; +const RESOLUTION_PRESET_WIDGET = "preset"; +const CUSTOM_MP_WIDGET = "custom_mp"; +const CUSTOM_RESOLUTION_PRESET = "Custom"; +const LEGACY_ASPECT_WIDGET = "aspect"; +const SIZE_SOURCE_WIDGET = "size_source"; +const WIDTH_WIDGET = "width"; +const HEIGHT_WIDGET = "height"; +const SIZE_SOURCE_FIRST_IMAGE = "First Image"; +const SIZE_SOURCE_MANUAL = "Manual"; +const SIZE_SOURCE_LEGACY = "Legacy Aspect"; +const RESOLUTION_PRESET_DRAFT = "Draft — 0.30 MP"; +const RESOLUTION_PRESET_BALANCED = "Balanced — 0.60 MP"; +const RESOLUTION_PRESET_NATIVE = "Native 768"; +const CANVAS_MULTIPLE = 32; +const NATIVE_SHORT_EDGE = 768; +const NATIVE_LONG_EDGE_CAP = 1344; +const GENERATION_MODE_WIDGET = "generation_mode"; +const REVIEW_ACTION_WIDGET = "review_action"; +const GENERATION_MODE_FULL_RUN = "Full Run"; +const GENERATION_MODE_REVIEW = "Review Each Chunk"; +const REVIEW_ACTION_CONTINUE = "Continue / Next"; +const REVIEW_ACTION_REGENERATE = "Regenerate Current"; +const REVIEW_ACTION_FINISH = "Finish Remaining"; +const TAKE_GROUP_WIDGET = "take_group"; +const TAKE_REVISION_WIDGET = "take_revision_id"; +const TAKE_ACTION_WIDGET = "take_action"; +const TAKE_ACTION_AUTOMATIC = "Automatic"; +const TAKE_ACTION_USE = "Use This Take"; +const TAKE_ACTION_CONTINUE = "Continue From Here"; +const REVIEW_PENDING_ACTION = "__h3ContinuumPendingReviewAction"; +const REVIEW_UI_SELECTION = "__h3ContinuumReviewUiSelection"; +const TAKE_PENDING_ACTION = "__h3ContinuumPendingTakeAction"; +const PRODUCTION_STATUS_WIDGET = "Review Ready"; +const PRODUCTION_CONTINUE_WIDGET = "Use it and continue"; +const PRODUCTION_REGENERATE_WIDGET = "Try this chunk again"; +const PRODUCTION_FINISH_WIDGET = "Use it and finish the rest"; +const PRODUCTION_BACK_TO_SETTINGS_WIDGET = "Back to Settings"; +const PRODUCTION_RETURN_TO_REVIEW_WIDGET = "Return to Review"; +const PRODUCTION_RESTART_WIDGET = "Start again from Chunk 1"; +const PRODUCTION_OUTPUT_RETRY_WIDGET = "Retry saved output"; +const TAKE_STATUS_WIDGET = "Render History / Takes"; +const TAKE_TOGGLE_WIDGET = "Render History"; +const TAKE_PREVIOUS_WIDGET = "Previous Take"; +const TAKE_NEXT_WIDGET = "Next Take"; +const TAKE_USE_WIDGET = "Use This Take"; +const TAKE_CONTINUE_WIDGET = "Continue From Here"; +const PRODUCTION_TRANSIENT_WIDGET = "__h3ContinuumProductionTransient"; +const FACADE_TRANSIENT_WIDGET = "__h3ContinuumFacadeTransient"; +const FACADE_PROMPT_FORMAT_WIDGET = "Prompt Format"; +const FACADE_CONTINUITY_WIDGET = "Continuity"; +const FACADE_BASE_SEED_WIDGET = "Base Seed"; +const FACADE_CONTROL_AFTER_WIDGET = "Control After Generate"; +const FACADE_AUDIO_CONTINUITY_WIDGET = "Audio Continuity"; +const FACADE_CHUNKS_WIDGET = "Chunks"; +const FACADE_SECONDS_WIDGET = "Seconds per Chunk"; +const FACADE_TOTAL_LENGTH_WIDGET = "Total Length"; +const FACADE_SIZE_SOURCE_WIDGET = "Size Source"; +const FACADE_RESOLUTION_WIDGET = "Resolution"; +const FACADE_CUSTOM_MP_WIDGET = "Custom MP"; +const FACADE_WIDTH_WIDGET = "Width"; +const FACADE_HEIGHT_WIDGET = "Height"; +const FACADE_GENERATE_WIDGET = "Run"; +const FACADE_SAVE_WIDGET = "Progress"; +const FACADE_READY_WIDGET = "Ready to Queue"; +const FACADE_REFERENCE_SIZE_WIDGET = "Reference Image Size"; +const FACADE_VIDEO_SIZE_WIDGET = "Video Guide Size"; +const FACADE_ADVANCED_WIDGET = "Advanced Settings"; +const FACADE_GENERATE_ALL = "Generate Full Video"; +const FACADE_GENERATE_REVIEW = "Review Each Chunk"; +const FACADE_SAVE_OFF = "Off — No resume or Take history"; +const FACADE_SAVE_ON = "On — Resume and Takes available"; +const FACADE_HELP = Object.freeze({ + [FACADE_PROMPT_FORMAT_WIDGET]: ( + "Prompt interpretation mode. Auto accepts Fixed text, Timeline/List syntax, or JSON and " + + "uses the first valid format it detects." + ), + [FACADE_CONTINUITY_WIDGET]: ( + "Video continuation overlap between chunks. Balanced — 22 frames is the normal Production default." + ), + [FACADE_BASE_SEED_WIDGET]: ( + "Base seed used for deterministic chunk seed derivation. Keep it fixed to reproduce the same run." + ), + [FACADE_CONTROL_AFTER_WIDGET]: ( + "What ComfyUI does to Base Seed after Queue. randomize chooses a new seed for the next Queue; " + + "fixed keeps it unchanged." + ), + [FACADE_AUDIO_CONTINUITY_WIDGET]: ( + "Preserves audio continuation across chunk boundaries. Keep this On for normal audiovisual generation." + ), + [FACADE_CHUNKS_WIDGET]: ( + "Number of Continuum chunks to generate. This is an explicit setting and is never " + + "recalculated from Total Length." + ), + [FACADE_SECONDS_WIDGET]: ( + "Duration of each chunk in seconds. Set this directly, for example 3 chunks × 10 seconds." + ), + [FACADE_TOTAL_LENGTH_WIDGET]: ( + "Read-only total duration calculated from Chunks × Seconds per Chunk. It never changes either setting." + ), + [FACADE_GENERATE_WIDGET]: ( + "Generate Full Video creates all remaining chunks in one Queue. Review Each Chunk pauses " + + "after each physical group so you can keep it, try it again, or finish the rest." + ), + [FACADE_SIZE_SOURCE_WIDGET]: ( + "First Image preserves the selected First Image aspect ratio. Manual uses the exact Width " + + "and Height below. This choice is explicit and is not changed automatically." + ), + [FACADE_RESOLUTION_WIDGET]: ( + "Resolution preset used with First Image sizing. Draft uses least memory, Balanced adds detail, " + + "Native 768 uses the H3 native short edge, and Custom uses Custom MP." + ), + [FACADE_CUSTOM_MP_WIDGET]: ( + "Custom target megapixels while preserving the First Image aspect ratio. The final " + + "Width and Height are aligned to the H3 canvas requirements." + ), + [FACADE_WIDTH_WIDGET]: ( + "Exact output width used in Manual mode. Use a multiple of 32. Manual Width and Height " + + "are suitable for T2VA or any workflow without a First Image." + ), + [FACADE_HEIGHT_WIDGET]: ( + "Exact output height used in Manual mode. Use a multiple of 32. Manual Width and Height " + + "are suitable for T2VA or any workflow without a First Image." + ), + [FACADE_SAVE_WIDGET]: ( + "On saves chunk progress atomically for safe resume and Take history. Review Each Chunk " + + "turns this on automatically." + ), + [FACADE_READY_WIDGET]: ( + "Plain-language summary of what the next normal Queue will do. It uses current graph links " + + "and widget values and does not change the backend contract." + ), + [FACADE_REFERENCE_SIZE_WIDGET]: ( + "Controls only connected Reference Images. Match Output is the practical default. " + + "Max Identity preserves more reference detail but can use more memory." + ), + [FACADE_VIDEO_SIZE_WIDGET]: ( + "Controls only connected Video Guide Frames. Efficient uses about 0.4 MP, Balanced " + + "about 0.6 MP, and Match Output uses the output pixel area." + ), + [FACADE_ADVANCED_WIDGET]: ( + "Show or hide technical controls such as prompt parsing, continuity strength, seed, " + + "audio continuity, continuation backend, and explicit regeneration." + ), +}); +const ADVANCED_WIDGET_HELP = Object.freeze({ + prompt_mode: ( + "How Sequence Prompt is interpreted. Auto detects Fixed, list-separated, and " + + "[time] timeline formats." + ), + continuity: ( + "Amount of prior video context retained at each chunk boundary. Balanced - 22 frames " + + "is the Production default; Strong - 39 frames is experimental." + ), + base_seed: ( + "Base seed used to derive deterministic per-chunk seeds. Keep it fixed when comparing " + + "settings or Takes." + ), + control_after_generate: ( + "Controls how Base Seed changes after Queue. Use fixed/keep for repeatable comparisons; " + + "randomize creates a new base seed for the next Queue." + ), + audio_continuity: ( + "On carries previous generated-audio context across chunk boundaries. Turn it off only " + + "when isolating or replacing generated audio." + ), + continuation_backend: ( + "Standard uses the current V3.8 continuation path. Compatibility restores the older " + + "Reference Context path for comparison or older workflows." + ), + reroll_from_chunk: ( + "Auto resumes the longest compatible saved prefix. Selecting a chunk reuses everything " + + "before it and regenerates that chunk and all following chunks." + ), + run_name: ( + "Optional stable name for Resume and Render History. Leave blank to use the sampler's " + + "automatic project identity." + ), + reroll_nonce: ( + "Variation number for an explicit regeneration. Change it to create another Take while " + + "keeping the same prompt, seed, and other settings." + ), +}); +const V38_VIEW_PROPERTY = "H3 Continuum View"; +const V38_VIEW_BASIC = "Basic"; +const V38_VIEW_PRODUCTION = "Production"; +const V38_VIEW_OPTIONS = [V38_VIEW_BASIC, V38_VIEW_PRODUCTION]; +const SETTINGS = { + detailedReport: "H3Continuum.DetailedReport", + developerDiagnostics: "H3Continuum.DeveloperDiagnostics", + samplingPreview: "H3Continuum.SamplingPreview", +}; + +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 findWidget(node, name) { + return node.widgets?.find((widget) => widget.name === name); +} + +function setWidgetVisible(widget, visible) { + if (!widget) { + return; + } + if (!widget.__h3ContinuumOriginal) { + widget.__h3ContinuumOriginal = { + type: widget.type, + computeSize: widget.computeSize, + hidden: widget.hidden, + optionsHidden: widget.options?.hidden, + }; + } + widget.options ||= {}; + if (visible) { + const original = widget.__h3ContinuumOriginal; + 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; + } + } else { + widget.hidden = true; + widget.type = "converted-widget"; + widget.options.hidden = true; + widget.computeSize = () => [0, -4]; + } +} + +function hidePersistentWidget(widget) { + setWidgetVisible(widget, false); +} + +function settingValue(id, fallback) { + try { + return app.ui?.settings?.getSettingValue?.(id) ?? fallback; + } catch { + return fallback; + } +} + +function applyRuntimeSettings(node) { + const detailed = Boolean(settingValue(SETTINGS.detailedReport, false)); + const debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); + const preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); + const diagnosticsWidget = findWidget(node, "diagnostics"); + const debugWidget = findWidget(node, "debug"); + const previewWidget = findWidget(node, "show_preview"); + const strictWidget = findWidget(node, "strict_compatibility"); + if (diagnosticsWidget) diagnosticsWidget.value = detailed ? "Detailed Report" : "Basic"; + if (debugWidget) debugWidget.value = debug; + if (previewWidget) previewWidget.value = preview; + if (strictWidget) strictWidget.value = false; +} + +function removeUnusedInput(node, name) { + const index = node.inputs?.findIndex((input) => input.name === name) ?? -1; + if (index < 0) { + return; + } + const input = node.inputs[index]; + if (input.link != null) { + app.graph?.removeLink(input.link); + } + node.removeInput(index); +} + +function regenerateOptions(chunks) { + const count = Math.max(1, Math.min(16, Number.parseInt(chunks, 10) || 1)); + return ["Auto", ...Array.from({ length: count }, (_, index) => `Chunk ${index + 1}`)]; +} + +function configureRegenerateFrom(node) { + const chunksWidget = findWidget(node, CHUNKS_WIDGET); + const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + if (!chunksWidget || !regenerateWidget) { + return; + } + const refresh = () => { + const values = regenerateOptions(chunksWidget.value); + regenerateWidget.options ||= {}; + regenerateWidget.options.values = values; + const numeric = typeof regenerateWidget.value === "number" + ? regenerateWidget.value + : Number.parseInt(String(regenerateWidget.value).replace(/^Chunk\s+/, ""), 10); + if (regenerateWidget.value === "Auto" || numeric === 0) { + regenerateWidget.value = "Auto"; + } else if (Number.isInteger(numeric) && numeric >= 1 && numeric < values.length) { + regenerateWidget.value = `Chunk ${numeric}`; + } else { + regenerateWidget.value = "Auto"; + } + }; + if (!chunksWidget.__h3ContinuumRegenerateCallback) { + const previous = chunksWidget.callback; + chunksWidget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + refresh(); + return result; + }; + chunksWidget.__h3ContinuumRegenerateCallback = true; + } + refresh(); +} + +function linkedInput(node, names) { + return node.inputs?.some((input) => names.includes(input.name) && input.link != null) ?? false; +} + +function removeUnusedLegacyInputs(node) { + if (!isModernSamplerClass(node.comfyClass)) return; + for (const name of ["guide", "reference_audio_1", "reference_audio_vae"]) { + if (!linkedInput(node, [name])) removeUnusedInput(node, name); + } +} + +function activeLinkedInput(node, names) { + const inputs = node.inputs?.filter( + (item) => names.includes(item.name) && item.link != null, + ) || []; + return inputs.some((input) => { + const link = app.graph?.links?.[input.link]; + if (!link) return true; + const source = app.graph?.getNodeById?.(link.origin_id); + if (!source) return true; + if ([2, 4].includes(Number(source.mode))) return false; + if (source.comfyClass === "H3ContinuumReferenceImages") { + return activeLinkedInput(source, source.inputs.filter( + (item) => /^reference_image_[4-9]$/.test(item.name), + ).map((item) => item.name)); + } + const enableWidget = source.widgets?.find((widget) => ( + [ + "Enable Image", + "Enable Video", + "Enable Audio", + "enable_image", + "enable_video", + "enable_audio", + ].includes(widget.name) + )); + if (!enableWidget) return true; + const value = enableWidget.value; + if (typeof value === "boolean") return value; + return !["off", "false", "disabled", "0", ""].includes( + String(value).trim().toLowerCase(), + ); + }); +} + +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 transientProductionWidgets(node) { + return node.widgets?.filter((widget) => widget[PRODUCTION_TRANSIENT_WIDGET]) || []; +} + +function installProductionSerializationGuard(node) { + if (node.__h3ContinuumProductionSerializationGuard) return; + const withoutTransientWidgets = (callback, owner, args) => { + const widgets = owner.widgets; + if (!Array.isArray(widgets)) return callback.apply(owner, args); + const removed = []; + for (let index = widgets.length - 1; index >= 0; index -= 1) { + if (widgets[index]?.[PRODUCTION_TRANSIENT_WIDGET]) { + removed.push({ index, widget: widgets[index] }); + widgets.splice(index, 1); + } + } + try { + return callback.apply(owner, args); + } finally { + removed.sort((left, right) => left.index - right.index); + for (const item of removed) { + widgets.splice(Math.min(item.index, widgets.length), 0, item.widget); + } + } + }; + const originalSerialize = node.serialize; + if (typeof originalSerialize === "function") { + node.serialize = function(...args) { + return withoutTransientWidgets(originalSerialize, this, args); + }; + } + const originalConfigure = node.configure; + if (typeof originalConfigure === "function") { + node.configure = function(...args) { + return withoutTransientWidgets(originalConfigure, this, args); + }; + } + node.__h3ContinuumProductionSerializationGuard = true; +} + +function addTransientProductionWidget(node, type, name, value, callback, options = {}) { + if (typeof node.addWidget !== "function") return null; + const widget = node.addWidget( + type, + name, + value, + callback, + { ...options, serialize: false }, + ); + if (!widget) return null; + widget[PRODUCTION_TRANSIENT_WIDGET] = true; + widget.serialize = false; + widget.options ||= {}; + widget.options.serialize = false; + return widget; +} + +function setExistingWidgetValue(widget, value) { + if (!widget || widget.value === value) return; + widget.value = value; + widget.callback?.(value); +} + +function hasManualRegenerateIntent(node) { + const value = findWidget(node, REGENERATE_WIDGET)?.value; + return Boolean(node.__h3ContinuumManualRegenerateIntent + || (value && value !== "Auto" + && node.properties?.[REGENERATE_INTENT_PROPERTY] === value)); +} + +function setRegenerateProgrammatically(node, value) { + const widget = findWidget(node, REGENERATE_WIDGET); + if (!widget) return; + delete node.__h3ContinuumManualRegenerateIntent; + if (node.properties) delete node.properties[REGENERATE_INTENT_PROPERTY]; + node.__h3ContinuumProgrammaticRegenerate = true; + try { + setExistingWidgetValue(widget, value); + } finally { + delete node.__h3ContinuumProgrammaticRegenerate; + } + if (value === "Auto" || value === 0 || value == null) { + delete node.__h3ContinuumManualRegenerateIntent; + } +} + +function repairStaleReviewRegenerate(node, project) { + const revision = canonicalStorageRevision(project); + if ( + !revision + || !["review_ready", "complete"].includes(revision.status) + || activeReviewPrompt(node) + || hasManualRegenerateIntent(node) + || node.__h3ContinuumRestartSelected + ) { + return false; + } + const widget = findWidget(node, REGENERATE_WIDGET); + // Only the legacy unowned Chunk 1 / nonce 0 residue is ambiguous. + // Later boundaries and fixed variations are explicit saved settings. + if (!["Chunk 1", 1].includes(widget?.value) + || Number(findWidget(node, REROLL_NONCE_WIDGET)?.value ?? 0) !== 0) return false; + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); + return true; +} + +function facadeProductionWidgets(node) { + return node.widgets?.filter((widget) => widget[FACADE_TRANSIENT_WIDGET]) || []; +} + +function addFacadeWidget(node, type, name, value, callback, options = {}) { + let widget = facadeProductionWidgets(node).find((item) => item.name === name); + if (widget) return widget; + widget = addTransientProductionWidget(node, type, name, value, callback, options); + if (!widget) return null; + widget[FACADE_TRANSIENT_WIDGET] = true; + return widget; +} + +function drawRoundedRect(ctx, x, y, width, height, radius) { + const safeRadius = Math.max(0, Math.min(radius, width / 2, height / 2)); + ctx.beginPath(); + if (typeof ctx.roundRect === "function") { + ctx.roundRect(x, y, width, height, safeRadius); + } else { + ctx.moveTo(x + safeRadius, y); + ctx.lineTo(x + width - safeRadius, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + safeRadius); + ctx.lineTo(x + width, y + height - safeRadius); + ctx.quadraticCurveTo(x + width, y + height, x + width - safeRadius, y + height); + ctx.lineTo(x + safeRadius, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - safeRadius); + ctx.lineTo(x, y + safeRadius); + ctx.quadraticCurveTo(x, y, x + safeRadius, y); + } + ctx.closePath(); +} + +function drawFacadeInfoWidget(widget, ctx, width, y, height) { + const left = 15; + const top = y + 3; + const innerWidth = Math.max(80, width - 30); + const innerHeight = Math.max(18, height - 6); + const variant = widget.__h3ContinuumInfoVariant || "row"; + ctx.save(); + ctx.textBaseline = "middle"; + if (variant === "badges") { + const badges = Array.isArray(widget.badges) ? widget.badges : []; + const gap = 6; + const chipWidth = Math.max(70, (innerWidth - gap * 3) / 4); + const chipHeight = Math.min(26, innerHeight); + for (let index = 0; index < badges.length; index += 1) { + const badge = badges[index]; + const chipX = left + index * (chipWidth + gap); + drawRoundedRect(ctx, chipX, top, chipWidth, chipHeight, 7); + ctx.fillStyle = badge.connected ? "rgba(31, 86, 38, 0.96)" : "rgba(31, 31, 31, 0.96)"; + ctx.fill(); + ctx.strokeStyle = badge.connected ? "#63d36d" : "#666"; + ctx.lineWidth = 1; + ctx.stroke(); + ctx.fillStyle = badge.connected ? "#e7ffe9" : "#bdbdbd"; + ctx.font = "12px Arial"; + ctx.textAlign = "center"; + ctx.fillText( + `${badge.label} ${badge.connected ? "✓" : "—"}`, + chipX + chipWidth / 2, + top + chipHeight / 2, + chipWidth - 10, + ); + } + ctx.restore(); + return; + } + + const palette = variant === "ready" + ? { + background: "rgba(17, 55, 24, 0.96)", + border: "#58c963", + headline: "#8ee987", + detail: "#e8f5e9", + } + : variant === "review" + ? { + background: "rgba(55, 42, 15, 0.97)", + border: "#b98b2d", + headline: "#ffc85a", + detail: "#f4ead2", + } + : { + background: "rgba(28, 28, 28, 0.96)", + border: "#666", + headline: "#bdbdbd", + detail: "#f0f0f0", + }; + drawRoundedRect(ctx, left, top, innerWidth, innerHeight, 8); + ctx.fillStyle = palette.background; + ctx.fill(); + ctx.strokeStyle = palette.border; + ctx.lineWidth = 1; + ctx.stroke(); + + if (variant === "row") { + ctx.font = "13px Arial"; + ctx.fillStyle = palette.headline; + ctx.textAlign = "left"; + ctx.fillText(widget.name, left + 12, top + innerHeight / 2, innerWidth * 0.43); + ctx.font = "13px Arial"; + ctx.fillStyle = palette.detail; + ctx.textAlign = "right"; + ctx.fillText(String(widget.value || ""), left + innerWidth - 12, top + innerHeight / 2, innerWidth * 0.57); + } else if (variant === "details") { + ctx.font = "12px Arial"; + ctx.fillStyle = palette.detail; + ctx.textAlign = "center"; + ctx.fillText(String(widget.value || ""), left + innerWidth / 2, top + innerHeight / 2, innerWidth - 20); + } else { + ctx.textAlign = "left"; + ctx.font = "bold 14px Arial"; + ctx.fillStyle = palette.headline; + ctx.fillText(String(widget.headline || widget.name), left + 14, top + 19, innerWidth - 28); + ctx.font = "12px Arial"; + ctx.fillStyle = palette.detail; + ctx.fillText(String(widget.detail || ""), left + 14, top + 42, innerWidth - 28); + } + ctx.restore(); +} + +function addFacadeInfoWidget(node, name, variant, height, facade = true) { + let widget = transientProductionWidgets(node).find((item) => item.name === name); + if (widget) return widget; + if (typeof node.addCustomWidget === "function") { + widget = { + name, + type: "custom", + value: "", + options: { serialize: false }, + serialize: false, + __h3ContinuumInfoVariant: variant, + computeSize(width) { + return [width, height]; + }, + draw(ctx, _node, width, y, _widgetHeight) { + drawFacadeInfoWidget(this, ctx, width, y, height); + }, + }; + widget[PRODUCTION_TRANSIENT_WIDGET] = true; + if (facade) widget[FACADE_TRANSIENT_WIDGET] = true; + node.addCustomWidget(widget); + } else { + widget = facade + ? addFacadeWidget( + node, + "text", + name, + "", + null, + { multiline: variant === "ready" || variant === "review" }, + ) + : addTransientProductionWidget( + node, + "text", + name, + "", + null, + { multiline: variant === "ready" || variant === "review" }, + ); + if (widget) { + widget.disabled = true; + widget.__h3ContinuumInfoVariant = variant; + widget.computeSize = () => [Math.max(300, Number(node.size?.[0] || 0)), height]; + } + } + return widget; +} + +function compactValue(value, maximumFractionDigits = 1) { + const number = Number(value); + if (!Number.isFinite(number)) return String(value ?? ""); + if (Number.isInteger(number)) return String(number); + return number.toFixed(maximumFractionDigits).replace(/\.?0+$/, ""); +} + +function durationLabel(node, chunks = null) { + if (linkedInput(node, [CHUNKS_WIDGET, "chunk_seconds"])) { + return "From connected inputs"; + } + const chunkCount = Number(chunks ?? findWidget(node, CHUNKS_WIDGET)?.value ?? 1); + const seconds = Number(findWidget(node, "chunk_seconds")?.value || 5); + return `${compactValue(chunkCount * seconds)} seconds`; +} + +function frameSizeLabel(width, height) { + return `${Math.round(Number(width) || 0)} × ${Math.round(Number(height) || 0)}`; +} + +function manualSizeLabel(node) { + const widthLinked = linkedInput(node, [WIDTH_WIDGET]); + const heightLinked = linkedInput(node, [HEIGHT_WIDGET]); + if (widthLinked && heightLinked) return "Width / Height from connected INT inputs"; + const width = findWidget(node, WIDTH_WIDGET)?.value; + const height = findWidget(node, HEIGHT_WIDGET)?.value; + if (widthLinked) return `Width from connected input • Height ${compactValue(height, 0)}`; + if (heightLinked) return `Width ${compactValue(width, 0)} • Height from connected input`; + return frameSizeLabel(width, height); +} + +function requiredConnectionNames(node) { + const labels = { + model: "Model", + clip: "CLIP", + video_vae: "Video VAE", + sampler: "Sampler", + sigmas: "Sigmas", + }; + return Object.entries(labels) + .filter(([name]) => !linkedInput(node, [name])) + .map(([, label]) => label); +} + +function baseSeedControlWidget(node) { + const seedWidget = findWidget(node, "base_seed"); + const linkedControl = seedWidget?.linkedWidgets?.find( + (widget) => widget?.name === "control_after_generate", + ); + return linkedControl || findWidget(node, "control_after_generate"); +} + +function setReviewSeedControlFixed(node) { + const control = baseSeedControlWidget(node); + if (!control) return false; + setExistingWidgetValue(control, "fixed"); + return String(control.value || "").toLowerCase() === "fixed"; +} + +function requireFixedSeedForReview(node) { + if (!isModernSamplerClass(node.comfyClass)) return; + if (findWidget(node, GENERATION_MODE_WIDGET)?.value !== GENERATION_MODE_REVIEW) return; + const control = String(baseSeedControlWidget(node)?.value || "").toLowerCase(); + if (control === "fixed") return; + throw new Error( + "H3 Continuum V3.8: Run = Review Each Chunk requires " + + "Control After Generate = fixed. This keeps Base Seed unchanged so the " + + "next Queue can reuse the accepted Chunk.", + ); +} + +function readySummary(node) { + if (activeReviewPrompt(node)) return {headline:"Queued / generating", detail:"Waiting for this Run's saved result."}; + if (node.__h3ContinuumOutputFailure?.runName === takeRunName(node)) return { + headline:"Chunk saved — output incomplete", detail:node.__h3ContinuumOutputFailure.message, + }; + if (node.__h3ContinuumQueueNotice) return {headline:"Check saved progress", detail:node.__h3ContinuumQueueNotice}; + if (findWidget(node, RUN_STORAGE_WIDGET)?.value === "Save + Auto Resume") { + if (reviewGraphHydrating || node.__h3ContinuumConfigurePending) return { + headline: "Restoring Review", detail: "Waiting for Workflow settings and connections.", + }; + if (node.__h3ContinuumHistoryRequest) return { + headline: "Loading saved progress", detail: "Reading this Run's Review and Render History.", + }; + if (node.__h3ContinuumTakeError) return { + headline: "Review history unavailable", detail: node.__h3ContinuumTakeError, + }; + } + const missing = requiredConnectionNames(node); + if (missing.length) { + return { + headline: "Connect required inputs", + detail: `Missing: ${missing.join(", ")}`, + }; + } + const sizeSource = findWidget(node, SIZE_SOURCE_WIDGET)?.value; + if ( + sizeSource === SIZE_SOURCE_FIRST_IMAGE + && !activeLinkedInput(node, ["first_frame"]) + ) { + return { + headline: "Check First Image", + detail: `Size Source is First Image, but no active image is connected. ${linkedInput(node, [WIDTH_WIDGET, HEIGHT_WIDGET]) ? "Fallback size" : "Queue fallback"}: ${manualSizeLabel(node)}.`, + }; + } + const chunks = Math.max(1, Number(findWidget(node, CHUNKS_WIDGET)?.value || 1)); + const seconds = Number(findWidget(node, "chunk_seconds")?.value || 5); + const reviewing = findWidget(node, GENERATION_MODE_WIDGET)?.value === GENERATION_MODE_REVIEW; + if (reviewing && chunks < 2 && !linkedInput(node, [CHUNKS_WIDGET])) { + return { + headline: "Set Chunks to 2 or more", + detail: ( + `Chunks is 1, so the first ${compactValue(seconds)}s chunk is also the last. ` + + "Set Chunks to 2 or more before Queue to use Review and Continue." + ), + }; + } + const controlAfterGenerate = String( + baseSeedControlWidget(node)?.value || "", + ).toLowerCase(); + if (reviewing && controlAfterGenerate !== "fixed") { + return { + headline: "Set Control After Generate to fixed", + detail: "Review Each Chunk must keep Base Seed unchanged between Queue runs.", + }; + } + const duration = linkedInput(node, [CHUNKS_WIDGET, "chunk_seconds"]) + ? "Duration from connected inputs" + : `${compactValue(chunks)} × ${compactValue(seconds)}s = ${durationLabel(node)}`; + const output = sizeSource === SIZE_SOURCE_FIRST_IMAGE + ? "First Image" + : `Manual ${manualSizeLabel(node)}`; + return { + headline: "Ready to Queue", + detail: `${duration} • ${output}${reviewing ? " • Review each chunk" : ""}`, + }; +} + +function setWidgetTooltip(widget, tooltip) { + if (!widget || !tooltip) return; + widget.tooltip = tooltip; + widget.options ||= {}; + widget.options.tooltip = tooltip; +} + +function facadeWidgetTooltip(node, name) { + if ([FACADE_WIDTH_WIDGET, FACADE_HEIGHT_WIDGET].includes(name)) { + const source = name === FACADE_WIDTH_WIDGET ? WIDTH_WIDGET : HEIGHT_WIDGET; + if (linkedInput(node, [source])) return ( + `Connected INT supplies ${name} at execution; the displayed number is the saved Manual reserve. ` + + "Disconnect to edit it. First Image sizing still uses the image and Resolution; " + + "the connected dimension applies only to Manual sizing or a missing-image fallback." + ); + } + if (name === FACADE_CHUNKS_WIDGET) { + const reviewing = findWidget(node, GENERATION_MODE_WIDGET)?.value === GENERATION_MODE_REVIEW; + const chunks = Math.max(1, Number(findWidget(node, CHUNKS_WIDGET)?.value || 1)); + if (reviewing && chunks < 2 && !linkedInput(node, [CHUNKS_WIDGET])) { + return ( + "Chunks is 1, so there is no next chunk to continue. Set Chunks to 2 or more " + + "before Queue when using Review Each Chunk." + ); + } + } + if (name === FACADE_GENERATE_WIDGET) { + const reviewing = findWidget(node, GENERATION_MODE_WIDGET)?.value === GENERATION_MODE_REVIEW; + return reviewing + ? ( + "Review Each Chunk: the next normal Queue generates at most one new physical group. " + + "Set Chunks to 2 or more; when the first chunk is ready, choose one of the " + + "three review actions, then press Queue." + ) + : ( + "Generate Full Video: one normal Queue generates all remaining chunks without pausing for review. " + + "Use Review Each Chunk when you want to approve or retry each result." + ); + } + if (name === FACADE_CONTROL_AFTER_WIDGET) { + const reviewing = findWidget(node, GENERATION_MODE_WIDGET)?.value === GENERATION_MODE_REVIEW; + if (reviewing) { + return ( + "Review Each Chunk requires fixed. Changing Base Seed between Queue runs " + + "starts a different stored revision instead of continuing the accepted Chunk." + ); + } + } + if (name === FACADE_SIZE_SOURCE_WIDGET) { + const firstImage = findWidget(node, SIZE_SOURCE_WIDGET)?.value === SIZE_SOURCE_FIRST_IMAGE; + return firstImage + ? ( + "First Image: uses the aspect ratio of the image connected to First Image, then " + + "Resolution chooses the pixel area. Use this for I2VA or FL2VA. If the image is unavailable, " + + "the displayed Manual Width and Height are used as a safe fallback." + ) + : ( + "Manual: enter exact Width and Height. Use this for T2VA, workflows without a First Image, " + + "or whenever the output canvas must be specified directly." + ); + } + if (name === FACADE_RESOLUTION_WIDGET) { + const preset = String(findWidget(node, RESOLUTION_PRESET_WIDGET)?.value || ""); + if (preset === RESOLUTION_PRESET_DRAFT) { + return "Draft - 0.30 MP: fastest First Image sizing option and the lowest VRAM starting point."; + } + if (preset === RESOLUTION_PRESET_BALANCED) { + return "Balanced - 0.60 MP: higher-detail First Image sizing with greater VRAM and processing cost."; + } + if (preset === RESOLUTION_PRESET_NATIVE) { + return "Native 768: preserves the First Image aspect with an H3-native 768 px short edge and a 1344 px long-edge cap."; + } + return "Custom: preserves the First Image aspect and uses the Custom MP target shown below."; + } + if (name === FACADE_SAVE_WIDGET) { + const enabled = findWidget(node, RUN_STORAGE_WIDGET)?.value === "Save + Auto Resume"; + return enabled + ? ( + "On: saves raw chunk progress and immutable Take history for safe resume, regeneration, " + + "Use This Take, and Continue From Here." + ) + : ( + "Off: does not keep resumable chunk history. Turn this On for Review Each Chunk, " + + "Render History, or partial regeneration." + ); + } + if (name === FACADE_REFERENCE_SIZE_WIDGET) { + const mode = String(findWidget(node, REFERENCE_SIZE_WIDGET)?.value || "Match Output"); + return mode === "Max Identity" + ? "Max Identity: retains more Reference Image detail for identity guidance, with a higher memory cost." + : "Match Output: resizes connected Reference Images to the output canvas. This is the practical default."; + } + if (name === FACADE_VIDEO_SIZE_WIDGET) { + const mode = String(findWidget(node, VIDEO_REFERENCE_SIZE_WIDGET)?.value || "Efficient - 0.4 MP"); + if (mode === "Balanced - 0.6 MP") { + return "Balanced - 0.6 MP: keeps more Video Guide detail than Efficient and uses more memory."; + } + if (mode === "Match Output") { + return "Match Output: processes Video Guide Frames at the output pixel area. This can be substantially heavier."; + } + return "Efficient - 0.4 MP: reduces Video Guide conditioning cost while preserving its source aspect ratio."; + } + return FACADE_HELP[name] || ""; +} + +function applyV38WidgetHelp(node) { + for (const widget of facadeProductionWidgets(node)) { + setWidgetTooltip(widget, facadeWidgetTooltip(node, widget.name)); + } + for (const [name, tooltip] of Object.entries(ADVANCED_WIDGET_HELP)) { + setWidgetTooltip(findWidget(node, name), tooltip); + } +} + +function installCompactNumberDisplay(widget, maximumFractionDigits) { + if (!widget || widget.type !== "number") return; + widget.options ||= {}; + delete widget.options.precision; + Object.defineProperty(widget, "_displayValue", { + configurable: true, + get() { + const value = Number(this.value); + if (!Number.isFinite(value)) return String(this.value ?? ""); + if (maximumFractionDigits <= 0 || Number.isInteger(value)) { + return String(Math.round(value)); + } + return value.toFixed(maximumFractionDigits).replace(/\.?0+$/, ""); + }, + }); +} + +function addFacadeProxyWidget( + node, + { + type, + name, + sourceName, + sourceWidget = null, + options = {}, + fromSource = (value) => value, + onSet = null, + compactDecimals = null, + }, +) { + const source = sourceWidget || findWidget(node, sourceName); + if (!source) return null; + let widget = facadeProductionWidgets(node).find((item) => item.name === name); + if (!widget) { + widget = addFacadeWidget( + node, + type, + name, + fromSource(source.value), + (value) => { + if ([WIDTH_WIDGET, HEIGHT_WIDGET].includes(sourceName) + && linkedInput(node, [sourceName])) return; + if (onSet) { + onSet(value, source); + } else { + setExistingWidgetValue(source, value); + } + node.__h3ContinuumIntuitiveUxRefresh?.(); + }, + options, + ); + if (widget) { + setWidgetTooltip(widget, source.tooltip || source.options?.tooltip); + } + } + if (!widget) return null; + if (Number.isInteger(compactDecimals) && compactDecimals >= 0) { + installCompactNumberDisplay(widget, compactDecimals); + } + widget.value = fromSource(source.value); + const refreshKey = `__h3ContinuumFacadeRefresh_${name.replaceAll(" ", "_")}`; + attachRefresh(source, refreshKey, () => { + widget.value = fromSource(source.value); + node.__h3ContinuumIntuitiveUxRefresh?.(); + }); + return widget; +} + +function moveFacadeWidgetsToFront(node, orderedNames) { + if (!Array.isArray(node.widgets)) return; + const byName = new Map( + facadeProductionWidgets(node).map((widget) => [widget.name, widget]), + ); + const ordered = orderedNames.map((name) => byName.get(name)).filter(Boolean); + const remainder = node.widgets.filter((widget) => !widget[FACADE_TRANSIENT_WIDGET]); + node.widgets.splice(0, node.widgets.length, ...ordered, ...remainder); +} + +function configureFacadeInputSlots(node) { + const names = new Map([ + [CHUNKS_WIDGET, FACADE_CHUNKS_WIDGET], + ["chunk_seconds", FACADE_SECONDS_WIDGET], + [WIDTH_WIDGET, FACADE_WIDTH_WIDGET], + [HEIGHT_WIDGET, FACADE_HEIGHT_WIDGET], + ]); + // Core lays out widget sockets using the direct widget binding, not the + // getWidgetFromSlot override used for drawing and disabled-state lookup. + // Search current slots on every configure pass: graph restore replaces them. + for (const [source, facade] of names) { + const slot = node.inputs?.find((input) => (input.widget?.name || input.name) === source); + const widget = findWidget(node, facade); + if (slot && widget) slot._widget = widget; + } + node._widgetSlotsDirty = true; + if (node.__h3ContinuumFacadeSlots || typeof node.getWidgetFromSlot !== "function" + || typeof node.getSlotFromWidget !== "function") return; + const getWidget = node.getWidgetFromSlot; + const getSlot = node.getSlotFromWidget; + // Keep Core input names/configuration intact; only map their visible controls. + node.getWidgetFromSlot = function(slot) { + const facade = names.get(slot?.widget?.name || slot?.name); + return facade ? findWidget(this, facade) : getWidget.call(this, slot); + }; + node.getSlotFromWidget = function(widget) { + for (const [source, facade] of names) { + if (widget?.name === facade) return this.inputs?.find( + (input) => (input.widget?.name || input.name) === source, + ) || getSlot.call(this, findWidget(this, source)); + } + return getSlot.call(this, widget); + }; + node.__h3ContinuumFacadeSlots = true; +} + +function moveNamedWidgetsToFront(node, orderedNames) { + if (!Array.isArray(node.widgets)) return; + const byName = new Map(node.widgets.map((widget) => [widget.name, widget])); + const ordered = orderedNames.map((name) => byName.get(name)).filter(Boolean); + const selected = new Set(ordered); + const remainder = node.widgets.filter((widget) => !selected.has(widget)); + node.widgets.splice(0, node.widgets.length, ...ordered, ...remainder); +} + +function configureIntuitiveV38Ux(node) { + if (!isModernSamplerClass(node.comfyClass) || typeof node.addWidget !== "function") return; + const sourceOptions = (name) => { + const widget = name === "control_after_generate" + ? baseSeedControlWidget(node) + : findWidget(node, name); + const values = widget?.options?.values; + return Array.isArray(values) ? [...values] : values; + }; + + const promptFormatFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_PROMPT_FORMAT_WIDGET, + sourceName: "prompt_mode", + options: { values: sourceOptions("prompt_mode") }, + }); + const continuityFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_CONTINUITY_WIDGET, + sourceName: "continuity", + options: { values: sourceOptions("continuity") }, + }); + const baseSeedSource = findWidget(node, "base_seed"); + const baseSeedFacade = addFacadeProxyWidget(node, { + type: "number", + name: FACADE_BASE_SEED_WIDGET, + sourceName: "base_seed", + compactDecimals: 0, + options: { + min: baseSeedSource?.options?.min, + max: baseSeedSource?.options?.max, + step: baseSeedSource?.options?.step, + }, + }); + const controlAfterFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_CONTROL_AFTER_WIDGET, + sourceName: "control_after_generate", + sourceWidget: baseSeedControlWidget(node), + options: { values: sourceOptions("control_after_generate") }, + }); + const audioContinuityFacade = addFacadeProxyWidget(node, { + type: "toggle", + name: FACADE_AUDIO_CONTINUITY_WIDGET, + sourceName: "audio_continuity", + }); + const chunksFacade = addFacadeProxyWidget(node, { + type: "number", + name: FACADE_CHUNKS_WIDGET, + sourceName: CHUNKS_WIDGET, + compactDecimals: 0, + options: { + min: findWidget(node, CHUNKS_WIDGET)?.options?.min, + max: findWidget(node, CHUNKS_WIDGET)?.options?.max, + step: findWidget(node, CHUNKS_WIDGET)?.options?.step, + }, + }); + const secondsFacade = addFacadeProxyWidget(node, { + type: "number", + name: FACADE_SECONDS_WIDGET, + sourceName: "chunk_seconds", + compactDecimals: 1, + options: { + min: findWidget(node, "chunk_seconds")?.options?.min, + max: findWidget(node, "chunk_seconds")?.options?.max, + step: findWidget(node, "chunk_seconds")?.options?.step, + }, + }); + const totalLengthWidget = addFacadeInfoWidget( + node, + FACADE_TOTAL_LENGTH_WIDGET, + "row", + 34, + ); + const readyWidget = addFacadeInfoWidget(node, FACADE_READY_WIDGET, "ready", 62); + + const outputFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_SIZE_SOURCE_WIDGET, + sourceName: SIZE_SOURCE_WIDGET, + options: { values: [SIZE_SOURCE_FIRST_IMAGE, SIZE_SOURCE_MANUAL] }, + }); + + const qualityFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_RESOLUTION_WIDGET, + sourceName: RESOLUTION_PRESET_WIDGET, + options: { values: sourceOptions(RESOLUTION_PRESET_WIDGET) }, + }); + + for (const [type, name, sourceName] of ( + [ + ["number", FACADE_CUSTOM_MP_WIDGET, CUSTOM_MP_WIDGET], + ["number", FACADE_WIDTH_WIDGET, WIDTH_WIDGET], + ["number", FACADE_HEIGHT_WIDGET, HEIGHT_WIDGET], + ["combo", FACADE_REFERENCE_SIZE_WIDGET, REFERENCE_SIZE_WIDGET], + ["combo", FACADE_VIDEO_SIZE_WIDGET, VIDEO_REFERENCE_SIZE_WIDGET], + ] + )) { + const source = findWidget(node, sourceName); + addFacadeProxyWidget(node, { + type, + name, + sourceName, + compactDecimals: type === "number" + ? (name === FACADE_CUSTOM_MP_WIDGET ? 2 : 0) + : null, + options: type === "combo" + ? { values: sourceOptions(sourceName) } + : { + min: source?.options?.min, + max: source?.options?.max, + step: source?.options?.step, + }, + }); + } + + const generationFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_GENERATE_WIDGET, + sourceName: GENERATION_MODE_WIDGET, + options: { values: [FACADE_GENERATE_ALL, FACADE_GENERATE_REVIEW] }, + fromSource: (value) => ( + value === GENERATION_MODE_REVIEW ? FACADE_GENERATE_REVIEW : FACADE_GENERATE_ALL + ), + onSet: (value, source) => { + const reviewing = value === FACADE_GENERATE_REVIEW; + if (reviewing && source.value !== GENERATION_MODE_REVIEW) { + // Selecting a mode is setup, not selecting a saved review. + node.__h3ContinuumModeSetup = {}; + } else if (!reviewing) { + delete node.__h3ContinuumModeSetup; + } + setExistingWidgetValue( + source, + reviewing ? GENERATION_MODE_REVIEW : GENERATION_MODE_FULL_RUN, + ); + if (reviewing) { + setExistingWidgetValue( + findWidget(node, RUN_STORAGE_WIDGET), + "Save + Auto Resume", + ); + } + }, + }); + if (generationFacade) { + setWidgetTooltip(generationFacade, ( + "Generate Full Video generates every chunk in one Queue. Review Each Chunk pauses " + + "after each completed chunk so you can keep it, try it again, or finish the rest." + )); + } + + const storageFacade = addFacadeProxyWidget(node, { + type: "combo", + name: FACADE_SAVE_WIDGET, + sourceName: RUN_STORAGE_WIDGET, + options: { values: [FACADE_SAVE_OFF, FACADE_SAVE_ON] }, + fromSource: (value) => ( + value === "Save + Auto Resume" ? FACADE_SAVE_ON : FACADE_SAVE_OFF + ), + onSet: (value, source) => { + const enabled = value === FACADE_SAVE_ON; + setExistingWidgetValue(source, enabled ? "Save + Auto Resume" : "Off"); + if (!enabled) { + setExistingWidgetValue( + findWidget(node, GENERATION_MODE_WIDGET), + GENERATION_MODE_FULL_RUN, + ); + } + }, + }); + if (storageFacade) { + setWidgetTooltip(storageFacade, ( + "Keep progress for safe resume and Render History. Review Each Chunk turns this on automatically." + )); + } + let advancedWidget = facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_ADVANCED_WIDGET, + ); + if (!advancedWidget) { + advancedWidget = addFacadeWidget( + node, + "button", + FACADE_ADVANCED_WIDGET, + null, + () => { + node.__h3ContinuumAdvancedOpen = !node.__h3ContinuumAdvancedOpen; + node.__h3ContinuumIntuitiveUxRefresh?.(); + }, + ); + if (advancedWidget) { + setWidgetTooltip(advancedWidget, "Show technical controls only when you need them."); + } + } + const orderedNames = [ + FACADE_PROMPT_FORMAT_WIDGET, + FACADE_CONTINUITY_WIDGET, + FACADE_BASE_SEED_WIDGET, + FACADE_CONTROL_AFTER_WIDGET, + FACADE_AUDIO_CONTINUITY_WIDGET, + FACADE_CHUNKS_WIDGET, + FACADE_SECONDS_WIDGET, + FACADE_TOTAL_LENGTH_WIDGET, + FACADE_SIZE_SOURCE_WIDGET, + FACADE_RESOLUTION_WIDGET, + FACADE_CUSTOM_MP_WIDGET, + FACADE_WIDTH_WIDGET, + FACADE_HEIGHT_WIDGET, + FACADE_GENERATE_WIDGET, + FACADE_SAVE_WIDGET, + FACADE_READY_WIDGET, + FACADE_ADVANCED_WIDGET, + FACADE_REFERENCE_SIZE_WIDGET, + FACADE_VIDEO_SIZE_WIDGET, + ]; + node.__h3ContinuumFacadeOrder = orderedNames; + moveFacadeWidgetsToFront(node, orderedNames); + configureFacadeInputSlots(node); + installProductionSerializationGuard(node); + + const refresh = () => { + const firstImage = findWidget(node, SIZE_SOURCE_WIDGET)?.value === SIZE_SOURCE_FIRST_IMAGE; + const customResolution = ( + firstImage + && findWidget(node, RESOLUTION_PRESET_WIDGET)?.value === CUSTOM_RESOLUTION_PRESET + ); + const referenceConnected = activeLinkedInput( + node, + node.comfyClass === V39_NODE_CLASS ? ["reference_images"] + : ["reference_image_1", "reference_image_2", "reference_image_3", "reference_image_4", "reference_image_5", "image_references"], + ); + const videoConnected = activeLinkedInput(node, ["reference_video_1"]); + const storageEnabled = findWidget(node, RUN_STORAGE_WIDGET)?.value === "Save + Auto Resume"; + const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + const explicitRegeneration = storageEnabled + && regenerateWidget?.value !== "Auto" + && Number.parseInt(String(regenerateWidget?.value).replace(/^Chunk\s+/, ""), 10) > 0; + const advanced = Boolean(node.__h3ContinuumAdvancedOpen); + node.__h3ContinuumAdvancedOpen = advanced; + + if (promptFormatFacade) promptFormatFacade.value = findWidget(node, "prompt_mode")?.value; + if (continuityFacade) continuityFacade.value = findWidget(node, "continuity")?.value; + if (baseSeedFacade) baseSeedFacade.value = findWidget(node, "base_seed")?.value; + if (controlAfterFacade) { + controlAfterFacade.value = baseSeedControlWidget(node)?.value; + } + if (audioContinuityFacade) { + audioContinuityFacade.value = findWidget(node, "audio_continuity")?.value; + } + if (chunksFacade) chunksFacade.value = findWidget(node, CHUNKS_WIDGET)?.value; + if (secondsFacade) secondsFacade.value = findWidget(node, "chunk_seconds")?.value; + if (totalLengthWidget) totalLengthWidget.value = durationLabel(node); + if (outputFacade) { + outputFacade.value = findWidget(node, SIZE_SOURCE_WIDGET)?.value; + } + if (qualityFacade) qualityFacade.value = findWidget(node, RESOLUTION_PRESET_WIDGET)?.value; + if (readyWidget) { + const summary = readySummary(node); + readyWidget.headline = summary.headline; + readyWidget.detail = summary.detail; + readyWidget.value = `${summary.headline}\n${summary.detail}`; + readyWidget.__h3ContinuumInfoVariant = summary.headline === "Ready to Queue" + ? "ready" + : "review"; + } + if (advancedWidget) { + advancedWidget.label = advanced + ? "Hide Advanced Settings" + : "Show Advanced Settings"; + } + + for (const name of orderedNames) { + setWidgetVisible( + facadeProductionWidgets(node).find((widget) => widget.name === name), + true, + ); + } + setWidgetVisible( + facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_RESOLUTION_WIDGET, + ), + firstImage, + ); + setWidgetVisible( + facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_CUSTOM_MP_WIDGET, + ), + customResolution, + ); + for (const name of [FACADE_WIDTH_WIDGET, FACADE_HEIGHT_WIDGET]) { + const source = name === FACADE_WIDTH_WIDGET ? WIDTH_WIDGET : HEIGHT_WIDGET; + const facade = facadeProductionWidgets(node).find((widget) => widget.name === name); + const connected = linkedInput(node, [source]); + if (facade) facade.disabled = firstImage || connected; + setWidgetVisible( + facade, + !firstImage || connected, + ); + } + setWidgetVisible( + facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_REFERENCE_SIZE_WIDGET, + ), + advanced && referenceConnected, + ); + setWidgetVisible( + facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_VIDEO_SIZE_WIDGET, + ), + advanced && videoConnected, + ); + + for (const name of ( + [ + SIZE_SOURCE_WIDGET, + RESOLUTION_PRESET_WIDGET, + CUSTOM_MP_WIDGET, + WIDTH_WIDGET, + HEIGHT_WIDGET, + "prompt_mode", + "continuity", + "base_seed", + "control_after_generate", + "audio_continuity", + CHUNKS_WIDGET, + "chunk_seconds", + RUN_STORAGE_WIDGET, + REFERENCE_SIZE_WIDGET, + VIDEO_REFERENCE_SIZE_WIDGET, + GENERATION_MODE_WIDGET, + REVIEW_ACTION_WIDGET, + ] + )) { + hidePersistentWidget(findWidget(node, name)); + } + for (const name of ( + [ + "continuation_backend", + ] + )) { + setWidgetVisible(findWidget(node, name), advanced); + } + setWidgetVisible(findWidget(node, REGENERATE_WIDGET), advanced && storageEnabled); + setWidgetVisible(findWidget(node, LEGACY_RUN_NAME_WIDGET), advanced && storageEnabled); + setWidgetVisible(findWidget(node, REROLL_NONCE_WIDGET), advanced && explicitRegeneration); + applyV38WidgetHelp(node); + // This is the appended native widget, not another transient proxy. + // Core persists its value; visibility never changes the saved mode. + const videoMode = findWidget(node, "video_reference_mode"); + setWidgetVisible(videoMode, videoConnected); + if (videoMode) { + videoMode.label = "Video Reference Mode"; + setWidgetTooltip(videoMode, String(videoMode.value) === "Follow Timeline" + ? "Experimental: use successive 24 fps source intervals. After the source ends, continue without a video reference. Independent of Prompt Format." + : "Legacy Video Guide behavior: reuse the same bounded source prefix on each physical group. This is not source looping or stretching."); + } + const timelineInput = node.inputs?.find((item) => item.name === "reference_video_1"); + if (timelineInput) { + timelineInput.label = "Timeline Video Frames"; + } + moveFacadeWidgetsToFront(node, orderedNames); + node.__h3ContinuumProductionUxRefresh?.(); + node.setDirtyCanvas?.(true, true); + }; + node.__h3ContinuumIntuitiveUxRefresh = refresh; + for (const [name, key] of ( + [ + ["prompt_mode", "__h3ContinuumFacadePromptMode"], + ["video_reference_mode", "__h3ContinuumFacadeVideoReferenceMode"], + ["continuity", "__h3ContinuumFacadeContinuity"], + ["base_seed", "__h3ContinuumFacadeBaseSeed"], + ["audio_continuity", "__h3ContinuumFacadeAudioContinuity"], + [CHUNKS_WIDGET, "__h3ContinuumFacadeChunks"], + ["chunk_seconds", "__h3ContinuumFacadeSeconds"], + [SIZE_SOURCE_WIDGET, "__h3ContinuumFacadeSizeSource"], + [RESOLUTION_PRESET_WIDGET, "__h3ContinuumFacadePreset"], + [CUSTOM_MP_WIDGET, "__h3ContinuumFacadeCustomMp"], + [WIDTH_WIDGET, "__h3ContinuumFacadeWidth"], + [HEIGHT_WIDGET, "__h3ContinuumFacadeHeight"], + [RUN_STORAGE_WIDGET, "__h3ContinuumFacadeStorage"], + [REGENERATE_WIDGET, "__h3ContinuumFacadeRegenerate"], + [GENERATION_MODE_WIDGET, "__h3ContinuumFacadeGenerate"], + ] + )) { + attachRefresh(findWidget(node, name), key, refresh); + } + attachRefresh( + baseSeedControlWidget(node), + "__h3ContinuumFacadeControlAfter", + refresh, + ); + if (!node.__h3ContinuumFacadeConnectionCallback) { + const previous = node.onConnectionsChange; + node.onConnectionsChange = function(...args) { + const result = previous?.apply(this, args); + setTimeout(refresh, 0); + return result; + }; + node.__h3ContinuumFacadeConnectionCallback = true; + } + refresh(); +} + +function productionQueueSummary(node) { + const generation = findWidget(node, GENERATION_MODE_WIDGET)?.value; + const action = findWidget(node, REVIEW_ACTION_WIDGET)?.value; + if (generation !== GENERATION_MODE_REVIEW) { + return "Full Run"; + } + if (action === REVIEW_ACTION_REGENERATE) { + return "Regenerate current physical group (atomic)"; + } + if (action === REVIEW_ACTION_FINISH) { + return "Reuse accepted prefix + finish remaining"; + } + return "Accept current + continue one physical group"; +} + +function productionRunPlan(node) { + const storage = findWidget(node, RUN_STORAGE_WIDGET)?.value || "Off"; + const regenerateFrom = findWidget(node, REGENERATE_WIDGET)?.value ?? "Auto"; + const nonce = findWidget(node, REROLL_NONCE_WIDGET)?.value ?? 0; + return ( + `Next Queue: ${productionQueueSummary(node)} | ` + + `Storage: ${storage} | From: ${regenerateFrom} | Nonce: ${nonce}` + ); +} + +function canonicalStorageRevision(project) { + const revisionId = String(project?.canonical_storage_revision_id || ""); + const revisions = Array.isArray(project?.revisions) ? project.revisions : []; + return revisions.find((item) => String(item?.revision_id || "") === revisionId) || null; +} + +// Browser edit detection is advisory: it can withdraw stale actions, never +// approve a saved prefix. Run Storage still owns all compatibility/reuse checks. +function reviewSettingsSnapshot(node) { + const ignored = new Set([ + PROJECT_WIDGET, LEGACY_RUN_NAME_WIDGET, RUN_STORAGE_WIDGET, + GENERATION_MODE_WIDGET, REVIEW_ACTION_WIDGET, REGENERATE_WIDGET, + REROLL_NONCE_WIDGET, TAKE_GROUP_WIDGET, TAKE_REVISION_WIDGET, + TAKE_ACTION_WIDGET, "control_after_generate", "diagnostics", "debug", + "strict_compatibility", "show_preview", + ]); + const seen = new Set(); + const visit = (current) => { + if (!current || seen.has(current)) return null; + seen.add(current); + const widgets = (current.widgets || []).filter((widget) => ( + !widget[PRODUCTION_TRANSIENT_WIDGET] && !widget[FACADE_TRANSIENT_WIDGET] + && widget.options?.serialize !== false && widget.type !== "button" + && !(current === node && ignored.has(widget.name)) + )).map((widget) => [widget.name, widget.value]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))); + const graph = node.graph || (typeof app === "undefined" ? null : app.graph); + const inputs = (current.inputs || []).map((input) => { + const link = graph?.links?.[input.link]; + return [input.name, input.link, link?.origin_slot, + visit(graph?.getNodeById?.(link?.origin_id))]; + }); + return [current.id, current.comfyClass || current.type, current.mode, widgets, inputs]; + }; + try { return JSON.stringify(visit(node)); } catch { return null; } +} + +function reviewSettingsChanged(node) { + const baseline = node.__h3ContinuumReviewedSettings; + if (baseline == null) return false; + const current = reviewSettingsSnapshot(node); + return current != null && current !== baseline; +} + +function rememberReviewSettings(node, requestedSettings) { + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + if (!revision || !["review_ready", "complete"].includes(revision.status)) return; + const key = JSON.stringify([takeRunName(node), revision.revision_id, + revision.status, revision.review_unit, revision.updated_utc]); + if (key === node.__h3ContinuumReviewedSettingsKey) return; + node.__h3ContinuumReviewedSettingsKey = key; + node.__h3ContinuumReviewedSettings = requestedSettings ?? reviewSettingsSnapshot(node); +} + +function selectProductionRestart(node) { + clearTakeSelection(node); + setExistingWidgetValue(findWidget(node, REVIEW_ACTION_WIDGET), REVIEW_ACTION_CONTINUE); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); + node.__h3ContinuumRestartSelected = true; + setRegenerateProgrammatically(node, "Chunk 1"); + delete node[REVIEW_UI_SELECTION]; + node.__h3ContinuumProductionUxRefresh?.(); +} + +function reviewReady(node) { + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + // Completion ends continuation, not the user's ability to inspect/retry a Take. + // Keep the backend status authoritative; never rewrite complete to review_ready. + if (revision?.status === "complete") return true; + if (revision?.status === "review_ready" && takeReadOnly(revision)) return true; + return revision?.status === "review_ready" && reviewHasUnit(node); +} + +function reviewHasUnit(node) { + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + if (revision && takeReadOnly(revision)) return false; + const unit = revision?.review_unit; + return [unit?.physical_group, unit?.start, unit?.end].every( + (value) => Number.isInteger(Number(value)) && Number(value) > 0, + ) && Number(unit.end) >= Number(unit.start) + && Number(unit.physical_group) === Number(unit.start); +} + +function reviewStatus(node) { + const pending = activeReviewPrompt(node); + if (pending) return "Queued / generating\nWaiting for this Run's saved result."; + if (node.__h3ContinuumOutputFailure?.runName === takeRunName(node)) { + return "Chunk saved — output incomplete\n" + node.__h3ContinuumOutputFailure.message; + } + if (node.__h3ContinuumQueueNotice) return "Check saved progress\n" + node.__h3ContinuumQueueNotice; + if (node.__h3ContinuumTakeError) { + return `Review status unavailable: ${node.__h3ContinuumTakeError}`; + } + const from = findWidget(node, REGENERATE_WIDGET)?.value; + if (from && from !== "Auto" && from !== 0) { + return `Regenerate from ${from}\nPress Queue directly. Saved Takes are kept.`; + } + if (reviewSettingsChanged(node)) { + return "Settings changed — previous review is out of date\nQueue current settings, or start again from Chunk 1. Saved Takes are kept."; + } + const project = node.__h3ContinuumTakeProject; + if (!project) return "Queue the workflow to create the first chunk."; + const revision = canonicalStorageRevision(project); + if (!revision) return "Queue the workflow to create the first chunk."; + if (takeReadOnly(revision)) { + return takeReadOnlyExplanation(revision); + } + if (revision.status === "complete") { + const unit = revision.review_unit; + const label = reviewHasUnit(node) + ? (Number(unit.end) > Number(unit.start) + ? `Chunks ${unit.start}-${unit.end}` : `Chunk ${unit.start}`) + : ""; + if (label && node[REVIEW_UI_SELECTION] === REVIEW_ACTION_REGENERATE) { + return `Saved sequence is complete\nSelected: retry ${label}. Press Run to generate a new Take.`; + } + return "Saved sequence is complete\n" + (label + ? `Retry ${label}, or open history/settings below.` + : "Open history/settings below to extend or regenerate."); + } + if (reviewReady(node)) { + const group = revision.review_unit; + const label = Number(group.end) > Number(group.start) + ? `Chunks ${group.start}-${group.end}` + : `Chunk ${group.physical_group}`; + const selected = node[REVIEW_UI_SELECTION]; + const selectedLabel = selected === REVIEW_ACTION_CONTINUE + ? PRODUCTION_CONTINUE_WIDGET + : selected === REVIEW_ACTION_REGENERATE + ? PRODUCTION_REGENERATE_WIDGET + : selected === REVIEW_ACTION_FINISH + ? PRODUCTION_FINISH_WIDGET + : null; + if (selectedLabel) { + return `${label} is ready for review\nSelected: ${selectedLabel}. Press Queue to run this action.`; + } + return `${label} is ready for review\nChoose what happens next, then press Queue.`; + } + if (revision.status === "interrupted") { + return "The last run was interrupted. Queue to resume safely."; + } + return "Generation is in progress. Review actions will appear when the chunk is ready."; +} + +function selectProductionReviewAction(node, action) { + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + if (revision && takeReadOnly(revision)) return; + if (activeReviewPrompt(node) || node.__h3ContinuumOutputFailure) return; + const from = findWidget(node, REGENERATE_WIDGET)?.value; + if (reviewSettingsChanged(node) || (from && from !== "Auto" && from !== 0)) { + node.__h3ContinuumProductionUxRefresh?.(); + return; + } + setExistingWidgetValue(findWidget(node, RUN_STORAGE_WIDGET), "Save + Auto Resume"); + setExistingWidgetValue(findWidget(node, GENERATION_MODE_WIDGET), GENERATION_MODE_REVIEW); + setReviewSeedControlFixed(node); + setExistingWidgetValue(findWidget(node, REVIEW_ACTION_WIDGET), action); + node[REVIEW_UI_SELECTION] = action; + node.__h3ContinuumProductionUxRefresh?.(); + node.setDirtyCanvas?.(true, true); +} + +function takeRunName(node) { + const explicit = String(findWidget(node, LEGACY_RUN_NAME_WIDGET)?.value || "").trim(); + if (explicit) return explicit; + const projectId = String(findWidget(node, PROJECT_WIDGET)?.value || "").trim().toLowerCase(); + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(projectId)) { + return ""; + } + return `run_${projectId.replaceAll("-", "")}`; +} + +function takeGroup(item) { + const physicalGroup = Number(item?.group?.physical_group || 0); + const start = Number(item?.group?.start || physicalGroup); + const end = Number(item?.group?.end || start); + if (!Number.isInteger(physicalGroup) || physicalGroup < 1) return null; + if (!Number.isInteger(start) || !Number.isInteger(end) || start < 1 || end < start) { + return null; + } + return { physical_group: physicalGroup, start, end }; +} + +const takeCatalogCache = new WeakMap(); + +function takeReadOnly(item) { + return Number(item?.sampling_contract_version) !== 6 || item?.generation_reusable !== true; +} + +const TAKE_REUSE_REASON_HELP = new Map([ + ["KJ/Core preview implementation is outside the audited source profiles", + "Bypass KJ Model Preview Override in a workflow copy, then test a new Run."], + ["KJ preview VAE/Audio VAE or Tiny VAE is outside the supported configuration", + "Disconnect the preview node's optional VAE/Audio VAE and set Tiny VAE to none. Keep the generation VAEs connected."], + ["Core approximate-VAE preview is outside the supported configuration", + "Set Core preview to Auto or Latent2RGB before starting a new Run."], + ["KJ preview runtime code or state could not be verified", + "Check Detailed Report; bypass KJ Model Preview Override in a workflow copy to isolate it."], + ...[ + "MODEL wrapper/patch contract is not completely observable", + "SAMPLER function/options are not completely observable", + "CLIP/Qwen encoder contract is not completely observable", + "Video VAE contract is not completely observable", + "Reference Audio VAE contract is not completely observable", + "Driving Audio VAE contract is not completely observable", + "Saved generation conditions could not be fully verified; see Detailed Report", + ].map((reason) => [reason, ""]), +]); + +function takeReadOnlyExplanation(item) { + if (!takeReadOnly(item)) return ""; + if (Number(item?.sampling_contract_version) === 5) { + return "Sampling v5 history is read-only for v6 generation\nStart a new Run from Chunk 1. Existing Takes are kept."; + } + const verifiedMetadata = Number(item?.sampling_contract_version) === 6 + && item?.generation_reusable === false; + const lines = [verifiedMetadata + ? "Saved Sampling v6 Take is read-only: its generation conditions were not fully verified." + : "Saved Take reuse could not be verified: compatibility metadata is incomplete or unsupported."]; + const reasons = Array.isArray(item?.resume_disabled_reasons) + ? [...new Set(item.resume_disabled_reasons.slice(0, 8).filter( + (reason) => typeof reason === "string" && TAKE_REUSE_REASON_HELP.has(reason), + ))] + : []; + lines.push(...reasons); + const help = [...new Set(reasons.map((reason) => TAKE_REUSE_REASON_HELP.get(reason)).filter(Boolean))]; + if (help.length) { + lines.push(...help, "After correcting the configuration, start a new Run from Chunk 1. Existing Takes are kept."); + } else { + lines.push("Check Detailed Report and the installed/backend version before starting a new Run. Existing Takes are kept."); + } + return lines.join("\n"); +} + +function takeCatalog(node) { + const project = node.__h3ContinuumTakeProject; + if (project && takeCatalogCache.has(project)) return takeCatalogCache.get(project); + const revisions = project?.group_revisions; + if (!Array.isArray(revisions)) return []; + const normalized = revisions + .map((item) => ({ item, group: takeGroup(item) })) + .filter(({ item, group }) => group && String(item?.revision_id || "")); + if (!normalized.length) return []; + + // project.json is an archive for every sampling lineage that has used this + // Run Name. Take actions, however, are deliberately validated by the + // backend against the current canonical lineage only. Never present old + // lineages (or orphaned ancestry) as actionable history. + const normalizedById = new Map(normalized.map( + (entry) => [String(entry.item.revision_id), entry], + )); + const activeIds = Object.values(project?.active_revisions || {}).map(String); + const anchor = normalizedById.get(String(project?.canonical_head_revision_id || "")) + || activeIds.map((revisionId) => normalizedById.get(revisionId)).find(Boolean) + || null; + const canonicalLineage = String(anchor?.item?.lineage_sha256 || ""); + const lineageAware = normalized.some( + ({ item }) => Boolean(String(item?.lineage_sha256 || "")), + ); + if (lineageAware && !canonicalLineage) return []; + const scoped = canonicalLineage + ? normalized.filter( + ({ item }) => String(item?.lineage_sha256 || "") === canonicalLineage || takeReadOnly(item), + ) + : normalized; + const scopedById = new Map(scoped.map( + (entry) => [String(entry.item.revision_id), entry], + )); + const resolvable = ({ item }) => { + const reverse = []; + const seen = new Set(); + let revisionId = String(item.revision_id || ""); + while (revisionId) { + if (seen.has(revisionId)) return false; + seen.add(revisionId); + const entry = scopedById.get(revisionId); + if (!entry) return false; + reverse.push(entry); + revisionId = String(entry.item.parent_revision_id || ""); + } + let expectedStart = 1; + for (const entry of reverse.reverse()) { + if (entry.group.start !== expectedStart) return false; + expectedStart = entry.group.end + 1; + } + return true; + }; + const sorted = scoped + .filter(resolvable) + .sort((left, right) => ( + left.group.physical_group - right.group.physical_group + || String(left.item.revision_order || left.item.revision_id).localeCompare( + String(right.item.revision_order || right.item.revision_id), + ) + )); + const totals = new Map(); + for (const { group } of sorted) { + totals.set(group.physical_group, (totals.get(group.physical_group) || 0) + 1); + } + const positions = new Map(); + const result = sorted.map(({ item, group }) => { + const takeNumber = (positions.get(group.physical_group) || 0) + 1; + positions.set(group.physical_group, takeNumber); + return { + ...item, + group, + take_number: takeNumber, + take_count: totals.get(group.physical_group), + }; + }); + takeCatalogCache.set(project, result); + return result; +} + +function takeCandidates(node) { + const catalog = takeCatalog(node); + const requestedGroup = Number(findWidget(node, TAKE_GROUP_WIDGET)?.value || 0); + const active = node.__h3ContinuumTakeProject?.active_revisions || {}; + const activeGroups = Object.keys(active).map(Number).filter(Number.isInteger); + const group = requestedGroup > 0 + ? requestedGroup + : (activeGroups.length ? Math.max(...activeGroups) : 0); + return catalog.filter((item) => item.group.physical_group === group); +} + +function selectedTake(node) { + const project = node.__h3ContinuumTakeProject; + const catalog = takeCatalog(node); + if (!project || !catalog.length) return null; + const selectedId = String(node.__h3ContinuumBrowseRevision + || findWidget(node, TAKE_REVISION_WIDGET)?.value || ""); + const explicit = catalog.find((item) => item.revision_id === selectedId); + if (explicit) return explicit; + const requestedGroup = Number(findWidget(node, TAKE_GROUP_WIDGET)?.value || 0); + const activeId = requestedGroup > 0 + ? project.active_revisions?.[String(requestedGroup)] + : project.canonical_head_revision_id; + return ( + catalog.find((item) => item.revision_id === activeId) + || catalog.find((item) => item.revision_id === project.canonical_head_revision_id) + || catalog.at(-1) + || null + ); +} + +function shortRevision(value) { + const text = String(value || ""); + return text ? text.slice(0, 12) : "root"; +} + +function physicalGroupLabel(group) { + return group.end > group.start + ? `${group.start}-${group.end} (atomic)` + : String(group.physical_group); +} + +function takeLabel(item) { + return `Group ${physicalGroupLabel(item.group)} / Take ${item.take_number}`; +} + +function groupSetLabel(groups) { + if (!groups.length) return "no groups"; + const ordered = [...groups].sort((left, right) => left.start - right.start); + const allSingle = ordered.every((group) => group.start === group.end); + const contiguous = ordered.every((group, index) => ( + index === 0 || group.start === ordered[index - 1].end + 1 + )); + if (allSingle && contiguous && ordered.length > 1) { + return `Groups ${ordered[0].start}-${ordered.at(-1).end}`; + } + if (ordered.length === 1) return `Group ${physicalGroupLabel(ordered[0])}`; + return `Groups ${ordered.map(physicalGroupLabel).join(", ")}`; +} + +function takeAncestry(project, selected, catalog) { + const byId = new Map(catalog.map((item) => [item.revision_id, item])); + const reverse = []; + const seen = new Set(); + let revisionId = selected?.revision_id || null; + while (revisionId) { + if (seen.has(revisionId) || !byId.has(revisionId)) return []; + seen.add(revisionId); + const item = byId.get(revisionId); + reverse.push(item); + revisionId = item.parent_revision_id || null; + } + const chain = reverse.reverse(); + let expectedStart = 1; + for (const item of chain) { + if (item.group.start !== expectedStart) return []; + expectedStart = item.group.end + 1; + } + return chain; +} + +function continueFromTakeSummary(project, selected, catalog) { + if (takeReadOnly(selected)) { + return "Continue From Here: unavailable\n" + takeReadOnlyExplanation(selected); + } + const chain = takeAncestry(project, selected, catalog); + if (!chain.length) { + return "Continue From Here: unavailable until provenance is validated"; + } + const knownGroups = new Map(); + for (const item of catalog) { + knownGroups.set(item.group.physical_group, item.group); + } + const later = [...knownGroups.values()].filter( + (group) => group.start > selected.group.end, + ); + const regenerate = later.length + ? groupSetLabel(later) + : `groups after ${physicalGroupLabel(selected.group)} (backend-determined)`; + return ( + `Continue From Here: Reuse ${groupSetLabel(chain.map((item) => item.group))}` + + ` | Regenerate ${regenerate}` + ); +} + +function takeStatus(node) { + const project = node.__h3ContinuumTakeProject; + if (!project) return "No Render History yet"; + if ( + Number(project.run_storage_schema_version) === 2 + && Number(project.branch_provenance_version) !== 1 + ) { + return ( + "Legacy Run Storage v2 detected\n" + + "History is read-only until the next normal Queue reconstructs " + + "Branch Provenance non-destructively." + ); + } + const catalog = takeCatalog(node); + const selected = selectedTake(node); + if (!selected) return "No completed Takes in this Run Storage"; + const activeId = project.active_revisions?.[String(selected.group.physical_group)]; + const canonical = catalog.find((item) => item.revision_id === activeId) || null; + const canonicalHead = catalog.find( + (item) => item.revision_id === project.canonical_head_revision_id, + ) || null; + const action = findWidget(node, TAKE_ACTION_WIDGET)?.value || TAKE_ACTION_AUTOMATIC; + const rawCount = Array.isArray(project.group_revisions) + ? project.group_revisions.length + : 0; + const hiddenCount = Math.max(0, rawCount - catalog.length); + const lines = [ + `Selected: ${takeLabel(selected)} | ${shortRevision(selected.revision_id)}`, + canonical + ? `Canonical: ${takeLabel(canonical)} | ${shortRevision(canonical.revision_id)}` + : "Canonical: unavailable", + canonicalHead + ? `Canonical head: ${takeLabel(canonicalHead)} | ${shortRevision(canonicalHead.revision_id)}` + : "Canonical head: unavailable", + `Compatible history: ${catalog.filter(item => !takeReadOnly(item)).length} Takes`, + continueFromTakeSummary(project, selected, catalog), + ]; + if (hiddenCount) { + lines.push( + `${hiddenCount} incompatible or incomplete Take${hiddenCount === 1 ? "" : "s"} hidden`, + ); + } + if (findWidget(node, RUN_STORAGE_WIDGET)?.value === "Off") { + lines.push("Run Storage: Off (history view only; a Take action enables storage)"); + } + if (action !== TAKE_ACTION_AUTOMATIC) { + const targetId = String(findWidget(node, TAKE_REVISION_WIDGET)?.value || ""); + const target = catalog.find(item => item.revision_id === targetId); + lines.push(`Next Queue: ${action} — ${target ? takeLabel(target) : "selection unavailable"}`); + lines.push("Browsing does not change the queued selection. Press an action to apply a different Take."); + } + return lines.join("\n"); +} + +function selectTakeOffset(node, offset) { + const catalog = takeCatalog(node); + if (!catalog.length) return; + const current = selectedTake(node); + const currentIndex = Math.max(0, catalog.findIndex(item => item.revision_id === current?.revision_id)); + const index = (currentIndex + offset + catalog.length) % catalog.length; + node.__h3ContinuumBrowseRevision = catalog[index].revision_id; + node.__h3ContinuumProductionUxRefresh?.(); + node.setDirtyCanvas?.(true, true); +} + +function selectTakeAction(node, action) { + const selected = selectedTake(node); + if (!selected || takeReadOnly(selected) || reviewSettingsChanged(node) || activeReviewPrompt(node)) return; + delete node.__h3ContinuumModeSetup; + setExistingWidgetValue( + findWidget(node, TAKE_GROUP_WIDGET), + Number(selected.group.physical_group), + ); + setExistingWidgetValue( + findWidget(node, TAKE_REVISION_WIDGET), + String(selected.revision_id), + ); + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, RUN_STORAGE_WIDGET), "Save + Auto Resume"); + setExistingWidgetValue(findWidget(node, GENERATION_MODE_WIDGET), GENERATION_MODE_REVIEW); + setReviewSeedControlFixed(node); + setExistingWidgetValue(findWidget(node, REVIEW_ACTION_WIDGET), REVIEW_ACTION_CONTINUE); + setExistingWidgetValue(findWidget(node, TAKE_ACTION_WIDGET), action); + node.__h3ContinuumProductionUxRefresh?.(); + node.setDirtyCanvas?.(true, true); +} + +function clearTakeSelection(node) { + setExistingWidgetValue(findWidget(node, TAKE_GROUP_WIDGET), 0); + setExistingWidgetValue(findWidget(node, TAKE_REVISION_WIDGET), ""); + setExistingWidgetValue(findWidget(node, TAKE_ACTION_WIDGET), TAKE_ACTION_AUTOMATIC); +} + +async function loadTakeHistory(node, options = {}) { + // Creation precedes saved widget/link restoration. Never bind a Run or + // settings baseline to that intermediate graph. + if (reviewGraphHydrating || node.__h3ContinuumConfigurePending) return false; + if (!reviewNodeAttached(node)) return false; + const runName = takeRunName(node); + const epoch = reviewGraphEpoch; + node.__h3ContinuumTakeInitialLoad = true; + const requestedSettings = options.reviewedSettings ?? node.__h3ContinuumReadReviewSettings?.(); + const identityChanged = node.__h3ContinuumHistoryRun !== runName; + if (identityChanged) { + node.__h3ContinuumHistoryRun = runName; + node.__h3ContinuumTakeProject = null; + delete node.__h3ContinuumBrowseRevision; + delete node.__h3ContinuumOutputFailure; + delete node.__h3ContinuumQueueNotice; + delete node.__h3ContinuumReviewedSettings; + delete node.__h3ContinuumReviewedSettingsKey; + // The first read must not rewrite a saved explicit Take selection. + if (node.__h3ContinuumHistoryRunInitialized) clearTakeSelection(node); + node.__h3ContinuumHistoryRunInitialized = true; + } + if (!options.force && node.__h3ContinuumHistoryRequest?.runName === runName) { + return node.__h3ContinuumHistoryRequest.promise; + } + const token = Number(node.__h3ContinuumTakeLoadToken || 0) + 1; + node.__h3ContinuumTakeLoadToken = token; + const current = () => epoch === reviewGraphEpoch && !reviewGraphHydrating + && reviewNodeAttached(node) + && node.__h3ContinuumTakeLoadToken === token && takeRunName(node) === runName; + if (!runName) { + node.__h3ContinuumTakeProject = null; + delete node.__h3ContinuumTakeError; + node.__h3ContinuumProductionUxRefresh?.(); + return false; + } + const promise = (async () => { + try { + const subfolder = `h3_continuum/runs/${runName}`; + const response = await api.fetchApi( + `/view?filename=project.json&type=output&subfolder=${encodeURIComponent(subfolder)}`, + { cache: "no-store" }, + ); + if (!current()) return false; + if (response.status === 404) { + node.__h3ContinuumTakeProject = null; + delete node.__h3ContinuumTakeError; + return true; + } + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const project = await response.json(); + if (!current()) return false; + if (project?.run_name && project.run_name !== runName) { + throw new Error("Run Storage identity does not match this request"); + } + const legacy = Number(project?.run_storage_schema_version) === 2 + && Number(project?.branch_provenance_version) !== 1; + if (!legacy && Number(project?.branch_provenance_version) !== 1) { + throw new Error("Branch Provenance v1 is unavailable"); + } + node.__h3ContinuumTakeProject = project; + node.__h3ContinuumRememberReviewSettings?.(requestedSettings); + repairStaleReviewRegenerate(node, project); + delete node.__h3ContinuumTakeError; + return true; + } catch (error) { + if (!current()) return false; + node.__h3ContinuumTakeProject = null; + node.__h3ContinuumTakeError = String(error?.message || error); + return false; + } finally { + if (current()) { + node.__h3ContinuumIntuitiveUxRefresh?.(); + node.__h3ContinuumProductionUxRefresh?.(); + } + } + })(); + node.__h3ContinuumHistoryRequest = { runName, token, promise }; + try { return await promise; } + finally { + if (node.__h3ContinuumHistoryRequest?.token === token) { + delete node.__h3ContinuumHistoryRequest; + if (current()) node.__h3ContinuumIntuitiveUxRefresh?.(); + } + } +} + +// One immutable record per accepted prompt/node/run. Never correlate via +// Sampler `executed`: that event exists only for nodes returning UI output. +const reviewPrompts = new Map(); +const reviewEarlyTerminals = new Map(); +let reviewSubmissionCount = 0; +let reviewQueueSequence = 0; + +function reviewRevisionKey(project) { + const r = canonicalStorageRevision(project); + return r ? JSON.stringify([r.revision_id, r.status, r.review_unit, r.updated_utc]) : ""; +} + +function reviewPromptRunName(inputs) { + const explicit = String(inputs?.run_name || "").trim(); + if (explicit) return explicit; + const id = String(inputs?.project_id || "").trim().toLowerCase(); + return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id) + ? `run_${id.replaceAll("-", "")}` : ""; +} + +function reviewPromptIncludes(output, nodeId, options) { + const targets = options?.partialExecutionTargets; + if (!Array.isArray(targets) || !targets.length) return true; + const seen = new Set(); + const visit = (id) => { + id = String(id); + if (seen.has(id)) return; + seen.add(id); + for (const value of Object.values(output[id]?.inputs || {})) { + if (Array.isArray(value) && value.length === 2 && output[String(value[0])]) visit(value[0]); + } + }; + targets.forEach(visit); + return seen.has(String(nodeId)); +} + +function activeReviewPrompt(node) { + for (const records of reviewPrompts.values()) { + const item = !records.terminalEvent && records.find(r => r.node === node && r.runName === takeRunName(node)); + if (item) return item; + } + return null; +} + +async function refreshV38TakeHistoryAfterExecution(event) { + const promptId = String(event?.detail?.prompt_id || ""); + if (!promptId) return; + const records = reviewPrompts.get(promptId); + if (!records) { + // A very fast execution may finish before the HTTP response. Buffer only + // while a submission is in flight; unrelated prompts never affect nodes. + if (reviewSubmissionCount && reviewEarlyTerminals.size < 64) { + reviewEarlyTerminals.set(promptId, event); + } + return; + } + records.terminalEvent = event; + if (records.processing) return records.processing; + records.processing = (async () => { + const pending = []; + for (const record of records) { + const node = record.node; + if (takeRunName(node) !== record.runName || String(node.id) !== record.nodeId + || !(app.graph?._nodes || []).includes(node) + || record.sequence < Number(node.__h3ContinuumAppliedPromptSequence || 0)) continue; + const ok = await loadTakeHistory(node, {force: true, reviewedSettings: record.settings}); + if (!ok) { + if (takeRunName(node) === record.runName) pending.push(record); + continue; + } + if (takeRunName(node) !== record.runName + || record.sequence < Number(node.__h3ContinuumAppliedPromptSequence || 0)) continue; + const project = node.__h3ContinuumTakeProject; + const revision = canonicalStorageRevision(project); + // Converted input widgets can submit a graph link rather than a literal + // count. In that case the backend, not the browser, resolves its value. + const requestedCount = !Array.isArray(record.intent.chunks) + ? Number(record.intent.chunks) : NaN; + const literalCount = Number.isInteger(requestedCount) && requestedCount > 0; + const saved = revision && ["complete", "review_ready"].includes(revision.status) + && (revision.status === "complete" || reviewHasUnit(node)) + && (!revision.review_unit || (reviewHasUnit(node) + && (!literalCount || Number(revision.review_unit.end) <= requestedCount))); + const changed = reviewRevisionKey(project) !== record.baseline; + const success = event.type === "execution_success"; + const unchangedReview = success && !changed && revision?.status === "review_ready" + && record.intent[GENERATION_MODE_WIDGET] === GENERATION_MODE_REVIEW + && record.intent[TAKE_ACTION_WIDGET] !== TAKE_ACTION_USE; + if (unchangedReview) { + node.__h3ContinuumQueueNotice = "No new saved chunk was found for this Queue. Reload progress before continuing."; + } else if (saved && (success || changed)) { + delete node.__h3ContinuumQueueNotice; + if (record.intent[REGENERATE_WIDGET] === "Auto" || record.intent[REGENERATE_WIDGET] === 0) { + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); + } + // Only this setup selection can be released. A later mode selection + // or an edit to another Run is not owned by this execution. + if (record.setup === node.__h3ContinuumModeSetup) delete node.__h3ContinuumModeSetup; + node.__h3ContinuumReviewedSettings = record.settings; + node.__h3ContinuumAppliedPromptSequence = record.sequence; + if (success) delete node.__h3ContinuumOutputFailure; + else node.__h3ContinuumOutputFailure = { + promptId, runName: record.runName, + revisionId: revision.revision_id, + message: "Chunk saved; preview/output did not finish. Retry saved output without sampling a new Take.", + }; + } + node.__h3ContinuumIntuitiveUxRefresh?.(); + node.__h3ContinuumProductionUxRefresh?.(); + } + if (reviewPrompts.get(promptId) === records) { + if (pending.length) { + pending.terminalEvent = event; + reviewPrompts.set(promptId, pending); + } else reviewPrompts.delete(promptId); + } + })(); + try { return await records.processing; } finally { delete records.processing; } +} + +function installReviewQueueAdapter() { + if (api.__h3ContinuumReviewQueueAdapter || typeof api.queuePrompt !== "function") return; + const previous = api.queuePrompt; + api.queuePrompt = async function(number, data, options, ...rest) { + const output = { ...(data?.output || {}) }; + const records = []; + for (const [nodeId, item] of Object.entries(output)) { + if (!isModernSamplerClass(item?.class_type) || !reviewPromptIncludes(output, nodeId, options)) continue; + const node = app.graph?.getNodeById?.(nodeId) + || app.graph?._nodes?.find(n => String(n.id) === nodeId); + if (!node || !isModernSamplerClass(node.comfyClass)) continue; + requireFixedSeedForReview(node); + const normalizedInputs = { ...(item.inputs || {}) }; + normalizeRunStorageState(node, normalizedInputs); + const inputs = buildReviewQueueInputs(node, normalizedInputs); + output[nodeId] = { ...item, inputs }; + records.push({ node, nodeId, runName: reviewPromptRunName(inputs), + settings: reviewSettingsSnapshot(node), setup: node.__h3ContinuumModeSetup, + baseline: reviewRevisionKey(node.__h3ContinuumTakeProject), + intent: Object.freeze({ ...inputs }), sequence: ++reviewQueueSequence }); + } + if (!records.length) return previous.call(this, number, data, options, ...rest); + reviewSubmissionCount++; + try { + const response = await previous.call(this, number, {...data, output}, options, ...rest); + const promptId = String(response?.prompt_id || ""); + if (!promptId) return response; + reviewPrompts.set(promptId, records); + for (const r of records) { + delete r.node.__h3ContinuumQueueNotice; + // Capture is per-prompt, never one mutable "last queue" slot. + r.node[REVIEW_PENDING_ACTION] = r.intent[REVIEW_ACTION_WIDGET]; + r.node[TAKE_PENDING_ACTION] = r.intent[TAKE_ACTION_WIDGET]; + if (r.node.__h3ContinuumRestartSelected && r.intent[REGENERATE_WIDGET] === "Chunk 1") { + r.node.__h3ContinuumRestartQueued = true; + } + r.node.__h3ContinuumProductionUxRefresh?.(); + } + const early = reviewEarlyTerminals.get(promptId); + reviewEarlyTerminals.delete(promptId); + if (early) await refreshV38TakeHistoryAfterExecution(early); + return response; + } finally { + reviewSubmissionCount--; + if (!reviewSubmissionCount) reviewEarlyTerminals.clear(); + } + }; + api.__h3ContinuumReviewQueueAdapter = true; +} + +let reviewSyncPromise = null; + +async function synchronizeReviewQueue({discover = false} = {}) { + if (reviewSyncPromise) return reviewSyncPromise; + reviewSyncPromise = (async () => { + let queue; + try { + const response = await api.fetchApi("/queue", {cache: "no-store"}); + if (!response.ok) return; + queue = await response.json(); + } catch { return; } // A connection error is not cancellation or completion. + const queued = [...(queue.queue_running || []), ...(queue.queue_pending || [])]; + const present = new Set(queued.map(item => String(item[1]))); + if (discover) { + for (const item of queued) { + const promptId = String(item[1] || ""); + const output = item[2] || {}; + if (!promptId || reviewPrompts.has(promptId)) continue; + const records = []; + for (const node of app.graph?._nodes || []) { + const nodeId = String(node.id); + const submitted = output[nodeId]; + if (!isModernSamplerClass(node.comfyClass) || submitted?.class_type !== node.comfyClass + || !reviewPromptIncludes(output, nodeId, {partialExecutionTargets: item[4]}) + || reviewPromptRunName(submitted.inputs) !== takeRunName(node)) continue; + records.push({node, nodeId, runName: takeRunName(node), + settings: reviewSettingsSnapshot(node), setup: node.__h3ContinuumModeSetup, + baseline: reviewRevisionKey(node.__h3ContinuumTakeProject), + intent: Object.freeze({...submitted.inputs}), sequence: ++reviewQueueSequence}); + } + if (records.length) reviewPrompts.set(promptId, records); + } + } + for (const [promptId, records] of [...reviewPrompts]) { + if (records.terminalEvent) { + await refreshV38TakeHistoryAfterExecution(records.terminalEvent); + continue; + } + if (present.has(promptId)) continue; + try { + const response = await api.fetchApi(`/history/${encodeURIComponent(promptId)}`, {cache:"no-store"}); + if (!response.ok) continue; + const history = (await response.json())?.[promptId]; + if (history) { + const messages = history.status?.messages || []; + const terminal = [...messages].reverse().find(item => [ + "execution_success", "execution_error", "execution_interrupted", + ].includes(item[0])); + if (terminal) await refreshV38TakeHistoryAfterExecution({type:terminal[0], detail:{prompt_id:promptId}}); + } else if (!reviewSubmissionCount) { + // No running/pending entry and no history: cancelled before + // execution. No invented commit and no automatic resampling. + reviewPrompts.delete(promptId); + for (const record of records) { + if (takeRunName(record.node) !== record.runName) continue; + record.node.__h3ContinuumQueueNotice = "Queued prompt is no longer pending. Refresh saved progress before continuing."; + record.node.__h3ContinuumIntuitiveUxRefresh?.(); + record.node.__h3ContinuumProductionUxRefresh?.(); + } + } + } catch { /* Keep ownership until the server can be read again. */ } + } + })(); + try { return await reviewSyncPromise; } finally { reviewSyncPromise = null; } +} + +async function reloadReviewHistory() { + for (const node of app.graph?._nodes || []) { + if (isModernSamplerClass(node.comfyClass)) await loadTakeHistory(node, {force: true}); + } + await synchronizeReviewQueue({discover: true}); +} + +function reconcileReviewQueueStatus(event) { + const remaining = event?.detail?.exec_info?.queue_remaining; + if (remaining === 0 && reviewPrompts.size && !reviewSubmissionCount) { + // Read the server queue/history rather than inferring completion from + // a zero queue count. This also handles dropped terminal messages. + return synchronizeReviewQueue(); + } +} + +function retrySavedReviewOutput(node) { + const project = node.__h3ContinuumTakeProject; + const head = takeCatalog(node).find(r => r.revision_id === project?.canonical_head_revision_id); + if (!head || reviewSettingsChanged(node) || activeReviewPrompt(node)) return; + node.__h3ContinuumBrowseRevision = head.revision_id; + selectTakeAction(node, TAKE_ACTION_USE); +} + +function attachTakeHistoryReload(node) { + for (const [name, key] of ( + [ + [RUN_STORAGE_WIDGET, "__h3ContinuumTakeStorageReload"], + [LEGACY_RUN_NAME_WIDGET, "__h3ContinuumTakeRunNameReload"], + [PROJECT_WIDGET, "__h3ContinuumTakeProjectReload"], + ] + )) { + const widget = findWidget(node, name); + if (!widget || widget[key]) continue; + const previous = widget.callback; + widget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + void loadTakeHistory(node); + return result; + }; + widget[key] = true; + } +} + +function configureProductionReviewUx(node) { + if (!isModernSamplerClass(node.comfyClass) || typeof node.addWidget !== "function") return; + let statusWidget = transientProductionWidgets(node).find( + (widget) => widget.name === PRODUCTION_STATUS_WIDGET, + ); + if (!statusWidget) { + statusWidget = addFacadeInfoWidget( + node, + PRODUCTION_STATUS_WIDGET, + "review", + 68, + false, + ); + if (statusWidget) { + statusWidget.disabled = true; + setWidgetTooltip(statusWidget, ( + "Review and completion come from the saved backend revision. " + + "After completion, retry the last reviewed unit or open Render History. " + + "To extend, use Back to Settings, increase Chunks, then press Run. " + + "The backend checks whether saved chunks can be reused." + )); + } + const buttons = ( + [ + [PRODUCTION_CONTINUE_WIDGET, REVIEW_ACTION_CONTINUE], + [PRODUCTION_REGENERATE_WIDGET, REVIEW_ACTION_REGENERATE], + [PRODUCTION_FINISH_WIDGET, REVIEW_ACTION_FINISH], + ] + ); + for (const [name, action] of buttons) { + const widget = addTransientProductionWidget( + node, + "button", + name, + null, + () => selectProductionReviewAction(node, action), + ); + if (widget) { + setWidgetTooltip(widget, ( + name === PRODUCTION_CONTINUE_WIDGET + ? "Keep the reviewed chunk and generate the next chunk after normal Queue." + : name === PRODUCTION_REGENERATE_WIDGET + ? "Create another Take for the reviewed chunk after normal Queue." + : "Keep the reviewed chunk and finish all remaining chunks after normal Queue." + )); + } + } + const retryOutput = addTransientProductionWidget(node, "button", PRODUCTION_OUTPUT_RETRY_WIDGET, + null, () => retrySavedReviewOutput(node)); + setWidgetTooltip(retryOutput, "Reuse the saved canonical Take and retry decoding/saving. No new Sampling. Then press Queue."); + const backToSettings = addTransientProductionWidget( + node, + "button", + PRODUCTION_BACK_TO_SETTINGS_WIDGET, + null, + () => { + node.__h3ContinuumReviewSettingsOpen = true; + node.__h3ContinuumIntuitiveUxRefresh?.(); + node.__h3ContinuumProductionUxRefresh?.(); + }, + ); + if (backToSettings) { + setWidgetTooltip(backToSettings, ( + "Show the normal Continuum settings without changing the pending review, " + + "selected action, Take, or canonical branch." + )); + } + const returnToReview = addTransientProductionWidget( + node, + "button", + PRODUCTION_RETURN_TO_REVIEW_WIDGET, + null, + () => { + delete node.__h3ContinuumModeSetup; + node.__h3ContinuumReviewSettingsOpen = false; + node.__h3ContinuumIntuitiveUxRefresh?.(); + node.__h3ContinuumProductionUxRefresh?.(); + }, + ); + if (returnToReview) { + setWidgetTooltip(returnToReview, ( + "Return to the pending chunk review without changing any settings or Take state." + )); + } + const restart = addTransientProductionWidget( + node, "button", PRODUCTION_RESTART_WIDGET, null, + () => selectProductionRestart(node), + ); + if (restart) setWidgetTooltip(restart, ( + "Select a new branch from Chunk 1 using the current settings and automatic " + + "Take variation. Press Queue afterward. Saved Takes are not deleted; " + + "the restart selection is consumed once after Queue." + )); + const historyToggle = addTransientProductionWidget( + node, + "button", + TAKE_TOGGLE_WIDGET, + null, + () => { + node.__h3ContinuumHistoryOpen = !node.__h3ContinuumHistoryOpen; + node.__h3ContinuumProductionUxRefresh?.(); + }, + ); + if (historyToggle) { + setWidgetTooltip(historyToggle, "Open the stored Take list only when you need it."); + } + const takeStatusWidget = typeof node.addCustomWidget === "function" + ? node.addCustomWidget({ + type: "h3_continuum_take_history", + name: TAKE_STATUS_WIDGET, + value: "No Render History yet", + serialize: false, + options: { serialize: false }, + [PRODUCTION_TRANSIENT_WIDGET]: true, + draw(ctx, _node, width, y, height) { + const renderHeight = Math.max( + 28, + Number(this.computeSize?.(width)?.[1] || height || 28), + ); + ctx.save(); + ctx.beginPath(); + ctx.rect(15, y + 4, Math.max(1, width - 30), renderHeight - 8); + ctx.clip(); + ctx.fillStyle = "#eeeeee"; + ctx.font = "12px Arial"; + ctx.textAlign = "left"; + ctx.textBaseline = "top"; + const lines = String(this.value || "").split("\n"); + const count = Math.max(1, Math.floor((renderHeight - 12) / 16)); + for (let i = 0; i < Math.min(lines.length, count); i++) { + ctx.fillText(lines[i], 18, y + 6 + i * 16, Math.max(1, width - 36)); + } + ctx.restore(); + }, + }) + : addTransientProductionWidget( + node, + "text", + TAKE_STATUS_WIDGET, + "No Render History yet", + null, + { multiline: true }, + ); + if (takeStatusWidget) { + takeStatusWidget.disabled = true; + takeStatusWidget.computeSize = () => { + const lines = String(takeStatusWidget.value || "").split("\n").length; + return [ + Math.max(300, Number(node.size?.[0] || 0)), + Math.min(124, Math.max(44, 12 + lines * 16)), + ]; + }; + setWidgetTooltip(takeStatusWidget, ( + "Read-only Branch Provenance from Run Storage. Selecting a Take does not " + + "change the canonical branch until Use This Take is queued normally." + )); + } + for (const [name, callback] of ( + [ + [TAKE_PREVIOUS_WIDGET, () => selectTakeOffset(node, -1)], + [TAKE_NEXT_WIDGET, () => selectTakeOffset(node, 1)], + [TAKE_USE_WIDGET, () => selectTakeAction(node, TAKE_ACTION_USE)], + [TAKE_CONTINUE_WIDGET, () => selectTakeAction(node, TAKE_ACTION_CONTINUE)], + ] + )) { + const widget = addTransientProductionWidget(node, "button", name, null, callback); + if (widget) { + setWidgetTooltip( + widget, + name === TAKE_PREVIOUS_WIDGET || name === TAKE_NEXT_WIDGET + ? "Walk through stored physical-group Takes without changing the canonical branch." + : "Uses immutable physical-group revision provenance; Queue normally after selecting an action.", + ); + } + } + installProductionSerializationGuard(node); + + } + const refresh = () => { + const reviewing = ( + findWidget(node, GENERATION_MODE_WIDGET)?.value === GENERATION_MODE_REVIEW + ); + const storageEnabled = ( + findWidget(node, RUN_STORAGE_WIDGET)?.value === "Save + Auto Resume" + ); + const historyOpen = storageEnabled && Boolean(node.__h3ContinuumHistoryOpen); + const ready = reviewing && storageEnabled && reviewReady(node); + const complete = canonicalStorageRevision(node.__h3ContinuumTakeProject)?.status === "complete"; + const readyRevisionId = ready + ? String(canonicalStorageRevision(node.__h3ContinuumTakeProject)?.revision_id || "") + : ""; + if (readyRevisionId && readyRevisionId !== node.__h3ContinuumReviewSettingsRevision) { + node.__h3ContinuumReviewSettingsRevision = readyRevisionId; + node.__h3ContinuumReviewSettingsOpen = false; + } else if (!ready) { + node.__h3ContinuumReviewSettingsOpen = false; + } + const modeSetup = Boolean(node.__h3ContinuumModeSetup); + const settingsOpen = ready && !modeSetup && Boolean(node.__h3ContinuumReviewSettingsOpen); + const reviewOpen = ready && !modeSetup && !settingsOpen; + const from = findWidget(node, REGENERATE_WIDGET)?.value; + const edited = reviewSettingsChanged(node); + const outputFailure = node.__h3ContinuumOutputFailure?.runName === takeRunName(node); + const busy = Boolean(activeReviewPrompt(node)); + const canReview = !takeReadOnly(canonicalStorageRevision(node.__h3ContinuumTakeProject)) + && !edited && !busy && !outputFailure && (!from || from === "Auto" || from === 0); + const takeCount = takeCatalog(node).length; + const actionNames = new Set([ + PRODUCTION_STATUS_WIDGET, + PRODUCTION_CONTINUE_WIDGET, + PRODUCTION_REGENERATE_WIDGET, + PRODUCTION_FINISH_WIDGET, + ]); + const historyNames = new Set([ + TAKE_STATUS_WIDGET, + TAKE_PREVIOUS_WIDGET, + TAKE_NEXT_WIDGET, + TAKE_USE_WIDGET, + TAKE_CONTINUE_WIDGET, + ]); + for (const widget of transientProductionWidgets(node)) { + if (widget[FACADE_TRANSIENT_WIDGET]) continue; + if (widget.name === PRODUCTION_STATUS_WIDGET) { + setWidgetVisible(widget, reviewOpen); + } else if (widget.name === PRODUCTION_OUTPUT_RETRY_WIDGET) { + setWidgetVisible(widget, reviewOpen && outputFailure); + widget.disabled = edited || busy; + } else if (widget.name === PRODUCTION_REGENERATE_WIDGET) { + setWidgetVisible(widget, reviewOpen && canReview && reviewHasUnit(node)); + } else if ( + widget.name === PRODUCTION_CONTINUE_WIDGET + || widget.name === PRODUCTION_FINISH_WIDGET + ) { + setWidgetVisible(widget, reviewOpen && canReview && !complete); + } else if (actionNames.has(widget.name)) { + setWidgetVisible(widget, reviewOpen); + } else if (widget.name === PRODUCTION_BACK_TO_SETTINGS_WIDGET) { + setWidgetVisible(widget, reviewOpen); + } else if (widget.name === PRODUCTION_RETURN_TO_REVIEW_WIDGET) { + setWidgetVisible(widget, settingsOpen || (ready && modeSetup)); + } else if (widget.name === PRODUCTION_RESTART_WIDGET) { + setWidgetVisible(widget, ready && !busy); + } else if (widget.name === TAKE_TOGGLE_WIDGET) { + setWidgetVisible(widget, reviewOpen && takeCount > 0); + } else if (historyNames.has(widget.name)) { + setWidgetVisible(widget, reviewOpen && historyOpen && takeCount > 0); + } + } + if (statusWidget) { + const [headline, detail = ""] = reviewStatus(node).split("\n", 2); + statusWidget.headline = headline; + statusWidget.detail = detail; + statusWidget.value = detail ? `${headline}\n${detail}` : headline; + statusWidget.__h3ContinuumInfoVariant = "review"; + } + const takeStatusWidget = transientProductionWidgets(node).find( + (widget) => widget.name === TAKE_STATUS_WIDGET, + ); + if (takeStatusWidget) { + takeStatusWidget.value = node.__h3ContinuumTakeError + ? `Render History unavailable: ${node.__h3ContinuumTakeError}` + : takeStatus(node); + } + const catalog = takeCatalog(node); + const hasSelection = Boolean(selectedTake(node)); + const takeActionAvailable = hasSelection && !takeReadOnly(selectedTake(node)) && !edited && !busy; + const historyToggle = transientProductionWidgets(node).find( + (widget) => widget.name === TAKE_TOGGLE_WIDGET, + ); + if (historyToggle) { + const count = catalog.length; + historyToggle.label = historyOpen + ? "Close Render History" + : `Render History — ${count} Take${count === 1 ? "" : "s"}`; + } + const selectedAction = node[REVIEW_UI_SELECTION]; + for (const [name, action] of ( + [ + [PRODUCTION_CONTINUE_WIDGET, REVIEW_ACTION_CONTINUE], + [PRODUCTION_REGENERATE_WIDGET, REVIEW_ACTION_REGENERATE], + [PRODUCTION_FINISH_WIDGET, REVIEW_ACTION_FINISH], + ] + )) { + const widget = transientProductionWidgets(node).find((item) => item.name === name); + if (widget) widget.label = selectedAction === action ? `✓ ${name}` : name; + } + for (const name of [TAKE_PREVIOUS_WIDGET, TAKE_NEXT_WIDGET]) { + const widget = transientProductionWidgets(node).find((item) => item.name === name); + if (widget) widget.disabled = catalog.length < 2; + } + for (const name of [TAKE_USE_WIDGET, TAKE_CONTINUE_WIDGET]) { + const widget = transientProductionWidgets(node).find((item) => item.name === name); + if (widget) widget.disabled = !takeActionAvailable; + } + if (reviewOpen) { + for (const widget of facadeProductionWidgets(node)) { + if ( + widget.name !== FACADE_ADVANCED_WIDGET + && widget.name !== FACADE_REFERENCE_SIZE_WIDGET + && widget.name !== FACADE_VIDEO_SIZE_WIDGET + ) { + setWidgetVisible(widget, false); + } + } + moveNamedWidgetsToFront( + node, + [ + PRODUCTION_STATUS_WIDGET, + PRODUCTION_OUTPUT_RETRY_WIDGET, + PRODUCTION_CONTINUE_WIDGET, + PRODUCTION_REGENERATE_WIDGET, + PRODUCTION_FINISH_WIDGET, + PRODUCTION_BACK_TO_SETTINGS_WIDGET, + PRODUCTION_RESTART_WIDGET, + TAKE_TOGGLE_WIDGET, + TAKE_STATUS_WIDGET, + TAKE_PREVIOUS_WIDGET, + TAKE_NEXT_WIDGET, + TAKE_USE_WIDGET, + TAKE_CONTINUE_WIDGET, + FACADE_ADVANCED_WIDGET, + FACADE_REFERENCE_SIZE_WIDGET, + FACADE_VIDEO_SIZE_WIDGET, + ], + ); + } else if (settingsOpen && Array.isArray(node.__h3ContinuumFacadeOrder)) { + const readyFacade = facadeProductionWidgets(node).find( + (widget) => widget.name === FACADE_READY_WIDGET, + ); + if (readyFacade) { + const [headline, detail = ""] = reviewStatus(node).split("\n", 2); + readyFacade.headline = headline; + readyFacade.detail = detail; + readyFacade.value = detail ? `${headline}\n${detail}` : headline; + readyFacade.__h3ContinuumInfoVariant = "review"; + } + const settingsOrder = [...node.__h3ContinuumFacadeOrder]; + const readyIndex = settingsOrder.indexOf(FACADE_READY_WIDGET); + settingsOrder.splice( + readyIndex >= 0 ? readyIndex + 1 : settingsOrder.length, + 0, + PRODUCTION_RETURN_TO_REVIEW_WIDGET, + PRODUCTION_RESTART_WIDGET, + ); + moveNamedWidgetsToFront(node, settingsOrder); + } else if (Array.isArray(node.__h3ContinuumFacadeOrder)) { + if (ready && modeSetup) { + const order = [...node.__h3ContinuumFacadeOrder]; + const at = order.indexOf(FACADE_READY_WIDGET); + order.splice(at < 0 ? order.length : at + 1, 0, + PRODUCTION_RETURN_TO_REVIEW_WIDGET, PRODUCTION_RESTART_WIDGET); + moveNamedWidgetsToFront(node, order); + } else moveFacadeWidgetsToFront(node, node.__h3ContinuumFacadeOrder); + } + // Connected duration controls stay directly below the normal inputs, + // including while the settings facade is replaced by Review/History. + const connectedDuration = []; + for (const [source, facade] of [[CHUNKS_WIDGET, FACADE_CHUNKS_WIDGET], ["chunk_seconds", FACADE_SECONDS_WIDGET]]) { + if (!linkedInput(node, [source])) continue; + setWidgetVisible(findWidget(node, facade), true); + connectedDuration.push(facade); + } + if (connectedDuration.length) moveNamedWidgetsToFront(node, connectedDuration); + node._widgetSlotsDirty = true; + node.setDirtyCanvas?.(true, true); + }; + node.__h3ContinuumProductionUxRefresh = refresh; + if (!node.__h3ContinuumReviewRemovalGuard) { + const previous = node.onRemoved; + node.onRemoved = function(...args) { + this.__h3ContinuumConfigurePending?.cancel(); + this.__h3ContinuumTakeLoadToken = Number(this.__h3ContinuumTakeLoadToken || 0) + 1; + for (const [id, records] of reviewPrompts) { + const remaining = records.filter(record => record.node !== this); + if (remaining.length) reviewPrompts.set(id, remaining); + else reviewPrompts.delete(id); + } + return previous?.apply(this, args); + }; + node.__h3ContinuumReviewRemovalGuard = true; + } + node.__h3ContinuumReviewSettingsChanged = () => reviewSettingsChanged(node); + node.__h3ContinuumRememberReviewSettings = (requested) => rememberReviewSettings(node, requested); + node.__h3ContinuumReadReviewSettings = () => reviewSettingsSnapshot(node); + // Upstream prompt/media edits also invalidate review, not just local widgets. + if (!node.__h3ContinuumReviewDrawWatch) { + const previous = node.onDrawForeground; + node.onDrawForeground = function(...args) { + const result = previous?.apply(this, args); + const changed = reviewSettingsChanged(this); + if (changed !== this.__h3ContinuumReviewDrawChanged) { + this.__h3ContinuumReviewDrawChanged = changed; + this.__h3ContinuumIntuitiveUxRefresh?.(); + this.__h3ContinuumProductionUxRefresh?.(); + } + return result; + }; + node.__h3ContinuumReviewDrawWatch = true; + } + for (const [name, key] of ( + [ + [RUN_STORAGE_WIDGET, "__h3ContinuumProductionStorageRefresh"], + [REGENERATE_WIDGET, "__h3ContinuumProductionRegenerateRefresh"], + [REROLL_NONCE_WIDGET, "__h3ContinuumProductionNonceRefresh"], + [GENERATION_MODE_WIDGET, "__h3ContinuumProductionModeRefresh"], + [REVIEW_ACTION_WIDGET, "__h3ContinuumProductionActionRefresh"], + [TAKE_GROUP_WIDGET, "__h3ContinuumTakeGroupRefresh"], + [TAKE_REVISION_WIDGET, "__h3ContinuumTakeRevisionRefresh"], + [TAKE_ACTION_WIDGET, "__h3ContinuumTakeActionRefresh"], + ] + )) { + attachRefresh(findWidget(node, name), key, refresh); + } + attachTakeHistoryReload(node); + for (const widget of node.widgets || []) { + if (!widget[PRODUCTION_TRANSIENT_WIDGET] && !widget[FACADE_TRANSIENT_WIDGET]) { + attachRefresh(widget, "__h3ContinuumReviewEditRefresh", refresh); + } + } + refresh(); +} + +function configureV39ReferenceUx(node) { + if (node.comfyClass !== V39_NODE_CLASS) return; + let planWidget = transientProductionWidgets(node).find( + (widget) => widget.name === V39_PLAN_WIDGET, + ); + if (!planWidget) { + const value = V39_UNVERIFIED_PLAN; + planWidget = typeof node.addCustomWidget === "function" + ? node.addCustomWidget({ + type: "h3_continuum_reference_plan", + name: V39_PLAN_WIDGET, + value, + serialize: false, + options: { serialize: false }, + [PRODUCTION_TRANSIENT_WIDGET]: true, + computeSize(width) { + const count = String(this.value || "").split("\n").length; + return [width, Math.min(220, Math.max(48, 14 + count * 16))]; + }, + draw(ctx, _node, width, y, height) { + ctx.save(); + ctx.beginPath(); + ctx.rect(15, y + 4, Math.max(1, width - 30), Math.max(1, height - 8)); + ctx.clip(); + ctx.fillStyle = "#e7f4e9"; + ctx.font = "12px Arial"; + ctx.textAlign = "left"; + ctx.textBaseline = "top"; + const lines = String(this.value || "").split("\n"); + const count = Math.max(1, Math.floor((height - 12) / 16)); + for (let index = 0; index < Math.min(lines.length, count); index += 1) { + ctx.fillText(lines[index], 18, y + 6 + index * 16, Math.max(1, width - 36)); + } + ctx.restore(); + }, + }) + : addTransientProductionWidget( + node, "text", V39_PLAN_WIDGET, value, null, { multiline: true }, + ); + if (planWidget) { + planWidget.disabled = true; + setWidgetTooltip(planWidget, ( + "Read-only. Before Queue this is only configured intent. After Queue the " + + "backend reports actual physical groups, reused/generated status, " + + "R1-R9 to Picture mapping, contract hashes, and warnings." + )); + } + installProductionSerializationGuard(node); + } + const routeKey = () => reviewSettingsSnapshot(node); + const refresh = () => { + const key = routeKey(); + if (node.__h3ContinuumReferenceRouteKey !== key) { + node.__h3ContinuumReferenceRouteKey = key; + node.__h3ContinuumReferencePlan = null; + } + const legacyConnections = connectedV39LegacyReferenceInputs(node); + const reviewOpen = reviewReady(node) + && !node.__h3ContinuumReviewSettingsOpen + && !node.__h3ContinuumModeSetup; + if (planWidget) { + planWidget.value = legacyConnections.length + ? `Old Reference connection(s) ${legacyConnections.join(", ")} are not used by V3.9. Reconnect them through H3 Continuum Reference Images V3.9.` + : node.__h3ContinuumReferencePlan || V39_UNVERIFIED_PLAN; + setWidgetVisible(planWidget, !reviewOpen || legacyConnections.length > 0); + } + node.setDirtyCanvas?.(true, true); + }; + if (!node.__h3ContinuumV39ReferenceUxInstalled) { + const previousRefresh = node.__h3ContinuumIntuitiveUxRefresh; + node.__h3ContinuumIntuitiveUxRefresh = () => { + previousRefresh?.(); + refresh(); + }; + attachRefresh(findWidget(node, "chunks"), "__h3ContinuumV39ChunksRefresh", () => { + refreshV39ReferenceImagesForSampler(node); + refresh(); + }); + const previousExecuted = node.onExecuted; + node.onExecuted = function(message, ...args) { + const result = previousExecuted?.call(this, message, ...args); + const text = message?.h3_reference_plan?.[0]; + if (typeof text === "string") { + this.__h3ContinuumReferencePlan = text; + refresh(); + } + return result; + }; + const previousConnectionsChange = node.onConnectionsChange; + node.onConnectionsChange = function(...args) { + const result = previousConnectionsChange?.apply(this, args); + this.__h3ContinuumReferencePlan = null; + refreshV39ReferenceImagesForSampler(this); + refresh(); + return result; + }; + node.__h3ContinuumV39ReferenceUxInstalled = true; + } + refresh(); +} + +function normalizedV38View(node) { + return node.__h3ContinuumAdvancedOpen ? V38_VIEW_PRODUCTION : V38_VIEW_BASIC; +} + +function applyV38View(node) { + if (!isModernSamplerClass(node.comfyClass)) return; + node.__h3ContinuumIntuitiveUxRefresh?.(); + node.__h3ContinuumProductionUxRefresh?.(); + if (!reviewGraphHydrating && !node.__h3ContinuumConfigurePending + && reviewNodeAttached(node) && !node.__h3ContinuumTakeInitialLoad) { + void loadTakeHistory(node); + } + node.setDirtyCanvas?.(true, true); +} + +function configureV38ViewProperty(node) { + if (!isModernSamplerClass(node.comfyClass)) return V38_VIEW_BASIC; + node.properties ||= {}; + if (!node.__h3ContinuumLegacyViewMigrated) { + node.__h3ContinuumAdvancedOpen = ( + node.properties[V38_VIEW_PROPERTY] === V38_VIEW_PRODUCTION + ); + delete node.properties[V38_VIEW_PROPERTY]; + node.__h3ContinuumLegacyViewMigrated = true; + } + return normalizedV38View(node); +} + +function normalizeRunStorageState(node, apiInputs = null) { + const storageWidget = findWidget(node, RUN_STORAGE_WIDGET); + const storageEnabled = storageWidget?.value === "Save + Auto Resume"; + if (storageEnabled) { + return true; + } + const nonceWidget = findWidget(node, REROLL_NONCE_WIDGET); + setRegenerateProgrammatically(node, "Auto"); + if (nonceWidget) nonceWidget.value = 0; + if (apiInputs) { + apiInputs[REGENERATE_WIDGET] = "Auto"; + apiInputs[REROLL_NONCE_WIDGET] = 0; + } + return false; +} + +function configureConditionalWidgets(node) { + const storageWidget = findWidget(node, RUN_STORAGE_WIDGET); + const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + const nonceWidget = findWidget(node, REROLL_NONCE_WIDGET); + const runNameWidget = findWidget(node, LEGACY_RUN_NAME_WIDGET); + if (regenerateWidget && !regenerateWidget.__h3ContinuumManualIntentCallback) { + const previous = regenerateWidget.callback; + regenerateWidget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + if (!node.__h3ContinuumProgrammaticRegenerate) { + if (value === "Auto" || value === 0 || value == null) { + delete node.__h3ContinuumManualRegenerateIntent; + if (node.properties) delete node.properties[REGENERATE_INTENT_PROPERTY]; + } else { + node.__h3ContinuumManualRegenerateIntent = true; + if (isModernSamplerClass(node.comfyClass)) { + node.properties ||= {}; + node.properties[REGENERATE_INTENT_PROPERTY] = value; + } + } + } + return result; + }; + regenerateWidget.__h3ContinuumManualIntentCallback = true; + } + const refresh = () => { + removeUnusedLegacyInputs(node); + const productionView = true; + const storageEnabled = isModernSamplerClass(node.comfyClass) + ? storageWidget?.value === "Save + Auto Resume" + : normalizeRunStorageState(node); + const explicitRegeneration = storageEnabled + && regenerateWidget?.value !== "Auto" + && Number.parseInt(String(regenerateWidget?.value).replace(/^Chunk\s+/, ""), 10) > 0; + setWidgetVisible(regenerateWidget, storageEnabled && productionView); + setWidgetVisible(runNameWidget, storageEnabled && productionView); + setWidgetVisible(nonceWidget, explicitRegeneration && productionView); + setWidgetVisible( + findWidget(node, REFERENCE_SIZE_WIDGET), + productionView + && activeLinkedInput(node, node.comfyClass === V39_NODE_CLASS + ? ["reference_images"] + : ["reference_image_1", "reference_image_2", "reference_image_3", "reference_image_4", "reference_image_5", "image_references"]), + ); + setWidgetVisible( + findWidget(node, TIMELINE_SIZE_WIDGET), + linkedInput(node, ["timeline_video"]), + ); + setWidgetVisible( + findWidget(node, VIDEO_REFERENCE_SIZE_WIDGET), + productionView && linkedInput(node, ["reference_video_1"]), + ); + node.setDirtyCanvas?.(true, true); + }; + attachRefresh(storageWidget, "__h3ContinuumStorageCallback", refresh); + attachRefresh(regenerateWidget, "__h3ContinuumRegenerateVisibilityCallback", refresh); + if (!node.__h3ContinuumConnectionCallback) { + const previous = node.onConnectionsChange; + node.onConnectionsChange = function(...args) { + const result = previous?.apply(this, args); + setTimeout(refresh, 0); + return result; + }; + node.__h3ContinuumConnectionCallback = true; + } + refresh(); +} + +function configureResolutionPresetWidgets(node) { + if (!isModernSamplerClass(node.comfyClass)) { + return; + } + const aspectWidget = findWidget(node, LEGACY_ASPECT_WIDGET); + const sizeSourceWidget = findWidget(node, SIZE_SOURCE_WIDGET); + const widthWidget = findWidget(node, WIDTH_WIDGET); + const heightWidget = findWidget(node, HEIGHT_WIDGET); + const presetWidget = findWidget(node, RESOLUTION_PRESET_WIDGET); + const customMpWidget = findWidget(node, CUSTOM_MP_WIDGET); + if (!sizeSourceWidget || !widthWidget || !heightWidget) return; + + const roundCanvas = (value) => Math.max( + CANVAS_MULTIPLE, + Math.floor(Number(value) / CANVAS_MULTIPLE + 0.5) * CANVAS_MULTIPLE, + ); + const presetSize = (aspectRatio) => { + const preset = presetWidget?.value; + if (preset === RESOLUTION_PRESET_NATIVE) { + const landscape = aspectRatio >= 1; + const majorRatio = landscape ? aspectRatio : 1 / aspectRatio; + let shortEdge = NATIVE_SHORT_EDGE; + let longEdge = shortEdge * majorRatio; + if (longEdge > NATIVE_LONG_EDGE_CAP) { + longEdge = NATIVE_LONG_EDGE_CAP; + shortEdge = longEdge / majorRatio; + } + const longPx = Math.min(NATIVE_LONG_EDGE_CAP, roundCanvas(longEdge)); + const shortPx = Math.min(NATIVE_SHORT_EDGE, roundCanvas(shortEdge)); + return landscape ? [longPx, shortPx] : [shortPx, longPx]; + } + const megapixels = preset === RESOLUTION_PRESET_DRAFT + ? 0.30 + : preset === RESOLUTION_PRESET_BALANCED + ? 0.60 + : Number(customMpWidget?.value || 0.30); + const targetPixels = megapixels * 1_000_000; + return [ + roundCanvas(Math.sqrt(targetPixels * aspectRatio)), + roundCanvas(Math.sqrt(targetPixels / aspectRatio)), + ]; + }; + const firstImageGeometry = () => { + const input = node.inputs?.find((item) => item.name === "first_frame"); + if (input?.link == null) return null; + const link = app.graph?.links?.[input.link]; + const source = app.graph?.getNodeById?.(link?.origin_id); + if (!source || Number(source.mode) === 4) return null; + const image = source.imgs?.[0]; + const width = Number(image?.naturalWidth || image?.width || 0); + const height = Number(image?.naturalHeight || image?.height || 0); + return width > 0 && height > 0 ? { width, height } : null; + }; + const migrateLegacyAspect = () => { + if (sizeSourceWidget.value !== SIZE_SOURCE_LEGACY) return; + const legacy = String(aspectWidget?.value || "Auto from First Image"); + if (legacy === "Auto from First Image") { + sizeSourceWidget.value = SIZE_SOURCE_FIRST_IMAGE; + return; + } + const ratio = legacy === "Portrait 9:16" + ? 9 / 16 + : legacy === "Square 1:1" + ? 1 + : 16 / 9; + const [width, height] = presetSize(ratio); + if (!linkedInput(node, [WIDTH_WIDGET])) widthWidget.value = width; + if (!linkedInput(node, [HEIGHT_WIDGET])) heightWidget.value = height; + sizeSourceWidget.value = SIZE_SOURCE_MANUAL; + }; + migrateLegacyAspect(); + sizeSourceWidget.options ||= {}; + sizeSourceWidget.options.values = [SIZE_SOURCE_FIRST_IMAGE, SIZE_SOURCE_MANUAL]; + hidePersistentWidget(aspectWidget); + + const refresh = () => { + migrateLegacyAspect(); + const firstImage = sizeSourceWidget.value === SIZE_SOURCE_FIRST_IMAGE; + const geometry = firstImage ? firstImageGeometry() : null; + if (geometry) { + const [width, height] = presetSize( + geometry.width / geometry.height, + ); + if (!linkedInput(node, [WIDTH_WIDGET])) widthWidget.value = width; + if (!linkedInput(node, [HEIGHT_WIDGET])) heightWidget.value = height; + } + widthWidget.disabled = firstImage || linkedInput(node, [WIDTH_WIDGET]); + heightWidget.disabled = firstImage || linkedInput(node, [HEIGHT_WIDGET]); + presetWidget.disabled = !firstImage; + widthWidget.tooltip = firstImage + ? "Resolved from First Image at Queue time. The displayed value updates when exact frontend image geometry is available." + : "Manual output width. Must be aligned to 32 pixels."; + heightWidget.tooltip = firstImage + ? "Resolved from First Image at Queue time. The displayed value updates when exact frontend image geometry is available." + : "Manual output height. Must be aligned to 32 pixels."; + setWidgetVisible( + customMpWidget, + firstImage && presetWidget?.value === CUSTOM_RESOLUTION_PRESET, + ); + node.setDirtyCanvas?.(true, true); + }; + attachRefresh(sizeSourceWidget, "__h3ContinuumSizeSourceCallback", refresh); + attachRefresh(presetWidget, "__h3ContinuumResolutionPresetCallback", refresh); + attachRefresh(customMpWidget, "__h3ContinuumCustomMpCallback", refresh); + attachRefresh(widthWidget, "__h3ContinuumWidthCallback", refresh); + attachRefresh(heightWidget, "__h3ContinuumHeightCallback", refresh); + if (!node.__h3ContinuumResolutionConnectionCallback) { + const previous = node.onConnectionsChange; + node.onConnectionsChange = function(...args) { + const result = previous?.apply(this, args); + setTimeout(refresh, 0); + return result; + }; + node.__h3ContinuumResolutionConnectionCallback = true; + } + if (!node.__h3ContinuumResolutionConfigureGuard) { + const originalConfigure = node.configure; + const sizeSourceIndex = node.widgets?.indexOf(sizeSourceWidget) ?? -1; + if (typeof originalConfigure === "function" && sizeSourceIndex >= 0) { + node.configure = function(info, ...args) { + const values = Array.isArray(info?.widgets_values) + ? info.widgets_values + : []; + const hasExplicitSizeSource = values.length > sizeSourceIndex; + const result = originalConfigure.call(this, info, ...args); + if (!hasExplicitSizeSource) { + sizeSourceWidget.value = SIZE_SOURCE_LEGACY; + migrateLegacyAspect(); + } + refresh(); + return result; + }; + } + node.__h3ContinuumResolutionConfigureGuard = true; + } + node.__h3ContinuumResolutionUxRefresh = refresh; + refresh(); +} + +function isOneShotReviewAction(value) { + return value === REVIEW_ACTION_REGENERATE || value === REVIEW_ACTION_FINISH; +} + +function normalizeReviewActionOnLoad(node) { + if (!isModernSamplerClass(node.comfyClass)) { + return false; + } + delete node.__h3ContinuumManualRegenerateIntent; + delete node[REVIEW_PENDING_ACTION]; + delete node[REVIEW_UI_SELECTION]; + let changed = false; + const actionWidget = findWidget(node, REVIEW_ACTION_WIDGET); + if (actionWidget && isOneShotReviewAction(actionWidget.value)) { + actionWidget.value = REVIEW_ACTION_CONTINUE; + changed = true; + } + const takeActionWidget = findWidget(node, TAKE_ACTION_WIDGET); + if (takeActionWidget && takeActionWidget.value !== TAKE_ACTION_AUTOMATIC) { + takeActionWidget.value = TAKE_ACTION_AUTOMATIC; + changed = true; + } + return changed; +} + +function resetReviewActionAfterQueued(node) { + const pendingAction = node[REVIEW_PENDING_ACTION]; + delete node[REVIEW_PENDING_ACTION]; + delete node[REVIEW_UI_SELECTION]; + if (!isOneShotReviewAction(pendingAction)) { + return false; + } + const actionWidget = findWidget(node, REVIEW_ACTION_WIDGET); + if (!actionWidget || actionWidget.value !== pendingAction) { + return false; + } + actionWidget.value = REVIEW_ACTION_CONTINUE; + actionWidget.callback?.(REVIEW_ACTION_CONTINUE); + node.setDirtyCanvas?.(true, true); + return true; +} + +function resetTakeActionAfterQueued(node) { + const pendingAction = node[TAKE_PENDING_ACTION]; + delete node[TAKE_PENDING_ACTION]; + if (pendingAction !== TAKE_ACTION_USE && pendingAction !== TAKE_ACTION_CONTINUE) { + return false; + } + const actionWidget = findWidget(node, TAKE_ACTION_WIDGET); + if (!actionWidget || actionWidget.value !== pendingAction) return false; + actionWidget.value = TAKE_ACTION_AUTOMATIC; + actionWidget.callback?.(TAKE_ACTION_AUTOMATIC); + node.setDirtyCanvas?.(true, true); + return true; +} + +function buildReviewQueueInputs(node, apiInputs) { + const result = { ...apiInputs }; + const value = (name, fallback) => result[name] ?? findWidget(node, name)?.value ?? fallback; + const mode = value(GENERATION_MODE_WIDGET, GENERATION_MODE_FULL_RUN); + const storage = value(RUN_STORAGE_WIDGET, "Off"); + const setup = Boolean(node.__h3ContinuumModeSetup); + const stale = reviewSettingsChanged(node); + let from = value(REGENERATE_WIDGET, "Auto"); + let nonce = value(REROLL_NONCE_WIDGET, 0); + + // A Run mode change is never a hidden restart. Repair only an unowned + // stale Chunk 1 boundary; explicit Advanced regeneration stays explicit. + if ( + setup + && from === "Chunk 1" + && Number(nonce) === 0 + && !hasManualRegenerateIntent(node) + && !node.__h3ContinuumRestartSelected + ) { + from = "Auto"; + nonce = 0; + } + // Backend rejects regeneration without Run Storage. Normalize the impossible + // combination before submission and keep the visible controls consistent. + if (storage !== "Save + Auto Resume") { + from = "Auto"; + nonce = 0; + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); + } + result[REGENERATE_WIDGET] = from; + result[REROLL_NONCE_WIDGET] = nonce; + const manual = from && from !== "Auto" && from !== 0; + result[GENERATION_MODE_WIDGET] = mode; + result[REVIEW_ACTION_WIDGET] = mode === GENERATION_MODE_FULL_RUN || manual || setup || stale + ? REVIEW_ACTION_CONTINUE : value(REVIEW_ACTION_WIDGET, REVIEW_ACTION_CONTINUE); + for (const [name, fallback] of [[TAKE_GROUP_WIDGET, 0], [TAKE_REVISION_WIDGET, ""], + [TAKE_ACTION_WIDGET, TAKE_ACTION_AUTOMATIC]]) { + result[name] = setup || stale ? fallback : value(name, fallback); + } + return result; +} + +function configureReviewControls(node) { + if (!isModernSamplerClass(node.comfyClass)) { + return; + } + const generationWidget = findWidget(node, GENERATION_MODE_WIDGET); + const actionWidget = findWidget(node, REVIEW_ACTION_WIDGET); + const storageWidget = findWidget(node, RUN_STORAGE_WIDGET); + const takeActionWidget = findWidget(node, TAKE_ACTION_WIDGET); + if (!generationWidget || !actionWidget) { + return; + } + const refresh = () => { + setWidgetVisible( + actionWidget, + generationWidget.value === GENERATION_MODE_REVIEW, + ); + node.setDirtyCanvas?.(true, true); + }; + if (!generationWidget.__h3ContinuumReviewModeCallback) { + const previous = generationWidget.callback; + generationWidget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + if ( + value === GENERATION_MODE_REVIEW + && storageWidget?.value === "Off" + ) { + storageWidget.value = "Save + Auto Resume"; + storageWidget.callback?.("Save + Auto Resume"); + } + if (value === GENERATION_MODE_REVIEW) { + setReviewSeedControlFixed(node); + } + refresh(); + return result; + }; + generationWidget.__h3ContinuumReviewModeCallback = true; + } + if (generationWidget.value === GENERATION_MODE_REVIEW) { + setReviewSeedControlFixed(node); + } + if (!actionWidget.__h3ContinuumReviewAfterQueued) { + const previous = actionWidget.afterQueued; + actionWidget.afterQueued = function(...args) { + const result = previous?.apply(this, args); + resetReviewActionAfterQueued(node); + resetTakeActionAfterQueued(node); + if (node.__h3ContinuumRestartQueued) { + delete node.__h3ContinuumRestartQueued; + delete node.__h3ContinuumRestartSelected; + const from = findWidget(node, REGENERATE_WIDGET); + if (from?.value === "Chunk 1") { + setRegenerateProgrammatically(node, "Auto"); + } + } + return result; + }; + actionWidget.__h3ContinuumReviewAfterQueued = true; + } + if (takeActionWidget && !takeActionWidget.__h3ContinuumTakeAfterQueued) { + const previous = takeActionWidget.afterQueued; + takeActionWidget.afterQueued = function(...args) { + const result = previous?.apply(this, args); + resetTakeActionAfterQueued(node); + return result; + }; + takeActionWidget.__h3ContinuumTakeAfterQueued = true; + } + refresh(); +} + +function configureAssembler(node) { + if ( + node.comfyClass !== ASSEMBLE_SEAM_NODE_CLASS + && node.comfyClass !== V34_ASSEMBLE_SEAM_NODE_CLASS + && node.comfyClass !== V35_ASSEMBLE_SEAM_NODE_CLASS + ) { + return false; + } + const exactDuration = findWidget(node, "exact_total_duration"); + if (exactDuration) exactDuration.value = true; + applyRuntimeSettings(node); + hidePersistentWidget(exactDuration); + hidePersistentWidget(findWidget(node, "diagnostics")); + node.setDirtyCanvas?.(true, true); + return true; +} + +function configureNode(node) { + const isProduction = node.comfyClass === PRODUCTION_NODE_CLASS; + const isTimeline = node.comfyClass === TIMELINE_NODE_CLASS; + const isV34 = node.comfyClass === V34_NODE_CLASS; + const isV35 = node.comfyClass === V35_NODE_CLASS; + const isV36 = node.comfyClass === V36_NODE_CLASS; + const isV37 = node.comfyClass === V37_NODE_CLASS; + const isV38 = isModernSamplerClass(node.comfyClass); + if (node.comfyClass === V39_NODE_CLASS) pruneV39LegacyReferenceInputs(node); + if (!isProduction && !isTimeline && !isV34 && !isV35 && !isV36 && !isV37 && !isV38) { + configureV39ReferenceImages(node); + if (node.comfyClass === "H3ContinuumReferenceAudios") { + normalizeReferenceAudioLabels(node); + } + configureAssembler(node); + return null; + } + const projectWidget = findWidget(node, PROJECT_WIDGET); + if (isProduction || isV34 || isV35 || isV36 || isV37 || isV38) { + if (projectWidget && !String(projectWidget.value || "").trim()) { + projectWidget.value = createProjectId(); + } + if (!isV38) removeUnusedInput(node, PROMPT_OVERRIDES_INPUT); + } + applyRuntimeSettings(node); + if (isV35 || isV36 || isV37 || isV38) { + normalizeReferenceAudioLabels(node); + } + removeUnusedLegacyInputs(node); + hidePersistentWidget(findWidget(node, "diagnostics")); + hidePersistentWidget(findWidget(node, "strict_compatibility")); + hidePersistentWidget(findWidget(node, "debug")); + hidePersistentWidget(findWidget(node, "show_preview")); + hidePersistentWidget(projectWidget); + hidePersistentWidget(findWidget(node, TAKE_GROUP_WIDGET)); + hidePersistentWidget(findWidget(node, TAKE_REVISION_WIDGET)); + hidePersistentWidget(findWidget(node, TAKE_ACTION_WIDGET)); + configureV38ViewProperty(node); + configureRegenerateFrom(node); + configureConditionalWidgets(node); + configureResolutionPresetWidgets(node); + configureReviewControls(node); + configureIntuitiveV38Ux(node); + configureProductionReviewUx(node); + configureV39ReferenceUx(node); + applyV38View(node); + node.setDirtyCanvas?.(true, true); + return projectWidget; +} + +let reviewGraphEpoch = 0; +let reviewGraphHydrating = false; + +function reviewNodeAttached(node) { + const graph = node.graph || app.graph; + return Boolean(graph && (graph.getNodeById?.(node.id) === node + || graph._nodes?.includes(node))); +} + +function configureNodeAfterSetup(node) { + // Coalesce the existing deferred setup passes and expose their completion. + // No extra guessed delay: history waits for the actual final setup pass. + let pending = node.__h3ContinuumConfigurePending; + if (pending?.epoch !== reviewGraphEpoch) { + pending?.cancel(); + const epoch = reviewGraphEpoch; + let finish; + pending = { epoch, timers: [], promise: new Promise(resolve => { finish = resolve; }) }; + pending.cancel = () => { + for (const timer of pending.timers) clearTimeout(timer); + if (node.__h3ContinuumConfigurePending === pending) delete node.__h3ContinuumConfigurePending; + finish(); + }; + node.__h3ContinuumConfigurePending = pending; + for (const delay of [0, 100]) { + pending.timers.push(setTimeout(() => { + try { + if (epoch === reviewGraphEpoch && reviewNodeAttached(node)) configureNode(node); + } finally { + if (delay === 100) { + pending.cancel(); + if (epoch === reviewGraphEpoch && reviewNodeAttached(node)) applyV38View(node); + } + } + }, delay)); + } + } + configureNode(node); + return pending.promise; +} + +app.registerExtension({ + name: "H3Continuum.ProjectId", + + setup() { + installReviewQueueAdapter(); + api.addEventListener("reconnected", reloadReviewHistory); + api.addEventListener("status", reconcileReviewQueueStatus); + for (const eventName of [ + "execution_success", + "execution_error", + "execution_interrupted", + ]) { + api.addEventListener( + eventName, + refreshV38TakeHistoryAfterExecution, + ); + } + const settings = app.ui?.settings; + settings?.addSetting?.({ + id: SETTINGS.samplingPreview, + name: "H3 Continuum: Sampling Preview", + type: "boolean", + defaultValue: true, + tooltip: "Show live sampling previews. Disable only to reduce preview overhead.", + onChange: () => refreshConfiguredNodes(), + }); + settings?.addSetting?.({ + id: SETTINGS.developerDiagnostics, + name: "H3 Continuum: Developer Diagnostics", + type: "boolean", + defaultValue: false, + tooltip: "Enable developer-only Continuum logging and assertions.", + onChange: () => refreshConfiguredNodes(), + }); + settings?.addSetting?.({ + id: SETTINGS.detailedReport, + name: "H3 Continuum: Detailed Report", + type: "boolean", + defaultValue: false, + tooltip: "Include detailed diagnostics in status and assembly reports.", + onChange: () => refreshConfiguredNodes(), + }); + }, + + beforeConfigureGraph() { + reviewGraphEpoch++; + reviewGraphHydrating = true; + for (const node of app.graph?._nodes || []) node.__h3ContinuumConfigurePending?.cancel(); + }, + + onGraphLoadError() { + reviewGraphEpoch++; + reviewGraphHydrating = false; + for (const node of app.graph?._nodes || []) node.__h3ContinuumConfigurePending?.cancel(); + }, + + nodeCreated(node) { + configureNodeAfterSetup(node); + }, + + loadedGraphNode(node) { + if (node.comfyClass === V39_NODE_CLASS) { + node.__h3ContinuumReferencePlan = null; + } + normalizeReviewActionOnLoad(node); + configureNodeAfterSetup(node); + }, + + async afterConfigureGraph() { + // API graph loading can call this hook without beforeConfigureGraph. + const epoch = reviewGraphEpoch; + reviewGraphHydrating = true; + const nodes = [...(app.graph?._nodes || [])]; + const pending = []; + for (const node of nodes) { + migrateReferenceImageInputs(node); + pending.push(configureNodeAfterSetup(node)); + } + await Promise.all(pending); + if (epoch !== reviewGraphEpoch) return; + reviewGraphHydrating = false; + for (const node of nodes) { + if (!isModernSamplerClass(node.comfyClass) || !reviewNodeAttached(node)) continue; + void loadTakeHistory(node, { force: true, reviewedSettings: reviewSettingsSnapshot(node) }); + } + }, + + async beforeQueuePrompt(prompt) { + const seen = new Set(); + for (const node of app.graph?._nodes || []) { + const projectWidget = configureNode(node); + const apiNode = prompt.output?.[String(node.id)]; + if (node.comfyClass === V39_NODE_CLASS && apiNode?.inputs) { + node.__h3ContinuumReferencePlan = null; + configureV39ReferenceUx(node); + } + if (apiNode?.inputs) { + if ( + node.comfyClass === PRODUCTION_NODE_CLASS + || node.comfyClass === TIMELINE_NODE_CLASS + || node.comfyClass === V34_NODE_CLASS + || node.comfyClass === V35_NODE_CLASS + || node.comfyClass === V36_NODE_CLASS + || node.comfyClass === V37_NODE_CLASS + || isModernSamplerClass(node.comfyClass) + ) { + node.__h3ContinuumResolutionUxRefresh?.(); + if (!isModernSamplerClass(node.comfyClass)) { + normalizeRunStorageState(node, apiNode.inputs); + } + apiNode.inputs.diagnostics = settingValue(SETTINGS.detailedReport, false) + ? "Detailed Report" + : "Basic"; + apiNode.inputs.debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); + apiNode.inputs.show_preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); + apiNode.inputs.strict_compatibility = false; + } else if ( + node.comfyClass === ASSEMBLE_SEAM_NODE_CLASS + || node.comfyClass === V34_ASSEMBLE_SEAM_NODE_CLASS + || node.comfyClass === V35_ASSEMBLE_SEAM_NODE_CLASS + ) { + apiNode.inputs.diagnostics = settingValue(SETTINGS.detailedReport, false) + ? "Detailed Report" + : "Basic"; + apiNode.inputs.exact_total_duration = true; + } + } + if (!projectWidget) { + continue; + } + let projectId = String(projectWidget.value || "").trim(); + if (!projectId || seen.has(projectId)) { + projectId = createProjectId(); + projectWidget.value = projectId; + } + seen.add(projectId); + if (apiNode?.inputs) { + apiNode.inputs.project_id = projectId; + } + } + }, +}); + +function refreshConfiguredNodes() { + for (const node of app.graph?._nodes || []) { + configureNodeAfterSetup(node); + } +} diff --git a/js/vendor/dumas_h3_continuum/reference_audio_ui.js b/js/vendor/dumas_h3_continuum/reference_audio_ui.js new file mode 100644 index 0000000..ace250e --- /dev/null +++ b/js/vendor/dumas_h3_continuum/reference_audio_ui.js @@ -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; +} diff --git a/js/vendor/dumas_h3_continuum/reference_image_ui.js b/js/vendor/dumas_h3_continuum/reference_image_ui.js new file mode 100644 index 0000000..88e8708 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/reference_image_ui.js @@ -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); +} diff --git a/js/vendor/dumas_h3_continuum/reference_images_v39.js b/js/vendor/dumas_h3_continuum/reference_images_v39.js new file mode 100644 index 0000000..f8d8668 --- /dev/null +++ b/js/vendor/dumas_h3_continuum/reference_images_v39.js @@ -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); +} diff --git a/js/vendor/dumas_h3_continuum/storage_settings.js b/js/vendor/dumas_h3_continuum/storage_settings.js new file mode 100644 index 0000000..ec4ebee --- /dev/null +++ b/js/vendor/dumas_h3_continuum/storage_settings.js @@ -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, + }); + }, +}); diff --git a/js/vendor/dumas_h3_continuum/video_reference_mode_ui.js b/js/vendor/dumas_h3_continuum/video_reference_mode_ui.js new file mode 100644 index 0000000..641a20b --- /dev/null +++ b/js/vendor/dumas_h3_continuum/video_reference_mode_ui.js @@ -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; + }; + }, +}); diff --git a/js/vendor/dumas_h3_refmod_picker/placeholder.png b/js/vendor/dumas_h3_refmod_picker/placeholder.png new file mode 100755 index 0000000000000000000000000000000000000000..8cec3d6219ce86b5a1bf62d57111603103943ed4 GIT binary patch literal 30069 zcmeFZXIPZYvNrk*ARwTOh#)~pO3p}-I3SV*9C8-Pl5=JTMMM!0$r(f>y?{v0s0fZo z63G%2$zjMtp3~#I_F8*=dw=KrJHHm!g)nq?b$4}jg}bVKs;jMfj)IW_f}nHiYRX6m zA_2dWK;%T=#|EnTI|Q9UI_Vqx7~j#7wsChAw6=A>ZzmYw>H*pzNLC@h!`jB#&WH8B zor9B`96PqDjh)rWR*v0B{EqM)k6U(*PHI73c6veD`Zht%HaBhA733*o1Ec`~S34hT z)&N%*H*e_xIrcwvrNQrnKMS$5{^{c5EXQtqN0;@MyO$lSxS+V8FuObjtE`u;y);r; zgc=&p`{8@;tjgXy-ovWRjk2mNq@^Ag^0-XLY~MyN|oKqr1mHXZg1! z{j>Rh3ACO1m60A9(F=VJ8ySi zFB`ktet;bue>g|rqqMrKwS%3OotuM?qa3@4u;`8dqshq0_J6hzh`IO@PS3#22~02g zuR+HDYLjD^6crNrSCh&A+C*Ttw60Ttor|%u6F4hxK=r?^u0f#3I z#yZ&tDqH)2UZTRH5(2`K0;1yj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eg044G7I$W#X8zvG5P>3%Vy+1RR4l zJUpDA$Wd;Y4Ryp20fMDSOBcQ>h61_Cuy2jiCbn1zg_OMPH}{`x0>Bq?bfqTTocy%91#T~lefb6n?pIQKDX)nJ zz;wXKC~JI>E`cHq->fXZ@-iY$oLfSH`~0z|RzNx@mj5s|t{4T_KHFw?ZB26~wkwaD z3n@+kY0w1038n+#L%f}Qf?2|Ju11=t55aIQ1pLFxaWejkV3iES`p3mSl{qQZ1XKXm zT@F95%U^%HbnG0@=Yl8-t`)jU0Jg1xYOw9x{`K^QiNg-7c$b*GJI3aCqJPb}b!v7^ zg^#8fxa6p;9Z>8$ap{ShLbc7^3z=Sg8f<1KMcKO2@P$vNKte%{H9Js8vvlVV4~SWY zz2$&OgxRm{-;k}mw)CA8yhWY8-avSz;Ywdg&@>32@2sH|3eqW0eg;Q>6j|C#smWo4 z7|<72rB|Q!{zwz#wOA!d2gJ)Y;8s)v_;PV<+euO{;nc>)&0OYGuZRJKwd_x})D9bI z#BEwQzyDe}Nvi0$p1ne?>+$W4ND$n$LE)}cz7B{K1fS*fggRR{sN3qENidYYDlH^s z{PEpd$_%R)cjaPw5w6L3xu7G40tWPGmyD 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"); \ No newline at end of file diff --git a/js/vendor/dumas_h3_refmod_picker/refmod_loader.js b/js/vendor/dumas_h3_refmod_picker/refmod_loader.js new file mode 100644 index 0000000..6c15434 --- /dev/null +++ b/js/vendor/dumas_h3_refmod_picker/refmod_loader.js @@ -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"); \ No newline at end of file diff --git a/js/vendor/dumas_h3_refmod_picker/visual_refmod_picker.js b/js/vendor/dumas_h3_refmod_picker/visual_refmod_picker.js new file mode 100644 index 0000000..4901b98 --- /dev/null +++ b/js/vendor/dumas_h3_refmod_picker/visual_refmod_picker.js @@ -0,0 +1,1230 @@ +import { app } from "../../scripts/app.js"; +import { api } from "../../scripts/api.js"; + +const PLACEHOLDER_IMAGE_PATH = new URL("./placeholder.png", import.meta.url).href; +const DEFAULT_PICKER_NODE_SIZE = [240, 480]; +const MIN_PICKER_NODE_WIDTH = 200; +const PREVIEW_PANEL_OVERLAP_PX = 8; + +function isTypingTarget(target) { + if (!target) return false; + const tag = String(target.tagName || "").toUpperCase(); + return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.isContentEditable; +} + +let _vrpHoveredNode = null; +let _vrpArrowListenerInstalled = false; + +function isVrpNodeInGraph(node) { + if (!node || !app.graph?._nodes) return false; + return app.graph._nodes.includes(node); +} + +function getActiveVisualRefModPickerNode() { + if (_vrpHoveredNode && !_vrpHoveredNode.flags?.collapsed && isVrpNodeInGraph(_vrpHoveredNode)) { + return _vrpHoveredNode; + } + if (_vrpHoveredNode && !isVrpNodeInGraph(_vrpHoveredNode)) { + _vrpHoveredNode = null; + } + return null; +} + +function installVrpArrowNavigation() { + if (_vrpArrowListenerInstalled) return; + _vrpArrowListenerInstalled = true; + + window.addEventListener("keydown", async (event) => { + if (event.defaultPrevented) return; + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return; + if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) return; + if (isTypingTarget(event.target)) return; + + const node = getActiveVisualRefModPickerNode(); + if (!node || typeof node._vrpStepModByDelta !== "function") return; + + const direction = event.key === "ArrowRight" ? 1 : -1; + const handled = await node._vrpStepModByDelta(direction); + if (!handled) return; + event.preventDefault(); + event.stopPropagation(); + }, true); +} + +function hideWidget(widget) { + if (!widget) return; + widget.hidden = true; + widget.computeSize = () => [0, -4]; + if (widget.inputEl) widget.inputEl.style.display = "none"; +} + +function setDynamicWidgetVisible(widget, visible) { + if (!widget) return; + if (!widget._vrpVisibilityWrapped) { + widget._vrpVisibilityWrapped = true; + widget._vrpBaseComputeSize = widget.computeSize; + widget.computeSize = function (...args) { + if (widget._vrpHidden) { + return [0, -4]; + } + if (typeof widget._vrpBaseComputeSize === "function") { + return widget._vrpBaseComputeSize.apply(this, args); + } + return [MIN_PICKER_NODE_WIDTH, Number(LiteGraph?.NODE_WIDGET_HEIGHT || 24)]; + }; + } + if (typeof widget._vrpOriginalDisplay === "undefined" && widget.inputEl) { + widget._vrpOriginalDisplay = widget.inputEl.style.display; + } + widget._vrpHidden = !visible; + widget.hidden = !visible; + if (widget.inputEl) { + widget.inputEl.style.display = visible ? (widget._vrpOriginalDisplay || "") : "none"; + } +} + +function refreshPickerLayout(node) { + if (Array.isArray(node.size) && node.size[0] < MIN_PICKER_NODE_WIDTH) { + node.size[0] = MIN_PICKER_NODE_WIDTH; + } + node.setDirtyCanvas(true, true); + app.graph?.setDirtyCanvas(true, true); +} + +function estimatePreviewHeight(node, domWidget) { + const nodeHeight = Math.max(Number(node?.size?.[1]) || DEFAULT_PICKER_NODE_SIZE[1], 320); + const titleHeight = Number(LiteGraph?.NODE_TITLE_HEIGHT || 30); + const topBottomPadding = 16; + const widgets = Array.isArray(node?.widgets) ? node.widgets : []; + let occupied = 0; + for (const widget of widgets) { + if (!widget || widget === domWidget) continue; + const size = typeof widget.computeSize === "function" + ? widget.computeSize(node.size?.[0] || MIN_PICKER_NODE_WIDTH) + : null; + const height = Array.isArray(size) ? Number(size[1]) || 0 : 0; + if (height > 0) { + occupied += height; + } + } + return Math.max(120, nodeHeight - titleHeight - topBottomPadding - occupied); +} + +function basenameForDisplay(value) { + const normalized = String(value || "").replace(/\\/g, "/"); + const i = normalized.lastIndexOf("/"); + return i >= 0 ? normalized.substring(i + 1) : normalized; +} + +function entryDisplayName(entry) { + return String(entry?.name || basenameForDisplay(entry?.path || "") || ""); +} + +function dirnameForPath(value) { + const normalized = String(value || "").replace(/\\/g, "/").replace(/\/+$/, ""); + const i = normalized.lastIndexOf("/"); + return i > 0 ? normalized.substring(0, i) : ""; +} + +function normalizeSelectedModPath(value) { + const path = String(value || "").trim(); + return path && path.toLowerCase() !== "(none)" ? path : ""; +} + +function normalizeFsPath(value) { + return String(value || "").trim().replace(/\\/g, "/").replace(/\/+/g, "/"); +} + +function isAbsoluteFsPath(value) { + return /^(?:[a-zA-Z]:\/|\/)/.test(normalizeFsPath(value)); +} + +function relativePathFromRoot(path, root) { + const normalizedPath = normalizeFsPath(path); + const normalizedRoot = normalizeFsPath(root).replace(/\/+$/, ""); + if (!normalizedPath) return ""; + if (!normalizedRoot || !isAbsoluteFsPath(normalizedPath)) return normalizedPath; + const lowerPath = normalizedPath.toLowerCase(); + const lowerRoot = normalizedRoot.toLowerCase(); + if (lowerPath === lowerRoot) return ""; + if (lowerPath.startsWith(`${lowerRoot}/`)) { + return normalizedPath.substring(normalizedRoot.length + 1); + } + return normalizedPath; +} + +function displayPathFromRoot(path, root) { + const relativePath = relativePathFromRoot(path, root); + return relativePath || "/"; +} + +function resolvePathFromRoot(path, root) { + const normalizedPath = normalizeFsPath(path); + const normalizedRoot = normalizeFsPath(root).replace(/\/+$/, ""); + if (!normalizedPath) return ""; + if (!normalizedRoot || isAbsoluteFsPath(normalizedPath)) return normalizedPath; + return `${normalizedRoot}/${normalizedPath}`.replace(/\/+/g, "/"); +} + +function buildPreviewUrl(path) { + if (!path) return PLACEHOLDER_IMAGE_PATH; + return api.apiURL(`/h3refmods/refmod-browser/file?path=${encodeURIComponent(path)}`); +} + +function entryHasVisual(entry) { + if (!entry) return true; + if (entry.paired_split) return true; + if (typeof entry.has_visual === "boolean") return entry.has_visual; + return entry.kind !== "audio"; +} + +function entryHasAudio(entry) { + if (!entry) return true; + if (entry.paired_split) return true; + if (typeof entry.has_audio === "boolean") return entry.has_audio; + return entry.kind === "audio"; +} + +function installPreviewFallback(img) { + if (!img || img.dataset.vrpFallbackInstalled === "1") return img; + img.dataset.vrpFallbackInstalled = "1"; + img.addEventListener("error", () => { + if (img.src === PLACEHOLDER_IMAGE_PATH) return; + img.src = PLACEHOLDER_IMAGE_PATH; + }); + return img; +} + +function normalizePathKey(value) { + return String(value || "").replace(/\\/g, "/").replace(/\/+/g, "/").toLowerCase(); +} + +function pathsEqual(a, b) { + return normalizePathKey(a) === normalizePathKey(b); +} + +async function getRefModsRoot() { + try { + const resp = await api.fetchApi("/h3refmods/refmod-browser/root"); + if (!resp.ok) return ""; + const data = await resp.json(); + return data.ok ? data.root : ""; + } catch (err) { + console.warn("[VisualRefModPicker] Could not get refmods root:", err); + return ""; + } +} + +async function listBrowserFolder(path) { + const query = path ? `?path=${encodeURIComponent(path)}` : ""; + const resp = await api.fetchApi(`/h3refmods/refmod-browser/list${query}`); + if (!resp.ok) { + let msg = `Request failed (${resp.status})`; + try { + const err = await resp.json(); + if (err?.error) msg = err.error; + } catch { + // ignore + } + throw new Error(msg); + } + return await resp.json(); +} + +function makeButton(label, onClick) { + const button = document.createElement("button"); + button.textContent = label; + button.style.cssText = ` + background: #2e3b4a; + border: 1px solid rgba(255,255,255,0.2); + border-radius: 6px; + color: #dce6f2; + padding: 5px 12px; + cursor: pointer; + font-size: 12px; + `; + button.onmouseenter = () => { + button.style.background = "#3a4a5c"; + }; + button.onmouseleave = () => { + button.style.background = "#2e3b4a"; + }; + button.addEventListener("click", onClick); + return button; +} + +function createRefModBrowserModal(initialPath, onSelect) { + const overlay = document.createElement("div"); + overlay.style.cssText = ` + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.8); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + `; + + const modal = document.createElement("div"); + modal.style.cssText = ` + background: rgba(40, 44, 52, 0.98); + border: 1px solid rgba(255,255,255,0.1); + border-radius: 6px; + width: 95%; + max-width: 1304px; + height: 95%; + max-height: 1185px; + display: flex; + flex-direction: column; + overflow: hidden; + box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45); + `; + + const header = document.createElement("div"); + header.style.cssText = ` + padding: 15px 20px; + border-bottom: 1px solid rgba(255,255,255,0.1); + `; + + const topRow = document.createElement("div"); + topRow.style.cssText = "display: flex; justify-content: space-between; align-items: center;"; + + const title = document.createElement("div"); + title.textContent = "Select RefMod"; + title.style.cssText = "margin: 0; color: #aaa; font-size: 1.17em; font-weight: 600;"; + + const closeButton = document.createElement("button"); + closeButton.textContent = "×"; + closeButton.style.cssText = ` + background: none; + border: none; + color: #aaa; + font-size: 24px; + cursor: pointer; + padding: 0; + width: 30px; + height: 30px; + `; + closeButton.onclick = () => overlay.remove(); + + const upButton = makeButton("Up", () => { + if (state.parentPath) void loadFolder(state.parentPath); + }); + + topRow.append(title, closeButton); + header.append(topRow); + + const filterBar = document.createElement("div"); + filterBar.style.cssText = ` + padding: 10px 20px; + border-bottom: 1px solid rgba(255,255,255,0.1); + display: flex; + align-items: center; + gap: 10px; + `; + + filterBar.appendChild(upButton); + + const searchWrap = document.createElement("div"); + searchWrap.style.cssText = "position: relative; flex: 1; display: flex; align-items: center;"; + + const searchInput = document.createElement("input"); + searchInput.type = "text"; + searchInput.placeholder = "Search files..."; + searchInput.style.cssText = ` + flex: 1; + padding: 8px 36px 8px 12px; + background: rgba(45, 55, 72, 0.7); + border: 1px solid rgba(226, 232, 240, 0.2); + border-radius: 6px; + color: #ccc; + `; + + const clearSearchButton = document.createElement("button"); + clearSearchButton.type = "button"; + clearSearchButton.textContent = "×"; + clearSearchButton.title = "Clear search"; + clearSearchButton.style.cssText = ` + position: absolute; + right: 8px; + top: 50%; + transform: translateY(-50%); + width: 20px; + height: 20px; + padding: 0; + border: none; + background: transparent; + color: #aaa; + cursor: pointer; + font-size: 16px; + line-height: 1; + display: none; + `; + + searchWrap.append(searchInput, clearSearchButton); + filterBar.appendChild(searchWrap); + + const body = document.createElement("div"); + body.style.cssText = ` + flex: 1; + overflow-y: auto; + padding: 20px; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + gap: 15px; + align-content: start; + `; + + const status = document.createElement("div"); + status.style.cssText = "padding: 10px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); display: flex; gap: 12px; align-items: center; font-size: 12px; color: #888;"; + + const countsLabel = document.createElement("div"); + countsLabel.style.cssText = "white-space: nowrap;"; + + const pathLabel = document.createElement("div"); + pathLabel.style.cssText = "min-width: 0; flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"; + + status.append(countsLabel, pathLabel); + + modal.append(header, filterBar, status, body); + overlay.appendChild(modal); + document.body.appendChild(overlay); + + overlay.addEventListener("click", (event) => { + if (event.target === overlay) overlay.remove(); + }); + + const state = { + root: "", + currentPath: "", + parentPath: null, + items: [], + }; + + function setCardSelected(card, selected) { + if (!card) return; + card.dataset.selected = selected ? "1" : "0"; + card.style.borderColor = selected ? "rgba(255, 255, 255, 0.95)" : "rgba(226, 232, 240, 0.2)"; + card.style.background = selected ? "rgba(50, 112, 163, 0.28)" : "rgba(45, 55, 72, 0.7)"; + card.style.transform = "translateY(0)"; + } + + function updateVisibleItems() { + const search = String(searchInput.value || "").trim().toLowerCase(); + for (const entry of state.items) { + const haystack = `${entry.kind === "dir" ? entry.data.name : entry.data.name}`.toLowerCase(); + const visible = !search || haystack.includes(search); + entry.element.style.display = visible ? "flex" : "none"; + } + } + + function updateSearchClearButton() { + clearSearchButton.style.display = searchInput.value ? "block" : "none"; + } + + function folderCard(entry) { + const card = document.createElement("div"); + card.className = "folder-item"; + card.style.cssText = ` + background: rgba(45, 55, 72, 0.7); + border: 1px solid rgba(226, 232, 240, 0.2); + border-radius: 6px; + padding: 8px; + cursor: pointer; + transition: all 0.15s ease; + display: flex; + flex-direction: column; + gap: 8px; + `; + const icon = document.createElement("div"); + icon.style.cssText = ` + width: 100%; + height: 250px; + background: rgba(0, 0, 0, 0.5); + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + font-size: 64px; + `; + icon.textContent = "📁"; + const label = document.createElement("div"); + label.textContent = entry.name; + label.style.cssText = ` + font-size: 12px; + color: #ccc; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; + `; + label.title = entry.name; + card.append(icon, label); + card.onmouseenter = () => { + card.style.borderColor = "rgba(66, 153, 225, 0.9)"; + card.style.transform = "translateY(-2px)"; + card.style.background = "rgba(50, 112, 163, 0.5)"; + }; + card.onmouseleave = () => { + card.style.borderColor = "rgba(226, 232, 240, 0.2)"; + card.style.transform = "translateY(0)"; + card.style.background = "rgba(45, 55, 72, 0.7)"; + }; + card.addEventListener("click", () => void loadFolder(entry.path)); + return card; + } + + function modCard(entry) { + const card = document.createElement("div"); + card.className = "thumbnail-item"; + card.style.cssText = ` + background: rgba(45, 55, 72, 0.7); + border: 1px solid rgba(226, 232, 240, 0.2); + border-radius: 6px; + padding: 8px; + cursor: pointer; + transition: all 0.15s ease; + display: flex; + flex-direction: column; + gap: 8px; + `; + const imageBox = document.createElement("div"); + imageBox.style.cssText = ` + width: 100%; + height: 250px; + background: rgba(0, 0, 0, 0.5); + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + position: relative; + `; + const img = document.createElement("img"); + installPreviewFallback(img); + img.src = entry.preview_path ? `${buildPreviewUrl(entry.preview_path)}&${Date.now()}` : PLACEHOLDER_IMAGE_PATH; + img.style.cssText = ` + width: 100%; + height: 100%; + object-fit: cover; + object-position: center center; + display: block; + background: rgba(0, 0, 0, 0.5); + `; + imageBox.appendChild(img); + const title = document.createElement("div"); + title.textContent = entryDisplayName(entry); + title.style.cssText = ` + font-size: 12px; + color: #ccc; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; + `; + title.title = entryDisplayName(entry); + card.append(imageBox, title); + const selectedPath = state.selectedPath; + setCardSelected(card, !!selectedPath && pathsEqual(selectedPath, entry.path)); + card.onmouseenter = () => { + if (card.dataset.selected === "1") return; + card.style.borderColor = "rgba(66, 153, 225, 0.9)"; + card.style.transform = "translateY(-2px)"; + card.style.background = "rgba(50, 112, 163, 0.5)"; + }; + card.onmouseleave = () => { + if (card.dataset.selected === "1") { + setCardSelected(card, true); + return; + } + card.style.borderColor = "rgba(226, 232, 240, 0.2)"; + card.style.transform = "translateY(0)"; + card.style.background = "rgba(45, 55, 72, 0.7)"; + }; + card.addEventListener("click", () => { + onSelect(entry); + overlay.remove(); + }); + return card; + } + + async function loadFolder(path) { + const requestedPath = path || state.root; + try { + countsLabel.textContent = "Loading..."; + pathLabel.textContent = ""; + body.replaceChildren(); + state.items = []; + const data = await listBrowserFolder(requestedPath); + state.root = data.root || state.root; + state.currentPath = data.current_path || requestedPath || state.currentPath; + state.parentPath = data.parent_path || null; + state.selectedPath = null; + pathLabel.textContent = displayPathFromRoot( + state.currentPath || state.root, + state.root + ); + upButton.disabled = !state.parentPath; + countsLabel.textContent = `${(data.dirs || []).length} folder(s), ${(data.mods || []).length} RefMod(s)`; + + for (const dir of data.dirs || []) { + const element = folderCard(dir); + state.items.push({ kind: "dir", data: dir, element }); + body.appendChild(element); + } + for (const mod of data.mods || []) { + const element = modCard(mod); + state.items.push({ kind: "mod", data: mod, element }); + body.appendChild(element); + } + if (!body.childNodes.length) { + const empty = document.createElement("div"); + empty.textContent = "No RefMods or subfolders found here."; + empty.style.cssText = "text-align: center; padding: 40px; color: #aaa;"; + body.appendChild(empty); + } + updateVisibleItems(); + } catch (err) { + const rootPath = state.root || await getRefModsRoot(); + if (rootPath && requestedPath && !pathsEqual(requestedPath, rootPath)) { + console.warn("[VisualRefModPicker] Browser folder missing, falling back to refmods root:", requestedPath, err); + state.root = rootPath; + await loadFolder(rootPath); + return; + } + countsLabel.textContent = err?.message || "Could not load RefMods."; + pathLabel.textContent = ""; + } + } + + searchInput.addEventListener("input", () => { + updateSearchClearButton(); + updateVisibleItems(); + }); + + clearSearchButton.addEventListener("click", () => { + searchInput.value = ""; + updateSearchClearButton(); + updateVisibleItems(); + searchInput.focus(); + }); + + updateSearchClearButton(); + + void (async () => { + const root = await getRefModsRoot(); + state.root = root; + await loadFolder(initialPath || root); + })(); +} + +app.registerExtension({ + name: "H3RefModPicker.VisualRefModPicker", + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData?.name !== "H3RefModVisualPicker") return; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + const result = onNodeCreated?.apply(this, arguments); + const node = this; + if (!node.properties) node.properties = {}; + node._configuredFromWorkflow = false; + + const modPathWidget = node.widgets?.find((w) => w.name === "mod_path"); + const strengthWidget = node.widgets?.find((w) => w.name === "video_weight") + || node.widgets?.find((w) => w.name === "strength"); + const audioStrengthWidget = node.widgets?.find((w) => w.name === "audio_weight") + || node.widgets?.find((w) => w.name === "audio_strength"); + + const panel = document.createElement("div"); + panel.style.cssText = ` + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + box-sizing: border-box; + gap: 2px; + overflow: hidden; + background: transparent; + `; + + const previewBox = document.createElement("div"); + previewBox.style.cssText = ` + position: relative; + flex: 1; + min-height: 80px; + width: 100%; + border-radius: 10px; + background: rgba(34, 39, 48, 0.98); + border: 1px solid rgba(78, 90, 108, 0.72); + overflow: hidden; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + padding: 2px 4px 4px; + `; + + const portraitFrame = document.createElement("div"); + portraitFrame.style.cssText = ` + position: relative; + height: 100%; + width: auto; + max-width: 100%; + max-height: 100%; + aspect-ratio: 3 / 4; + border-radius: 8px; + overflow: hidden; + background: rgba(0, 0, 0, 0.5); + flex: 0 1 auto; + `; + + const img = document.createElement("img"); + img.draggable = false; + installPreviewFallback(img); + img.src = PLACEHOLDER_IMAGE_PATH; + img.style.cssText = ` + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; + object-position: center center; + display: block; + user-select: none; + pointer-events: none; + -webkit-user-drag: none; + `; + + const emptyLabel = document.createElement("div"); + emptyLabel.textContent = "No RefMod selected"; + emptyLabel.style.cssText = ` + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + font-size: 11px; + color: rgba(178, 191, 208, 0.92); + background: rgba(0, 0, 0, 0.25); + border-radius: 10px; + pointer-events: none; + `; + + portraitFrame.appendChild(img); + portraitFrame.appendChild(emptyLabel); + previewBox.appendChild(portraitFrame); + + const clickCatcher = document.createElement("div"); + clickCatcher.style.cssText = ` + position: absolute; + inset: 0; + cursor: pointer; + background: transparent; + `; + previewBox.appendChild(clickCatcher); + + previewBox.addEventListener("wheel", (event) => { + const canvas = app.canvas?.canvas || document.querySelector("canvas.lgraphcanvas"); + if (!canvas) return; + const forwarded = new WheelEvent("wheel", { + bubbles: true, + cancelable: true, + clientX: event.clientX, + clientY: event.clientY, + deltaX: event.deltaX, + deltaY: event.deltaY, + deltaZ: event.deltaZ, + deltaMode: event.deltaMode, + ctrlKey: event.ctrlKey, + shiftKey: event.shiftKey, + altKey: event.altKey, + metaKey: event.metaKey, + }); + canvas.dispatchEvent(forwarded); + }, { passive: true }); + panel.appendChild(previewBox); + + const domWidget = node.addDOMWidget("vrp_preview", "div", panel, { + serialize: false, + hideOnZoom: false, + }); + domWidget.getHeight = () => estimatePreviewHeight(node, domWidget); + + const strengthWidgetIndex = node.widgets.indexOf(strengthWidget); + const audioStrengthWidgetIndex = node.widgets.indexOf(audioStrengthWidget); + const numericStrengthWidget = node.addWidget( + "number", + "video_weight", + strengthWidget?.value != null ? Number(strengthWidget.value) : 1.0, + (v) => { + if (strengthWidget) strengthWidget.value = Number(v); + node.setDirtyCanvas(true, true); + }, + { + min: strengthWidget?.options?.min != null ? Number(strengthWidget.options.min) : 0, + max: strengthWidget?.options?.max != null ? Number(strengthWidget.options.max) : 10, + step: strengthWidget?.options?.step != null ? Number(strengthWidget.options.step) : 0.01, + precision: 2, + } + ); + numericStrengthWidget.serialize = false; + + const numericAudioStrengthWidget = node.addWidget( + "number", + "audio_weight", + audioStrengthWidget?.value != null ? Number(audioStrengthWidget.value) : 1.0, + (v) => { + if (audioStrengthWidget) audioStrengthWidget.value = Number(v); + node.setDirtyCanvas(true, true); + }, + { + min: audioStrengthWidget?.options?.min != null ? Number(audioStrengthWidget.options.min) : 0, + max: audioStrengthWidget?.options?.max != null ? Number(audioStrengthWidget.options.max) : 10, + step: audioStrengthWidget?.options?.step != null ? Number(audioStrengthWidget.options.step) : 0.01, + precision: 2, + } + ); + numericAudioStrengthWidget.serialize = false; + + const normalizedStrengthValue = (value, fallback = 1.0) => { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; + }; + + const syncNumericStrength = () => { + const fallback = normalizedStrengthValue(numericStrengthWidget?.value, 1.0); + const next = normalizedStrengthValue(strengthWidget?.value, fallback); + numericStrengthWidget.value = next; + if (strengthWidget) strengthWidget.value = next; + }; + + const syncNumericAudioStrength = () => { + const fallback = normalizedStrengthValue(numericAudioStrengthWidget?.value, 1.0); + const next = normalizedStrengthValue(audioStrengthWidget?.value, fallback); + numericAudioStrengthWidget.value = next; + if (audioStrengthWidget) audioStrengthWidget.value = next; + }; + + if (strengthWidget) { + const originalStrengthCb = strengthWidget.callback; + strengthWidget.callback = function () { + syncNumericStrength(); + if (originalStrengthCb) return originalStrengthCb.apply(this, arguments); + }; + } + if (audioStrengthWidget) { + const originalAudioStrengthCb = audioStrengthWidget.callback; + audioStrengthWidget.callback = function () { + syncNumericAudioStrength(); + if (originalAudioStrengthCb) return originalAudioStrengthCb.apply(this, arguments); + }; + } + syncNumericStrength(); + syncNumericAudioStrength(); + + if (strengthWidget) hideWidget(strengthWidget); + if (audioStrengthWidget) hideWidget(audioStrengthWidget); + if (modPathWidget) hideWidget(modPathWidget); + + const applyModalityVisibility = (entry) => { + const hasVisual = entryHasVisual(entry); + const hasAudio = entryHasAudio(entry); + setDynamicWidgetVisible(numericStrengthWidget, hasVisual); + setDynamicWidgetVisible(numericAudioStrengthWidget, hasAudio); + node.properties._vrpHasVisual = hasVisual; + node.properties._vrpHasAudio = hasAudio; + refreshPickerLayout(node); + }; + + const storedPreviewEntry = (path) => { + if (!path) return null; + return { + path, + preview_path: node.properties?._vrpPreviewPath || "", + paired_split: Boolean(node.properties?._vrpPairedSplit), + has_visual: typeof node.properties?._vrpHasVisual === "boolean" + ? node.properties._vrpHasVisual + : true, + has_audio: typeof node.properties?._vrpHasAudio === "boolean" + ? node.properties._vrpHasAudio + : true, + }; + }; + + applyModalityVisibility(null); + + let filePickerWidget = node.addWidget( + "combo", + "mod", + "(none)", + (label) => { + const selected = node._vrpModMap?.[label] || null; + setSelection(selected); + }, + { values: ["(none)"] } + ); + filePickerWidget.serialize = false; + node._vrpModMap = { "(none)": null }; + + node._vrpStepModByDelta = async (delta) => { + const direction = delta >= 0 ? 1 : -1; + const labels = Array.isArray(filePickerWidget?.options?.values) + ? filePickerWidget.options.values.filter((label) => label !== "(none)") + : []; + if (labels.length <= 1) return false; + + const currentLabel = String(filePickerWidget?.value || ""); + const currentIndex = labels.indexOf(currentLabel); + + let nextIndex; + if (currentIndex < 0) { + nextIndex = direction > 0 ? 0 : labels.length - 1; + } else { + nextIndex = (currentIndex + direction + labels.length) % labels.length; + } + + const nextLabel = labels[nextIndex]; + if (!nextLabel) return false; + + filePickerWidget.value = nextLabel; + if (typeof filePickerWidget.callback === "function") { + filePickerWidget.callback(nextLabel); + } else { + const nextEntry = node._vrpModMap?.[nextLabel] || null; + setSelection(nextEntry); + } + return true; + }; + + installVrpArrowNavigation(); + + const loadPreview = async (entry) => { + applyModalityVisibility(entry); + if (!entry || !entry.path) { + emptyLabel.textContent = "No RefMod selected"; + img.removeAttribute("src"); + img.style.display = "none"; + emptyLabel.style.display = "flex"; + return; + } + if (!entryHasVisual(entry)) { + emptyLabel.textContent = "Audio-only RefMod"; + img.style.display = "block"; + img.src = PLACEHOLDER_IMAGE_PATH; + emptyLabel.style.display = "flex"; + return; + } + img.style.display = "block"; + emptyLabel.style.display = "none"; + img.src = entry.preview_path ? buildPreviewUrl(entry.preview_path) : PLACEHOLDER_IMAGE_PATH; + }; + + const setSelection = (entry) => { + const selected = entry && entry.path ? entry : null; + const rootPath = node._vrpRoot || ""; + const absoluteValue = selected?.path || ""; + const storedValue = relativePathFromRoot(absoluteValue, rootPath); + if (modPathWidget) modPathWidget.value = storedValue; + const label = Object.keys(node._vrpModMap || {}).find((key) => pathsEqual(node._vrpModMap[key]?.path, absoluteValue)); + if (filePickerWidget) filePickerWidget.value = label || "(none)"; + node.properties._vrpModPath = storedValue; + node.properties._vrpModDir = selected?.path ? dirnameForPath(storedValue) : (node.properties._vrpModDir || ""); + node.properties._vrpPreviewPath = relativePathFromRoot(selected?.preview_path || "", rootPath); + node.properties._vrpPairedSplit = Boolean(selected?.paired_split); + node.properties._vrpHasVisual = selected ? entryHasVisual(selected) : true; + node.properties._vrpHasAudio = selected ? entryHasAudio(selected) : true; + void loadPreview(selected); + node.setDirtyCanvas(true, true); + }; + + const refreshPickerOptions = async (folderPath, preferredPath = null) => { + let requestedFolderPath = folderPath || ""; + let fallbackRoot = node._vrpRoot || await getRefModsRoot(); + if (!requestedFolderPath) { + requestedFolderPath = fallbackRoot; + } + if (!requestedFolderPath) return; + + let data; + try { + data = await listBrowserFolder(requestedFolderPath); + } catch (err) { + fallbackRoot = fallbackRoot || await getRefModsRoot(); + if (!fallbackRoot || pathsEqual(requestedFolderPath, fallbackRoot)) { + throw err; + } + console.warn("[VisualRefModPicker] Restored folder missing, falling back to refmods root:", requestedFolderPath, err); + requestedFolderPath = fallbackRoot; + data = await listBrowserFolder(requestedFolderPath); + node.properties._vrpModDir = ""; + } + + node._vrpRoot = data.root || node._vrpRoot || ""; + if (pathsEqual(requestedFolderPath, node._vrpRoot || "")) { + node.properties._vrpModDir = ""; + } else { + node.properties._vrpModDir = relativePathFromRoot(requestedFolderPath, node._vrpRoot || data.root || ""); + } + const labels = ["(none)"]; + const map = { "(none)": null }; + const used = new Set(labels); + for (const entry of data.mods || []) { + const base = entryDisplayName(entry) || entry.name; + let label = base; + let idx = 2; + while (used.has(label)) { + label = `${base} (${idx++})`; + } + used.add(label); + labels.push(label); + map[label] = entry; + } + node._vrpModMap = map; + if (filePickerWidget) filePickerWidget.options.values = labels; + const desiredPath = preferredPath != null ? preferredPath : (modPathWidget?.value || ""); + const desiredAbsolutePath = resolvePathFromRoot(desiredPath, node._vrpRoot || data.root || ""); + const desiredLabel = Object.keys(map).find((key) => pathsEqual(map[key]?.path, desiredAbsolutePath)); + if (filePickerWidget) filePickerWidget.value = desiredLabel || "(none)"; + return desiredLabel ? map[desiredLabel] : null; + }; + + const openBrowser = async () => { + const root = await getRefModsRoot(); + node._vrpRoot = root || node._vrpRoot || ""; + const current = node.properties?._vrpModPath || modPathWidget?.value || ""; + const initialPath = resolvePathFromRoot( + node.properties?._vrpModDir || dirnameForPath(current), + node._vrpRoot || root + ) || root; + createRefModBrowserModal(initialPath, async (selected) => { + node.properties._vrpModDir = dirnameForPath( + relativePathFromRoot(selected.path, node._vrpRoot || root) + ); + setSelection(selected); + await refreshPickerOptions(node.properties._vrpModDir, selected.path); + }); + }; + + const browseButton = node.addWidget("button", "📁 Select RefMod", null, openBrowser); + browseButton.serialize = false; + + const modPathWidgetIndex = node.widgets.indexOf(modPathWidget); + if (modPathWidgetIndex >= 0 && filePickerWidget) { + const pickerIndex = node.widgets.indexOf(filePickerWidget); + if (pickerIndex >= 0) { + node.widgets.splice(pickerIndex, 1); + node.widgets.splice(modPathWidgetIndex + 1, 0, filePickerWidget); + } + const buttonIndex = node.widgets.indexOf(browseButton); + if (buttonIndex >= 0) { + node.widgets.splice(buttonIndex, 1); + node.widgets.splice(modPathWidgetIndex + 2, 0, browseButton); + } + const previewIndex = node.widgets.indexOf(domWidget); + if (previewIndex >= 0) { + node.widgets.splice(previewIndex, 1); + node.widgets.splice(modPathWidgetIndex + 3, 0, domWidget); + } + } + + if (strengthWidgetIndex >= 0 && numericStrengthWidget) { + const numericIndex = node.widgets.indexOf(numericStrengthWidget); + if (numericIndex >= 0) { + node.widgets.splice(numericIndex, 1); + node.widgets.splice(strengthWidgetIndex + 1, 0, numericStrengthWidget); + } + } + if (audioStrengthWidgetIndex >= 0 && numericAudioStrengthWidget) { + const numericAudioIndex = node.widgets.indexOf(numericAudioStrengthWidget); + if (numericAudioIndex >= 0) { + node.widgets.splice(numericAudioIndex, 1); + node.widgets.splice(audioStrengthWidgetIndex + 1, 0, numericAudioStrengthWidget); + } + } + + if (filePickerWidget && browseButton) { + const pickerIndex = node.widgets.indexOf(filePickerWidget); + const buttonIndex = node.widgets.indexOf(browseButton); + if (pickerIndex >= 0 && buttonIndex >= 0) { + node.widgets.splice(buttonIndex, 1); + node.widgets.splice(pickerIndex + 1, 0, browseButton); + } + } + + clickCatcher.addEventListener("click", async (event) => { + event.stopPropagation(); + await openBrowser(); + }); + + const onMouseMove = node.onMouseMove; + node.onMouseMove = function () { + _vrpHoveredNode = this; + return onMouseMove?.apply(this, arguments); + }; + + const onMouseEnter = node.onMouseEnter; + node.onMouseEnter = function () { + _vrpHoveredNode = this; + return onMouseEnter?.apply(this, arguments); + }; + + const onMouseLeave = node.onMouseLeave; + node.onMouseLeave = function () { + if (_vrpHoveredNode === this) { + _vrpHoveredNode = null; + } + return onMouseLeave?.apply(this, arguments); + }; + + if (previewBox) { + previewBox.addEventListener("mouseenter", () => { + _vrpHoveredNode = node; + }); + previewBox.addEventListener("mouseleave", () => { + if (_vrpHoveredNode === node) { + _vrpHoveredNode = null; + } + }); + } + + const originalSerialize = node.serialize; + node.serialize = function () { + const rootPath = node._vrpRoot || ""; + const serializedModPath = normalizeSelectedModPath( + relativePathFromRoot(node.properties?._vrpModPath || modPathWidget?.value || "", rootPath) + ); + if (modPathWidget) { + modPathWidget.value = serializedModPath; + } + node.properties._vrpModPath = serializedModPath; + if (serializedModPath) { + node.properties._vrpModDir = dirnameForPath(serializedModPath); + } + node.properties._vrpPreviewPath = relativePathFromRoot(node.properties?._vrpPreviewPath || "", rootPath); + if (strengthWidget && numericStrengthWidget) { + strengthWidget.value = normalizedStrengthValue( + numericStrengthWidget.value, + normalizedStrengthValue(strengthWidget.value, 1.0) + ); + numericStrengthWidget.value = strengthWidget.value; + } + if (audioStrengthWidget && numericAudioStrengthWidget) { + audioStrengthWidget.value = normalizedStrengthValue( + numericAudioStrengthWidget.value, + normalizedStrengthValue(audioStrengthWidget.value, 1.0) + ); + numericAudioStrengthWidget.value = audioStrengthWidget.value; + } + return originalSerialize ? originalSerialize.apply(this, arguments) : undefined; + }; + + const oldOnResize = node.onResize; + node.onResize = function (size) { + const res = oldOnResize?.apply(this, arguments); + if (size) { + if (size[0] < 200) size[0] = 200; + if (size[1] < 320) size[1] = 320; + } + return res; + }; + + const origDraw = domWidget.draw; + domWidget.draw = function (ctx, n) { + if (typeof origDraw === "function") origDraw.apply(this, arguments); + if (!panel || n.flags?.collapsed) return; + panel.style.setProperty("width", (n.size[0] - 18) + "px", "important"); + panel.style.setProperty("left", "0px", "important"); + panel.style.setProperty("margin", "0px", "important"); + panel.style.setProperty("padding", "0 4px 4px", "important"); + panel.style.setProperty("height", `calc(100% + ${PREVIEW_PANEL_OVERLAP_PX}px)`, "important"); + panel.style.setProperty("transform", `translateY(-${PREVIEW_PANEL_OVERLAP_PX}px)`, "important"); + panel.style.setProperty("transform-origin", "top left", "important"); + panel.style.setProperty("box-sizing", "border-box", "important"); + panel.style.setProperty("overflow", "visible", "important"); + }; + + const onConfigure = node.onConfigure; + node.onConfigure = async function (info) { + node._configuredFromWorkflow = true; + node.properties._configuredFromWorkflow = true; + const res = onConfigure?.apply(this, arguments); + if (info && info.widgets_values) { + if (strengthWidget) { + const idx = this.widgets.indexOf(strengthWidget); + if (idx >= 0 && info.widgets_values[idx] !== undefined && info.widgets_values[idx] !== null) { + strengthWidget.value = normalizedStrengthValue(info.widgets_values[idx], 1.0); + } + } + if (audioStrengthWidget) { + const idx = this.widgets.indexOf(audioStrengthWidget); + if (idx >= 0 && info.widgets_values[idx] !== undefined && info.widgets_values[idx] !== null) { + audioStrengthWidget.value = normalizedStrengthValue(info.widgets_values[idx], 1.0); + } + } + } + if (strengthWidget && !Number.isFinite(Number(strengthWidget.value))) { + strengthWidget.value = 1.0; + } + if (audioStrengthWidget && !Number.isFinite(Number(audioStrengthWidget.value))) { + audioStrengthWidget.value = 1.0; + } + syncNumericStrength(); + syncNumericAudioStrength(); + + const restoredPath = normalizeSelectedModPath( + modPathWidget?.value || node.properties?._vrpModPath || "" + ); + if (modPathWidget) { + modPathWidget.value = restoredPath; + } + node.properties._vrpModPath = restoredPath; + if (restoredPath) { + node.properties._vrpModDir = dirnameForPath(restoredPath); + } + const restoredDir = node.properties?._vrpModDir || dirnameForPath(restoredPath); + const dir = restoredDir || await getRefModsRoot(); + node.properties._vrpModDir = dir; + const restoredEntry = await refreshPickerOptions(dir, restoredPath); + if (restoredEntry) { + setSelection(restoredEntry); + } else { + void loadPreview(storedPreviewEntry(restoredPath)); + } + return res; + }; + + setTimeout(async () => { + syncNumericStrength(); + syncNumericAudioStrength(); + const initialPath = normalizeSelectedModPath( + modPathWidget?.value || node.properties?._vrpModPath || "" + ); + if (modPathWidget) { + modPathWidget.value = initialPath; + } + node.properties._vrpModPath = initialPath; + if (initialPath) { + node.properties._vrpModDir = node.properties?._vrpModDir || dirnameForPath(initialPath); + } + const dir = node.properties?._vrpModDir || dirnameForPath(initialPath) || await getRefModsRoot(); + node.properties._vrpModDir = dir; + const initialEntry = await refreshPickerOptions(dir, initialPath || null); + if (initialEntry) { + setSelection(initialEntry); + } else { + void loadPreview(storedPreviewEntry(initialPath)); + } + if (!node.properties?._configuredFromWorkflow) { + node.setSize([...DEFAULT_PICKER_NODE_SIZE]); + } + }, 10); + + return result; + }; + }, +}); + +console.log("[H3RefModPicker] VisualRefModPicker extension loaded"); \ No newline at end of file diff --git a/js/vendor/dumas_minimax_h3_refmod/library_dialog.js b/js/vendor/dumas_minimax_h3_refmod/library_dialog.js new file mode 100644 index 0000000..09ab2e6 --- /dev/null +++ b/js/vendor/dumas_minimax_h3_refmod/library_dialog.js @@ -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; +} diff --git a/js/vendor/dumas_minimax_h3_refmod/refmod_apply.js b/js/vendor/dumas_minimax_h3_refmod/refmod_apply.js new file mode 100644 index 0000000..769add8 --- /dev/null +++ b/js/vendor/dumas_minimax_h3_refmod/refmod_apply.js @@ -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); + }, +}); diff --git a/js/vendor/dumas_minimax_h3_refmod/refmod_creation_labels.js b/js/vendor/dumas_minimax_h3_refmod/refmod_creation_labels.js new file mode 100644 index 0000000..626fcfc --- /dev/null +++ b/js/vendor/dumas_minimax_h3_refmod/refmod_creation_labels.js @@ -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; + }; + } + } +}); diff --git a/js/vendor/dumas_minimax_h3_refmod/refmod_library.js b/js/vendor/dumas_minimax_h3_refmod/refmod_library.js new file mode 100644 index 0000000..4f7dfc8 --- /dev/null +++ b/js/vendor/dumas_minimax_h3_refmod/refmod_library.js @@ -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; + }; + } +}); diff --git a/js/vendor/dumas_minimax_h3_refmod/refmod_slots.js b/js/vendor/dumas_minimax_h3_refmod/refmod_slots.js new file mode 100644 index 0000000..36ffe56 --- /dev/null +++ b/js/vendor/dumas_minimax_h3_refmod/refmod_slots.js @@ -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); + } + }, +});