-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathutils.js
More file actions
5927 lines (5162 loc) · 276 KB
/
Copy pathutils.js
File metadata and controls
5927 lines (5162 loc) · 276 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { DEFAULT_DIMENSIONS_LIST, DEFAULT_MODELS_ARCH_LIST, DEFAULT_CONTROLNET_CONDITIONING_LIST,
RUNWARE_NODE_TYPES, MODEL_TYPES_TERMS, MODEL_LIST_TERMS
} from "./types.js";
const TIMEOUT_RANGE = { min: 5, default: 90, max: 99 };
const OUTPUT_QUALITY_RANGE = { min: 20, default: 95, max: 99 };
const CACHE_SIZE_RANGE = { min: 30, default: 150, max: 4096 };
/** Must match `audioInferenceInputs.MAX_VIDEOS` in modules/audioInferenceInputs.py */
const AUDIO_INFERENCE_INPUTS_MAX_VIDEOS = 4;
/** Must match `audioInferenceInputs.MAX_AUDIOS` in modules/audioInferenceInputs.py */
const AUDIO_INFERENCE_INPUTS_MAX_AUDIOS = 4;
let openDialog = false;
let lastTimeout = false;
let lastOutputFormat = false;
let lastOutputQuality = false;
let lastEnableImagesCaching = null;
let lastMinImageCacheSize = false;
async function queryLocalAPI(endpoint, data) {
try {
const resp = await api.fetchApi(`/${endpoint}`, {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
return await resp.json();
} catch (err) {
return false;
}
}
const runwareLocalAPI = {
enhancePrompt: (userPrompt) => queryLocalAPI('promptEnhance', { userPrompt }),
setAPIKey: (apiKey) => queryLocalAPI('setAPIKey', { apiKey }),
setTimeout: (maxTimeout) => queryLocalAPI('setMaxTimeout', { maxTimeout }),
setOutputFormat: (outputFormat) => queryLocalAPI('setOutputFormat', { outputFormat }),
setOutputQuality: (outputQuality) => queryLocalAPI('setOutputQuality', { outputQuality }),
setEnableImagesCaching: (enableCaching) => queryLocalAPI('setEnableImagesCaching', { enableCaching }),
setMinImageCacheSize: (minCacheSize) => queryLocalAPI('setMinImageCacheSize', { minCacheSize }),
modelSearch: (modelQuery = "", modelArch = "all", modelType = "base", modelCat = "checkpoint", condtioning = "") =>
queryLocalAPI('modelSearch', { modelQuery, modelArch, modelType, modelCat, condtioning })
};
function mediaUUIDHandler(msgEvent) {
const mediaData = msgEvent.detail;
const mediaUUID = mediaData.mediaUUID;
const mediaNodeID = parseInt(mediaData.nodeID);
if(mediaData.success) {
const mediaNode = app.graph.getNodeById(mediaNodeID);
if(mediaNode !== null && mediaNode !== undefined) {
// Find the mediaUUID widget specifically
const mediaUUIDWidget = mediaNode.widgets.find(widget => widget.name === "mediaUUID");
if(mediaUUIDWidget) {
// Update both widget.value and inputEl.value for STRING widgets
if(mediaUUIDWidget.value !== undefined) {
mediaUUIDWidget.value = mediaUUID;
}
if(mediaUUIDWidget.inputEl) {
mediaUUIDWidget.inputEl.value = mediaUUID;
// Trigger change events to update the UI
mediaUUIDWidget.inputEl.dispatchEvent(new Event('input', { bubbles: true }));
mediaUUIDWidget.inputEl.dispatchEvent(new Event('change', { bubbles: true }));
}
}
}
}
return false;
}
function save3DFilepathHandler(msgEvent) {
const data = msgEvent.detail;
const filepath = data.filepath;
const nodeID = parseInt(data.nodeID, 10);
if (Number.isNaN(nodeID)) return false;
if(data.success && filepath) {
const node = app.graph.getNodeById(nodeID);
if(node !== null && node !== undefined) {
const filepathWidget = node.widgets.find(widget => widget.name === "filepath");
if(filepathWidget) {
if(filepathWidget.value !== undefined) {
filepathWidget.value = filepath;
}
if(filepathWidget.inputEl) {
filepathWidget.inputEl.value = filepath;
filepathWidget.inputEl.dispatchEvent(new Event('input', { bubbles: true }));
filepathWidget.inputEl.dispatchEvent(new Event('change', { bubbles: true }));
}
}
}
}
return false;
}
function captionNodeHandler(msgEvent) {
const captionData = msgEvent.detail;
const captionText = captionData.captionText;
const captionNodeID = parseInt(captionData.nodeID);
if(captionData.success) {
const captionNode = app.graph.getNodeById(captionNodeID);
if(captionNode !== null && captionNode !== undefined) {
// Find the imageCaption widget specifically
const imageCaptionWidget = captionNode.widgets.find(widget => widget.name === "imageCaption");
if(imageCaptionWidget && imageCaptionWidget.inputEl) {
imageCaptionWidget.inputEl.value = captionText;
}
}
}
return false;
}
function saveTextHandler(msgEvent) {
const data = msgEvent.detail;
const displayText = data.text;
const nodeID = parseInt(data.nodeID, 10);
if (!data.success || Number.isNaN(nodeID)) return false;
const node = app.graph.getNodeById(nodeID);
if (node === null || node === undefined) return false;
const widgetName = data.widgetName || "text";
const textWidget = node.widgets.find((w) => w.name === widgetName);
if (textWidget) {
if (textWidget.value !== undefined) {
textWidget.value = displayText;
}
if (textWidget.inputEl) {
textWidget.inputEl.value = displayText;
textWidget.inputEl.dispatchEvent(new Event("input", { bubbles: true }));
textWidget.inputEl.dispatchEvent(new Event("change", { bubbles: true }));
}
}
return false;
}
function videoTranscriptionHandler(msgEvent) {
const transcriptionData = msgEvent.detail;
const transcriptionText = transcriptionData.transcriptionText;
const transcriptionNodeID = parseInt(transcriptionData.nodeID);
if(transcriptionData.success) {
const transcriptionNode = app.graph.getNodeById(transcriptionNodeID);
if(transcriptionNode !== null && transcriptionNode !== undefined) {
// Find the prompt widget (where transcription is displayed)
const promptWidget = transcriptionNode.widgets.find(widget => widget.name === "prompt");
if(promptWidget && promptWidget.inputEl) {
promptWidget.inputEl.value = transcriptionText;
}
}
}
return false;
}
function videoOutputsHandler(msgEvent) {
const outputData = msgEvent.detail;
const draftId = outputData.draftId || "";
const videoId = outputData.videoId || "";
const nodeID = outputData.nodeID;
if(outputData.success && nodeID !== undefined && nodeID !== null) {
const nodeIdInt = typeof nodeID === 'string' ? parseInt(nodeID) : nodeID;
const outputNode = app.graph.getNodeById(nodeIdInt);
if(outputNode !== null && outputNode !== undefined) {
const draftIdWidget = outputNode.widgets.find(widget => widget.name === "draftId");
const videoIdWidget = outputNode.widgets.find(widget => widget.name === "videoId");
if(draftIdWidget) {
if(draftIdWidget.value !== undefined) draftIdWidget.value = draftId;
if(draftIdWidget.inputEl) {
draftIdWidget.inputEl.value = draftId;
draftIdWidget.inputEl.dispatchEvent(new Event('input', { bubbles: true }));
draftIdWidget.inputEl.dispatchEvent(new Event('change', { bubbles: true }));
}
}
if(videoIdWidget) {
if(videoIdWidget.value !== undefined) videoIdWidget.value = videoId;
if(videoIdWidget.inputEl) {
videoIdWidget.inputEl.value = videoId;
videoIdWidget.inputEl.dispatchEvent(new Event('input', { bubbles: true }));
videoIdWidget.inputEl.dispatchEvent(new Event('change', { bubbles: true }));
}
}
outputNode.setDirtyCanvas(true);
}
}
return false;
}
function notifyUser(message, type="info", title = "Runware", life = 4.5) {
app.extensionManager.toast.add({
severity: type, // 'info', 'success', 'warn', 'error' \\
summary: title,
detail: message,
life: Math.floor(life * 1000)
});
}
async function promptEnhanceHandler(e) {
if(e.ctrlKey && e.altKey && e.key.toLowerCase() === 'e') {
const userPrompt = e.target.value.trim();
if(userPrompt.length <= 1) {
notifyUser("Prompt Is Too Short!", "error", "Runware Prompt Enhancer");
return;
} else if(userPrompt.length > 300) {
notifyUser("Prompt Must Not Exceed 300 Characters!", "error", "Runware Prompt Enhancer");
return;
}
const enhanceResults = await runwareLocalAPI.enhancePrompt(userPrompt);
if(enhanceResults.success) {
e.target.value = enhanceResults.enhancedPrompt;
} else {
notifyUser(enhanceResults.error, "error", "Runware Prompt Enhancer");
}
}
}
function remNode(node) {
app.graph.remove(node);
app.graph.setDirtyCanvas(true,true);
}
async function APIKeyHandler(apiManagerNode) {
const widgets = apiManagerNode.widgets;
for(const widget of widgets) {
if(widget.name === "API Key") {
appendWidgetCB(widget, async function(...args) {
if(openDialog) return;
const apiKey = args[0].trim();
if(apiKey.length < 30) {
notifyUser("Invalid API Key Set, Please Try Again!", "error", "Runware API Manager");
return;
}
const setAPIKeyResults = await runwareLocalAPI.setAPIKey(apiKey);
if(setAPIKeyResults.success) {
remNode(apiManagerNode);
notifyUser("API Key Set Successfully!", "success", "Runware API Manager");
} else {
notifyUser(setAPIKeyResults.error, "error", "Runware API Manager");
}
});
} else if(widget.name === "Max Timeout") {
if(lastTimeout) widget.value = lastTimeout;
appendWidgetCB(widget, async function(...args) {
const maxTimeout = parseInt(args[0]);
if(isNaN(maxTimeout) || maxTimeout < TIMEOUT_RANGE.min || maxTimeout > TIMEOUT_RANGE.max) {
notifyUser(`Invalid Timeout Value! Must be between ${TIMEOUT_RANGE.min} and ${TIMEOUT_RANGE.max} seconds.`, "error", "Runware API Manager");
widget.value = lastTimeout || TIMEOUT_RANGE.default;
return;
}
const setTimeoutResults = await runwareLocalAPI.setTimeout(maxTimeout);
if(setTimeoutResults.success) {
notifyUser("Timeout Set Successfully!", "success", "Runware API Manager");
lastTimeout = maxTimeout;
} else {
widget.value = lastTimeout || TIMEOUT_RANGE.default;
notifyUser(setTimeoutResults.error, "error", "Runware API Manager");
}
});
} else if(widget.name === "Image Output Format") {
if(lastOutputFormat) widget.value = lastOutputFormat;
appendWidgetCB(widget, async function(...args) {
const outputFormat = args[0].trim().toUpperCase();
const setFormatResults = await runwareLocalAPI.setOutputFormat(outputFormat);
if(setFormatResults.success) {
notifyUser("Default Image Output Format Set Successfully!", "success", "Runware API Manager");
lastOutputFormat = outputFormat;
} else {
notifyUser(setFormatResults.error, "error", "Runware API Manager");
}
});
} else if(widget.name === "Image Output Quality") {
if(lastOutputQuality) widget.value = lastOutputQuality;
appendWidgetCB(widget, async function(...args) {
const outputQuality = parseInt(args[0]);
if(isNaN(outputQuality) || outputQuality < OUTPUT_QUALITY_RANGE.min || outputQuality > OUTPUT_QUALITY_RANGE.max) {
notifyUser(`Invalid Quality Value! Must be between ${OUTPUT_QUALITY_RANGE.min} and ${OUTPUT_QUALITY_RANGE.max}.`, "error", "Runware API Manager");
widget.value = lastOutputQuality || OUTPUT_QUALITY_RANGE.default;
return;
}
const setQualityResults = await runwareLocalAPI.setOutputQuality(outputQuality);
if(setQualityResults.success) {
notifyUser("Default Image Output Quality Set Successfully!", "success", "Runware API Manager");
lastOutputQuality = outputQuality;
} else {
widget.value = lastOutputQuality || OUTPUT_QUALITY_RANGE.default;
notifyUser(setQualityResults.error, "error", "Runware API Manager");
}
});
} else if(widget.name === "Enable Images Caching") {
if(lastEnableImagesCaching !== null) widget.value = lastEnableImagesCaching;
appendWidgetCB(widget, async function(...args) {
const enableCaching = args[0];
const setCachingResults = await runwareLocalAPI.setEnableImagesCaching(enableCaching);
if(setCachingResults.success) {
notifyUser("Image Caching Setting Updated Successfully!", "success", "Runware API Manager");
lastEnableImagesCaching = enableCaching;
} else {
widget.value = lastEnableImagesCaching;
notifyUser(setCachingResults.error, "error", "Runware API Manager");
}
});
} else if(widget.name === "Min Image Cache Size") {
if(lastMinImageCacheSize !== false) widget.value = lastMinImageCacheSize;
appendWidgetCB(widget, async function(...args) {
const minCacheSize = parseFloat(args[0]);
if(isNaN(minCacheSize) || minCacheSize < CACHE_SIZE_RANGE.min || minCacheSize > CACHE_SIZE_RANGE.max) {
notifyUser(`Invalid cache size! Must be between ${CACHE_SIZE_RANGE.min} KB and ${CACHE_SIZE_RANGE.max} KB.`, "error", "Runware API Manager");
widget.value = lastMinImageCacheSize || CACHE_SIZE_RANGE.default;
return;
}
const setCacheSizeResults = await runwareLocalAPI.setMinImageCacheSize(minCacheSize);
if(setCacheSizeResults.success) {
notifyUser("Minimum Image Cache Size Updated Successfully!", "success", "Runware API Manager");
lastMinImageCacheSize = minCacheSize;
} else {
widget.value = lastMinImageCacheSize || CACHE_SIZE_RANGE.default;
notifyUser(setCacheSizeResults.error, "error", "Runware API Manager");
}
});
}
}
}
function addTriggerWords(prompt, triggerWords) {
if (!triggerWords?.trim()) return prompt;
const cleanedTriggerWords = triggerWords
.trim()
.replace(/,\s*$/, '')
.split(',')
.map(word => word.trim())
.filter(word => word.length);
if (!prompt?.trim()) return cleanedTriggerWords.join(', ');
const wordsToAdd = cleanedTriggerWords.filter(word =>
!new RegExp(`\\b${word}\\b`, 'i').test(prompt)
);
return wordsToAdd.length
? `${prompt}${prompt.endsWith(',') ? ' ' : ', '}${wordsToAdd.join(', ')}`
: prompt;
}
function handleCustomErrors(errObj) {
const errData = errObj.detail;
const errCode = errData.errorCode;
if(errCode === 401 && !openDialog) {
const dialog = new comfyAPI.asyncDialog.ComfyAsyncDialog();
const htmlContent = `
<center>
<div style="padding: auto 200px; text-align: center;">
<h2>Runware Inference Error</h2>
<h4>Your API Key is Invalid Or Undefined. You Need To Update It.</h4>
<form method="POST" id="runwareAPIKey">
<input
id="apiKey"
type="text"
placeholder="Enter Your API Key ..." minlength="30" maxlength="48"
style="padding: 5px; min-width: 300px; text-align: center; margin-top: 10px;" required>
<div style="margin-top: 15px; display: flex; justify-content: center; gap: 10px;">
<button id="setAPIKeyBTN" style="padding: 8px 15px; background-color: #6c5ce7; color: #ccc;">Set Your API Key</button>
<button id="getAPIKeyBTN" style="padding: 8px 15px; background-color: #dfe6e9; color: #000;">Create New API Key</button>
</div>
</form>
</div>
</center>
`;
dialog.showModal(htmlContent).then(() => {
openDialog = false;
});
openDialog = true;
dialog.element.addEventListener('close', () => {
openDialog = false;
});
const runwareAPIForm = document.getElementById("runwareAPIKey");
const apiKeyInput = document.getElementById("apiKey");
const getAPIKeyBTN = document.getElementById("getAPIKeyBTN");
const setAPIKeyBTN = document.getElementById("setAPIKeyBTN");
getAPIKeyBTN.onclick = (e) => {
e.preventDefault();
window.open("https://my.runware.ai/keys?utm_source=comfyui&utm_medium=referral&utm_campaign=comfyui_api_key_creation", "_blank");
};
async function authUser(e) {
e.preventDefault();
e.stopPropagation();
const apiKey = apiKeyInput.value.trim();
if(apiKey.length < 30) {
runwareAPIForm.reportValidity();
return;
// notifyUser("Invalid API Key Set, Please Try Again!", "error", "Runware API Manager");
// return;
} else {
const setAPIKeyResults = await runwareLocalAPI.setAPIKey(apiKey);
if(setAPIKeyResults.success) {
dialog.close();
openDialog = false;
notifyUser("API Key Set Successfully!", "success", "Runware API Manager");
} else {
notifyUser(setAPIKeyResults.error, "error", "Runware API Manager");
}
}
};
setAPIKeyBTN.onclick = async (e) => {
authUser(e);
};
runwareAPIForm.onsubmit = async (e) => {
authUser(e);
};
}
}
function appendWidgetCB(node, newCB) {
const oldNodeCB = node.callback;
if(typeof oldNodeCB === "function") {
node.callback = function(...args) {
oldNodeCB?.apply(this, args);
newCB?.apply(this, args);
}
} else {
node.callback = newCB;
}
}
async function syncDimensionsNodeHandler(node, dimensionsWidget) {
const nodeWidgets = node.widgets;
let widthWidget = false, heightWidget = false;
for(const nodeWidget of nodeWidgets) {
const widgetName = nodeWidget.name;
const widgetType = nodeWidget.type;
if(widgetName === "width" && widgetType === "number") widthWidget = nodeWidget;
if(widgetName === "height" && widgetType === "number") heightWidget = nodeWidget;
}
appendWidgetCB(dimensionsWidget, function(...args) {
const chosenDimension = args[0];
if(chosenDimension === "Custom" || chosenDimension === "None") return;
const dimensionValue = DEFAULT_DIMENSIONS_LIST[chosenDimension];
if(!dimensionValue) return;
const [width, height] = dimensionValue.split("x");
widthWidget.callback(width, "customSetOperation");
heightWidget.callback(height, "customSetOperation");
});
if(widthWidget !== false) {
appendWidgetCB(widthWidget, function(...args) {
if(args[1] === "customSetOperation") return;
dimensionsWidget.value = "Custom";
});
}
if(heightWidget !== false) {
appendWidgetCB(heightWidget, function(...args) {
if(args[1] === "customSetOperation") return;
dimensionsWidget.value = "Custom";
});
}
}
const shortenAirCode = input => !input || !input.startsWith('urn:air:') ? input : input.match(/urn:air:.*?:.*?(civitai:\d+@\d+)$/)?.[1] || input;
async function searchNodeHandler(searchNode, searchInputWidget) {
const searchNodeWidgets = searchNode.widgets;
let modelArchWidget = false, modelTypeWidget = false, modelListWidget = false,
defaultWidgetValues = {}, triggerWordsList = {
"civitai:58390@62833": "", "civitai:82098@87153": "", "civitai:122359@135867": "",
"civitai:14171@16677": "mix4", "civitai:13941@16576": "", "civitai:25995@32988": "full body, chibi"
}, embeddingTriggerWordsList = {
"civitai:7808@9208": "easynegative", "civitai:4629@5637": "ng_deepnegative_v1_75t",
"civitai:56519@60938": "negative_hand", "civitai:72437@77169": "BadDream",
"civitai:11772@25820": "verybadimagenegative_v1.3", "civitai:71961@94057": "FastNegativeV2",
};
let isLora = false, isControlNet = false, isEmbedding = false, isVAE = false, modelTypeValue = false;
if(searchNode.comfyClass === RUNWARE_NODE_TYPES.LORASEARCH) isLora = true;
if(searchNode.comfyClass === RUNWARE_NODE_TYPES.CONTROLNET) isControlNet = true;
if(searchNode.comfyClass === RUNWARE_NODE_TYPES.EMBEDDING) isEmbedding = true;
if(searchNode.comfyClass === RUNWARE_NODE_TYPES.VAE) isVAE = true;
for(const searchWidget of searchNodeWidgets) {
const widgetName = searchWidget.name;
const widgetType = searchWidget.type;
if(widgetName === "Model Architecture" && widgetType === "combo") {
modelArchWidget = searchWidget;
defaultWidgetValues["modelArch"] = searchWidget.options.values;
}
if(MODEL_TYPES_TERMS.includes(widgetName) && widgetType === "combo") {
modelTypeWidget = searchWidget;
defaultWidgetValues["modelType"] = searchWidget.options.values;
}
if(MODEL_LIST_TERMS.includes(widgetName) && widgetType === "combo") {
modelListWidget = searchWidget;
defaultWidgetValues["modelList"] = searchWidget.options.values;
}
}
function resetValues() {
if(modelArchWidget) {
modelArchWidget.options.values = defaultWidgetValues["modelArch"];
modelArchWidget.value = defaultWidgetValues["modelArch"][0];
}
if(modelTypeWidget) {
modelTypeWidget.options.values = defaultWidgetValues["modelType"];
modelTypeWidget.value = defaultWidgetValues["modelType"][0];
}
if(modelListWidget) {
modelListWidget.options.values = defaultWidgetValues["modelList"];
modelListWidget.value = defaultWidgetValues["modelList"][0];
}
}
async function searchModels(exactQuery = null, returnOutput = false) {
let searchQuery;
if(exactQuery) {
searchQuery = exactQuery;
} else {
searchQuery = searchInputWidget.value.trim();
}
searchQuery = shortenAirCode(searchQuery);
const modelArchValue = DEFAULT_MODELS_ARCH_LIST[modelArchWidget.value];
if(isControlNet) {
modelTypeValue = DEFAULT_CONTROLNET_CONDITIONING_LIST[modelTypeWidget.value];
} else {
if(isEmbedding) {
modelTypeValue = "embeddings";
} else if(isVAE) {
modelTypeValue = "vae";
} else {
modelTypeValue = modelTypeWidget.value.toLowerCase().replace("model", "").trim();
}
}
let modelSearchResults = null;
if(isControlNet) {
modelSearchResults = await runwareLocalAPI.modelSearch(searchQuery, modelArchValue, "", "controlnet", modelTypeValue);
} else if(isLora || isEmbedding || isVAE) {
modelSearchResults = await runwareLocalAPI.modelSearch(searchQuery, modelArchValue, "", modelTypeValue);
} else {
modelSearchResults = await runwareLocalAPI.modelSearch(searchQuery, modelArchValue, modelTypeValue);
}
if(modelSearchResults.success) {
const modelListArray = [];
modelSearchResults.modelList.forEach(modelObj => {
if(isLora) triggerWordsList[modelObj.air] = modelObj.positiveTriggerWords?.trim() || false;
if(isEmbedding) embeddingTriggerWordsList[modelObj.air] = modelObj.positiveTriggerWords?.trim() || false;
modelListArray.push(`${modelObj.air} (${modelObj.name} ${modelObj.version})`);
});
if(exactQuery) {
const extraSearch = await searchModels(null, true);
if(extraSearch) {
const newModelList = [...new Set([...modelListArray, ...extraSearch])];
modelListWidget.options.values = newModelList;
return;
}
}
if(returnOutput) return modelListArray;
modelListWidget.options.values = modelListArray;
modelListWidget.value = modelListArray[0];
} else {
if(returnOutput) return false;
if(exactQuery) {
notifyUser("Failed To Load Workflow's Model List Value!", "error", "Runware Search");
return;
}
notifyUser(modelSearchResults.error, "error", "Runware Search");
}
}
function findTargetWidget(currentNode, targetWidgetName, depth = 1) {
try {
if(depth < 0) return false;
const nodeOutputs = currentNode.outputs;
if(nodeOutputs.length === 0) return false;
const outputLinks = nodeOutputs[0].links;
if(outputLinks.length === 0) return false;
for(const linkID of outputLinks) {
const linkInfo = app.graph.links[linkID];
const linkNodeID = linkInfo.target_id;
if(!linkNodeID) continue;
const targetNode = app.graph.getNodeById(linkNodeID);
let widgetFound = false;
if(targetNode.widgets !== undefined && targetNode.widgets.length > 0){
widgetFound = targetNode.widgets.find(widget => widget.name === targetWidgetName) || false;
}
if(widgetFound) {
return widgetFound;
} else {
return findTargetWidget(targetNode, targetWidgetName, depth - 1);
}
}
} catch(e) {
return false;
}
return false;
}
if(isLora) {
const runwareButton = document.createElement("button");
runwareButton.textContent = "Add Lora To Prompt";
runwareButton.style = "max-height: 50px; background-color: #333; color: #ccc;";
searchNode.addDOMWidget("addLora", "custom", runwareButton, {
selectOn: ['focus', 'click'],
});
runwareButton.addEventListener("click", async () => {
const chosenLora = modelListWidget.value.split(" ")[0];
if(!triggerWordsList.hasOwnProperty(chosenLora)) return;
const triggerWords = triggerWordsList[chosenLora];
if(triggerWords.length > 0) {
const positivePromptWidget = findTargetWidget(searchNode, "positivePrompt");
if(!positivePromptWidget) {
notifyUser("Lora Node Is Not Linked To Any Runware Inference Node!", "error", "Runware Lora Connector");
return;
}
const positivePromptWithTrigger = addTriggerWords(positivePromptWidget.value, triggerWords);
if(positivePromptWidget.value === positivePromptWithTrigger) {
notifyUser("Trigger Words Already Exists", "info", "Runware Lora Connector");
return;
}
positivePromptWidget.value = positivePromptWithTrigger;
notifyUser("Trigger Words Added Successfully!", "success", "Runware Lora Connector");
} else {
notifyUser("No Trigger Words Found For This Lora!", "warn", "Runware Lora Connector");
}
});
} else if(isEmbedding) {
const runwareButton = document.createElement("button");
runwareButton.textContent = "Add Embedding To Negative Prompt";
runwareButton.style = "max-height: 50px; background-color: #333; color: #ccc;";
searchNode.addDOMWidget("addEmbedding", "custom", runwareButton, {
selectOn: ['focus', 'click'],
});
runwareButton.addEventListener("click", async () => {
const chosenEmbedding = modelListWidget.value.split(" ")[0];
if (!embeddingTriggerWordsList.hasOwnProperty(chosenEmbedding)) return;
const triggerWords = embeddingTriggerWordsList[chosenEmbedding];
if(triggerWords.length > 0) {
const negativePromptWidget = findTargetWidget(searchNode, "negativePrompt");
if(!negativePromptWidget) {
notifyUser("Embedding Node Is Not Linked To Any Runware Inference Node!", "error", "Runware Embedding Connector");
return;
}
const negativePromptWithTrigger = addTriggerWords(negativePromptWidget.value, triggerWords);
if(negativePromptWidget.value === negativePromptWithTrigger) {
notifyUser("Trigger Words Already Exists", "info", "Runware Embedding Connector");
return;
}
negativePromptWidget.value = negativePromptWithTrigger;
notifyUser("Trigger Words Added Successfully!", "success", "Runware Embedding Connector");
} else {
notifyUser("No Trigger Words Found For This Embedding!", "warn", "Runware Embedding Connector");
}
});
}
appendWidgetCB(searchInputWidget, async function(...args) {
let searchQuery = args[0].trim();
const shortenSearchQuery = shortenAirCode(searchQuery);
if(searchQuery !== shortenSearchQuery) {
searchQuery = shortenSearchQuery;
searchInputWidget.value = searchQuery;
}
if(searchQuery.length === 0) {
resetValues();
} else if(searchQuery.length < 2) {
notifyUser("Invalid Search Value, Search Query must be at least 2 characters!", "error", "Runware Search");
return;
} else {
await searchModels();
}
});
appendWidgetCB(modelArchWidget, async function(...args) {
await searchModels();
});
if(!isVAE && !isEmbedding) {
appendWidgetCB(modelTypeWidget, async function(...args) {
await searchModels();
});
}
appendWidgetCB(searchNode, async function(...args) {
try {
let modelListValues = modelListWidget.options.values;
if(modelListValues.length <= 0) return;
modelListValues = modelListValues.map(model => model.split(" ")[0]);
const modelListCRValue = modelListWidget.value.split(" ")[0];
if(!modelListValues.includes(modelListCRValue)) {
searchModels(modelListCRValue);
}
} catch(e) {}
});
}
function toggleWidgetEnabled(widget, enabled, node) {
if (!widget || !widget.name) return;
// Use the same simple approach as videoInferenceDimensionsHandler
// Set widget disabled property
widget.disabled = !enabled;
// Disable/enable widgets using inputEl if available (same pattern as videoInferenceDimensionsHandler)
if (widget.inputEl) {
widget.inputEl.disabled = !enabled;
widget.inputEl.style.opacity = enabled ? "1" : "0.5";
widget.inputEl.style.cursor = enabled ? "text" : "not-allowed";
widget.inputEl.readOnly = !enabled;
}
// For combo/dropdown widgets, also try to disable the options element
if (widget.options && widget.options.element) {
widget.options.element.disabled = !enabled;
widget.options.element.style.opacity = enabled ? "1" : "0.5";
widget.options.element.style.pointerEvents = enabled ? "auto" : "none";
}
// Fallback: try to find inputs via DOM if inputEl is not available (same as videoInferenceDimensionsHandler)
if (!widget.inputEl && node) {
const nodeElement = node.htmlElements?.widgetsContainer || node.htmlElements;
if (nodeElement) {
const input = nodeElement.querySelector(`input[name="${widget.name}"], textarea[name="${widget.name}"], select[name="${widget.name}"]`);
if (input) {
input.disabled = !enabled;
input.style.opacity = enabled ? "1" : "0.5";
input.style.cursor = enabled ? "text" : "not-allowed";
input.readOnly = !enabled;
if (input.tagName === "SELECT") {
input.style.pointerEvents = enabled ? "auto" : "none";
}
}
}
}
}
function videoUpscalerToggleHandler(videoUpscalerNode) {
if (!videoUpscalerNode?.widgets) return;
const useUpscaleFactorWidget = videoUpscalerNode.widgets.find(w => w && w.name === "useUpscaleFactor");
const upscaleFactorWidget = videoUpscalerNode.widgets.find(w => w && w.name === "upscaleFactor");
const useFpsWidget = videoUpscalerNode.widgets.find(w => w && w.name === "useFps");
const fpsWidget = videoUpscalerNode.widgets.find(w => w && w.name === "fps");
const useDimensionWidget = videoUpscalerNode.widgets.find(w => w && w.name === "useDimension");
const widthWidget = videoUpscalerNode.widgets.find(w => w && w.name === "width");
const heightWidget = videoUpscalerNode.widgets.find(w => w && w.name === "height");
function applyToggleState() {
if (useUpscaleFactorWidget && upscaleFactorWidget) {
const enabled = useUpscaleFactorWidget.value === true;
toggleWidgetEnabled(upscaleFactorWidget, enabled, videoUpscalerNode);
}
if (useFpsWidget && fpsWidget) {
const enabled = useFpsWidget.value === true;
toggleWidgetEnabled(fpsWidget, enabled, videoUpscalerNode);
}
if (useDimensionWidget && widthWidget && heightWidget) {
const enabled = useDimensionWidget.value === "custom";
toggleWidgetEnabled(widthWidget, enabled, videoUpscalerNode);
toggleWidgetEnabled(heightWidget, enabled, videoUpscalerNode);
}
videoUpscalerNode.setDirtyCanvas(true);
}
// Initialize state once widgets are rendered
setTimeout(applyToggleState, 100);
if (useUpscaleFactorWidget) {
appendWidgetCB(useUpscaleFactorWidget, () => {
setTimeout(applyToggleState, 50);
});
}
if (useFpsWidget) {
appendWidgetCB(useFpsWidget, () => {
setTimeout(applyToggleState, 50);
});
}
if (useDimensionWidget) {
appendWidgetCB(useDimensionWidget, () => {
setTimeout(applyToggleState, 50);
});
}
}
function useParameterToggleHandler(node) {
// Prevent double registration
if (node._useParameterToggleHandlerRegistered) return;
node._useParameterToggleHandlerRegistered = true;
// Define explicit mappings: "useParameterName" -> ["parameter1", "parameter2", ...]
const parameterMappings = {
// Image Inference
"useSteps": ["steps"],
"useSeed": ["seed"],
"useCFGScale": ["cfgScale"], // Image inference uses lowercase cfgScale
"useScheduler": ["scheduler"],
"useClipSkip": ["clipSkip"],
"useUpscaleFactor": ["upscaleFactor"],
// Video Inference
"useCustomDimensions": ["width", "height"], // Note: Also handled separately in videoInferenceDimensionsHandler
"useDuration": ["duration"],
"useFps": ["fps"],
"useSchedulers": ["scheduler"],
"useCFGScale": ["cfgScale"],
// useSteps and useSeed are same as image inference, handled by fallback
// Upscaler specific mappings (override for nodes that have CFGScale with capital C)
"usePrompts": ["positivePrompt", "negativePrompt"],
"useClarityParams": ["controlNetWeight", "strength", "scheduler"],
"useCCSRParams": ["colorFix", "tileDiffusion"],
"useLatentParams": ["clipSkip"],
// Audio Inference
"usePositivePrompt": ["positivePrompt"],
"useSeed": ["seed"],
"useSteps": ["steps"],
"useStrength": ["strength"],
// Accelerator Options
"useCacheDistance": ["cacheDistance"],
"useTeaCacheDistance": ["teaCacheDistance"],
"useDeepCacheOptions": ["deepCacheInterval", "deepCacheBranchId"],
"useCacheSteps": ["cacheStartStep", "cacheEndStep"],
"useCachePercentageSteps": ["cacheStartStepPercentage", "cacheEndStepPercentage"],
"useCacheMaxConsecutiveSteps": ["cacheMaxConsecutiveSteps"],
// Bytedance Provider Settings
"useCameraFixed": ["cameraFixed"],
"useMaxSequentialImages": ["maxSequentialImages"],
"useFastMode": ["fastMode"],
// OpenAI Provider Settings (these are dropdowns, not booleans, but handle them anyway)
"useBackground": ["background"],
"useStyle": ["style"],
// Mask Margin
"Mask Margin": ["maskMargin"],
};
// Node-specific overrides for parameters that have different names in different nodes
// Format: nodeClass -> { "useParam": ["param1", "param2"] }
const nodeSpecificMappings = {
// Upscaler uses CFGScale (capital C) instead of cfgScale
[RUNWARE_NODE_TYPES.UPSCALER]: {
"useCFGScale": ["CFGScale"],
},
// Audio Inference uses CFGScale (capital C)
[RUNWARE_NODE_TYPES.AUDIOINFERENCE]: {
"useCFGScale": ["CFGScale"],
},
};
// Wait for widgets to be ready
function initializeHandler() {
if (!node.widgets || node.widgets.length === 0) {
setTimeout(initializeHandler, 100);
return;
}
// Find all "use" widgets and their corresponding parameter widgets upfront (like videoInferenceDimensionsHandler does)
const togglePairs = [];
// Find all "use" widgets
node.widgets.forEach(widget => {
if (!widget || !widget.name) return;
const isUseWidget = widget.name.startsWith("use") && (widget.type === "BOOLEAN" || widget.type === "COMBO");
const isMaskMargin = widget.name === "Mask Margin" && widget.type === "BOOLEAN";
if (!isUseWidget && !isMaskMargin) return;
const useParamName = widget.name;
// Get corresponding parameters - check node-specific mappings first, then general mappings
let paramNames = [];
const nodeClass = node.comfyClass;
if (nodeClass && nodeSpecificMappings[nodeClass] && nodeSpecificMappings[nodeClass][useParamName]) {
paramNames = nodeSpecificMappings[nodeClass][useParamName];
} else {
paramNames = parameterMappings[useParamName] || [];
}
// Handle special case: remove "use" prefix and lowercase first letter
if (paramNames.length === 0) {
const paramName = useParamName.replace(/^use/, "").replace(/^[A-Z]/, (match) => match.toLowerCase());
paramNames = [paramName];
}
// Find the actual parameter widgets
const paramWidgets = [];
paramNames.forEach(paramName => {
const paramWidget = node.widgets.find(w => w && w.name === paramName);
if (paramWidget) {
paramWidgets.push(paramWidget);
} else {
// If mapped parameter doesn't exist, try fallback auto-detection
const fallbackParamName = useParamName.replace(/^use/, "").replace(/^[A-Z]/, (match) => match.toLowerCase());
if (fallbackParamName !== paramName) {
const fallbackWidget = node.widgets.find(w => w && w.name === fallbackParamName);
if (fallbackWidget) {
paramWidgets.push(fallbackWidget);
}
}
}
});
if (paramWidgets.length > 0) {
togglePairs.push({
useWidget: widget,
paramWidgets: paramWidgets
});
}
});
// Create toggle functions for each pair (like toggleDimensionsEnabled in videoInferenceDimensionsHandler)
togglePairs.forEach(pair => {
const { useWidget, paramWidgets } = pair;
function toggleEnabled() {
// Determine if enabled based on widget type
let enabled = false;
if (useWidget.type === "BOOLEAN") {
enabled = useWidget.value === true;
} else if (useWidget.type === "COMBO") {
enabled = useWidget.value === "enable" || useWidget.value === "Enable";
}
// Apply to each parameter widget (exactly like toggleDimensionsEnabled does)
paramWidgets.forEach(paramWidget => {
if (paramWidget.inputEl) {
paramWidget.inputEl.disabled = !enabled;
paramWidget.inputEl.style.opacity = enabled ? "1" : "0.5";
paramWidget.inputEl.style.cursor = enabled ? "text" : "not-allowed";
paramWidget.inputEl.readOnly = !enabled;
}
paramWidget.disabled = !enabled;
// Fallback: try to find inputs via DOM if inputEl is not available
if (!paramWidget.inputEl) {
const nodeElement = node.htmlElements?.widgetsContainer || node.htmlElements;
if (nodeElement) {
const input = nodeElement.querySelector(`input[name="${paramWidget.name}"], textarea[name="${paramWidget.name}"], select[name="${paramWidget.name}"]`);
if (input) {
input.disabled = !enabled;
input.style.opacity = enabled ? "1" : "0.5";
input.style.cursor = enabled ? "text" : "not-allowed";
input.readOnly = !enabled;
if (input.tagName === "SELECT") {
input.style.pointerEvents = enabled ? "auto" : "none";
}
}
}
}
});
node.setDirtyCanvas(true);
}
// Set up callback (exactly like videoInferenceDimensionsHandler does)
appendWidgetCB(useWidget, () => {
setTimeout(toggleEnabled, 50);
});
// Initial call to set initial state
setTimeout(toggleEnabled, 50);
});
}
// Start initialization
setTimeout(initializeHandler, 200);
}
function upscalerToggleHandler(upscalerNode) {
// Find all "use" parameter widgets for Upscaler
const useUpscaleFactorWidget = upscalerNode.widgets.find(w => w.name === "useUpscaleFactor");
const upscaleFactorWidget = upscalerNode.widgets.find(w => w.name === "upscaleFactor");
const useStepsWidget = upscalerNode.widgets.find(w => w.name === "useSteps");
const stepsWidget = upscalerNode.widgets.find(w => w.name === "steps");
const useSeedWidget = upscalerNode.widgets.find(w => w.name === "useSeed");
const seedWidget = upscalerNode.widgets.find(w => w.name === "seed");
const useCFGScaleWidget = upscalerNode.widgets.find(w => w.name === "useCFGScale");
const cfgScaleWidget = upscalerNode.widgets.find(w => w.name === "CFGScale");