-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathapp.ts
More file actions
2471 lines (2215 loc) · 80.3 KB
/
Copy pathapp.ts
File metadata and controls
2471 lines (2215 loc) · 80.3 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 { useEventListener, useResizeObserver } from '@vueuse/core'
import _ from 'es-toolkit/compat'
import type { ToastMessageOptions } from 'primevue/toast'
import { reactive, unref } from 'vue'
import { shallowRef } from 'vue'
import { useCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion'
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
import { syncLayoutStoreNodeBoundsFromGraph } from '@/renderer/core/layout/sync/syncLayoutStoreFromGraph'
import { flushScheduledSlotLayoutSync } from '@/renderer/extensions/vueNodes/composables/useSlotElementTracking'
import { promotedInputSource } from '@/core/graph/subgraph/promotedInputWidget'
import { resolveConcretePromotedWidget } from '@/core/graph/subgraph/resolveConcretePromotedWidget'
import { resolveNodeDefText, setBackendNodeText, st, t } from '@/i18n'
import { normalizeI18nKey } from '@/utils/formatUtil'
import { ChangeTracker } from '@/scripts/changeTracker'
import type { IContextMenuValue } from '@/lib/litegraph/src/interfaces'
import {
inputAsSerialisable,
LGraph,
LGraphCanvas,
LGraphNode,
LiteGraph
} from '@/lib/litegraph/src/litegraph'
import { snapPoint } from '@/lib/litegraph/src/measure'
import type { Vector2 } from '@/lib/litegraph/src/litegraph'
import type {
IBaseWidget,
TWidgetValue
} from '@/lib/litegraph/src/types/widgets'
import { LGraphEventMode } from '@/lib/litegraph/src/types/globalEnums'
import { useFreeTierQuota } from '@/platform/cloud/subscription/composables/useFreeTierQuota'
import { isCloud } from '@/platform/distribution/types'
import { useSettingStore } from '@/platform/settings/settingStore'
import { useTelemetry } from '@/platform/telemetry'
import { installNodeAddedTelemetry } from '@/platform/telemetry/nodeAdded/installNodeAddedTelemetry'
import { normalizeExecutionTriggerSource } from '@/platform/telemetry/types'
import { getExecutionContext } from '@/platform/telemetry/utils/getExecutionContext'
import { groupMissingNodesByPack } from '@/platform/telemetry/utils/groupMissingNodesByPack'
import { toWorkflowExecutionContext } from '@/platform/telemetry/utils/workflowExecutionContext'
import type {
ExecutionContext,
WorkflowExecutionContext,
WorkflowExecutionIntent,
WorkflowOpenSource,
WorkflowQueueIntent
} from '@/platform/telemetry/types'
import { useToastStore } from '@/platform/updates/common/toastStore'
import { updatePendingWarnings } from '@/platform/workflow/core/utils/pendingWarnings'
import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
import { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation'
import type {
ComfyApiWorkflow,
ComfyWorkflowJSON
} from '@/platform/workflow/validation/schemas/workflowSchema'
import { toNodeId } from '@/types/nodeId'
import type { SerializedNodeId } from '@/types/nodeId'
import {
collectSubgraphDefinitions,
buildSubgraphExecutionPaths
} from '@/platform/workflow/core/utils/workflowFlattening'
import type { FlattenableWorkflowNode } from '@/platform/workflow/core/utils/workflowFlattening'
import type {
ExecutionErrorWsMessage,
NodeError,
NodeExecutionOutput,
ResultItem
} from '@/schemas/apiSchema'
import {
type ComfyNodeDef as ComfyNodeDefV1,
isComboInputSpecV1,
isComboInputSpecV2
} from '@/schemas/nodeDefSchema'
import {
type BaseDOMWidget,
ComponentWidgetImpl,
DOMWidgetImpl
} from '@/scripts/domWidget'
import { useAccountPreconditionDialog } from '@/platform/cloud/subscription/composables/useAccountPreconditionDialog'
import { resolveAccountPrecondition } from '@/platform/errorCatalog/accountPreconditionRouting'
import { useDialogService } from '@/services/dialogService'
import { useExtensionService } from '@/services/extensionService'
import { useLitegraphService } from '@/services/litegraphService'
import { useSubgraphService } from '@/services/subgraphService'
import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
import { useCommandStore } from '@/stores/commandStore'
import { useDomWidgetStore } from '@/stores/domWidgetStore'
import { useExecutionStore } from '@/stores/executionStore'
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
import { useExtensionStore } from '@/stores/extensionStore'
import { useAuthStore } from '@/stores/authStore'
import { useNodeOutputStore } from '@/stores/nodeOutputStore'
import { useJobPreviewStore } from '@/stores/jobPreviewStore'
import {
getAncestorExecutionIds,
tryNormalizeNodeExecutionId
} from '@/types/nodeIdentification'
import { KeyComboImpl } from '@/platform/keybindings/keyCombo'
import { useKeybindingStore } from '@/platform/keybindings/keybindingStore'
import { SYSTEM_NODE_DEFS, useNodeDefStore } from '@/stores/nodeDefStore'
import { useNodeReplacementStore } from '@/platform/nodeReplacement/nodeReplacementStore'
import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore'
import { useSubgraphStore } from '@/stores/subgraphStore'
import { useWidgetStore } from '@/stores/widgetStore'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { useWorkspaceStore } from '@/stores/workspaceStore'
import type { ComfyExtension, MissingNodeType } from '@/types/comfy'
import type { ExtensionManager } from '@/types/extensionTypes'
import type { NodeExecutionId } from '@/types/nodeIdentification'
import { normalizePromptError } from '@/utils/executionErrorUtil'
import { graphToPrompt } from '@/utils/executionUtil'
import { parseJsonWithNonFinite } from '@/utils/jsonUtil'
import { getCnrIdFromProperties } from '@/platform/nodeReplacement/cnrIdUtil'
import { useMissingNodesErrorStore } from '@/platform/nodeReplacement/missingNodesErrorStore'
import { rescanAndSurfaceMissingNodes } from '@/platform/nodeReplacement/missingNodeScan'
import {
refreshMissingModelPipeline,
runMissingModelPipeline
} from '@/platform/missingModel/missingModelPipeline'
import type { MissingModelPipelineResult } from '@/platform/missingModel/missingModelPipeline'
import { useMissingModelStore } from '@/platform/missingModel/missingModelStore'
import { runMissingMediaPipeline } from '@/platform/missingMedia/missingMediaPipeline'
import { useMissingMediaStore } from '@/platform/missingMedia/missingMediaStore'
import { getWorkflowMode } from '@/utils/appMode'
import { anyItemOverlapsRect } from '@/utils/mathUtil'
import { createUuidv4, zeroUuid } from '@/utils/uuid'
import {
collectAllNodes,
forEachNode,
getNodeByExecutionId,
isAncestorPathActive,
triggerCallbackOnAllNodes
} from '@/utils/graphTraversalUtil'
import {
executeWidgetsCallback,
createNode,
fixLinkInputSlots,
isImageNode,
isVideoNode
} from '@/utils/litegraphUtil'
import {
createSharedObjectUrl,
releaseSharedObjectUrl
} from '@/utils/objectUrlUtil'
import {
findLegacyRerouteNodes,
noNativeReroutes
} from '@/utils/migration/migrateReroute'
import { deserialiseAndCreate } from '@/utils/vintageClipboard'
import { type ComfyApi, PromptExecutionError, api } from './api'
import { defaultGraph } from './defaultGraph'
import { importA1111 } from './pnginfo'
import { applyPromotedWidgetControl } from './promotedWidgetControl'
import { $el, ComfyUI } from './ui'
import { ComfyAppMenu } from './ui/menu/index'
import { clone } from './utils'
import { type ComfyWidgetConstructor } from './widgets'
import { ensureCorrectLayoutScale } from '@/renderer/extensions/vueNodes/layout/ensureCorrectLayoutScale'
import {
extractFilesFromDragEvent,
hasAudioType,
hasImageType,
hasVideoType,
isMediaFile
} from '@/utils/eventUtils'
import { getWorkflowDataFromFile } from '@/scripts/metadata/parser'
import { SUPPORTED_MESH_EXTENSIONS } from '@/extensions/core/load3d/constants'
import Load3dUtils from '@/extensions/core/load3d/Load3dUtils'
import {
pasteAudioNode,
pasteAudioNodes,
pasteImageNode,
pasteImageNodes,
pasteVideoNode,
pasteVideoNodes
} from '@/composables/usePaste'
export const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview'
function isMeshModelFile(file: File): boolean {
const name = file.name.toLowerCase()
return SUPPORTED_MESH_EXTENSIONS.has(name.slice(name.lastIndexOf('.')))
}
export function sanitizeNodeName(string: string) {
let entityMap = {
'&': '',
'<': '',
'>': '',
'"': '',
"'": '',
'`': '',
'=': ''
}
return String(string).replace(/[&<>"'`=]/g, function fromEntityMap(s) {
return entityMap[s as keyof typeof entityMap]
})
}
function syncPromotedComboHostOptions(rootGraph: LGraph): void {
const widgetValueStore = useWidgetValueStore()
forEachNode(rootGraph, (node) => {
if (!node.isSubgraphNode()) return
for (const input of node.inputs) {
if (!input.widgetId) continue
const source = promotedInputSource(node, input)
if (!source) continue
const resolution = resolveConcretePromotedWidget(
node,
source.nodeId,
source.widgetName
)
if (resolution.status !== 'resolved') continue
const sourceWidget = resolution.resolved.widget
if (sourceWidget.type !== 'combo') continue
const state = widgetValueStore.getWidget(input.widgetId)
if (!state) continue
state.options = { ...(sourceWidget.options ?? {}) }
}
})
}
type Clipspace = {
widgets?: Pick<IBaseWidget, 'type' | 'name' | 'value'>[] | null
imgs?: HTMLImageElement[] | null
original_imgs?: HTMLImageElement[] | null
images?: ResultItem[] | null
selectedIndex: number
img_paste_mode: string
paintedIndex: number
combinedIndex: number
}
/**
* Optional inputs to {@link ComfyApp.queuePrompt}. `intent` is telemetry
* attribution only and never affects what gets executed.
*/
export interface QueuePromptOptions {
queueNodeIds?: NodeExecutionId[]
intent?: WorkflowQueueIntent
}
export class ComfyApp {
/**
* List of entries to queue
*/
private queueItems: {
number: number
batchCount: number
requestId: number
queueNodeIds?: NodeExecutionId[]
workflowQueueIntent?: WorkflowQueueIntent
}[] = []
private nextQueueRequestId = 1
/**
* If the queue is currently being processed
*/
private processingQueue: boolean = false
/**
* Content Clipboard
* @type {serialized node object}
*/
static clipspace: Clipspace | null = null
static clipspace_invalidate_handler: (() => void) | null = null
static open_maskeditor: (() => void) | null = null
static maskeditor_is_opended: (() => void) | null = null
static clipspace_return_node = null
vueAppReady: boolean
api: ComfyApi
ui: ComfyUI
extensionManager!: ExtensionManager
private _nodeOutputs!: Record<string, NodeExecutionOutput>
nodePreviewImages: Record<string, string[]>
private rootGraphInternal: LGraph | undefined
// TODO: Migrate internal usage to the
/** @deprecated Use {@link rootGraph} instead */
get graph() {
return this.rootGraphInternal!
}
get rootGraph(): LGraph {
if (!this.rootGraphInternal) {
console.error('ComfyApp graph accessed before initialization')
}
return this.rootGraphInternal!
}
/** Whether the root graph has been initialized. Safe to check without triggering error logs. */
get isGraphReady(): boolean {
return !!this.rootGraphInternal
}
canvas!: LGraphCanvas
dragOverNode: Pick<LGraphNode, 'onDragDrop' | 'id'> | null = null
readonly canvasElRef = shallowRef<HTMLCanvasElement>()
get canvasEl() {
// TODO: Fix possibly undefined reference
return unref(this.canvasElRef)!
}
private configuringGraphLevel: number = 0
get configuringGraph() {
return this.configuringGraphLevel > 0
}
ctx!: CanvasRenderingContext2D
bodyTop: HTMLElement
bodyLeft: HTMLElement
bodyRight: HTMLElement
bodyBottom: HTMLElement
canvasContainer: HTMLElement
menu: ComfyAppMenu
// Set by Comfy.Clipspace extension
openClipspace: () => void = () => {}
private positionConversion?: {
clientPosToCanvasPos: (pos: Vector2) => Vector2
canvasPosToClientPos: (pos: Vector2) => Vector2
}
/**
* The node errors from the previous execution.
* @deprecated Use app.extensionManager.lastNodeErrors instead
*/
get lastNodeErrors(): Record<string, NodeError> | null {
return useExecutionErrorStore().lastNodeErrors
}
/**
* The error from the previous execution.
* @deprecated Use app.extensionManager.lastExecutionError instead
*/
get lastExecutionError(): ExecutionErrorWsMessage | null {
return useExecutionErrorStore().lastExecutionError
}
/**
* @deprecated Use useExecutionStore().executingNodeId instead
* TODO: Update to support multiple executing nodes. This getter returns only the first executing node.
* Consider updating consumers to handle multiple nodes or use executingNodeIds array.
*/
get runningNodeId(): SerializedNodeId | null {
return useExecutionStore().executingNodeId
}
/**
* @deprecated Use useWorkspaceStore().shiftDown instead
*/
get shiftDown(): boolean {
return useWorkspaceStore().shiftDown
}
/**
* @deprecated Use useWidgetStore().widgets instead
*/
get widgets(): Record<string, ComfyWidgetConstructor> {
return Object.fromEntries(useWidgetStore().widgets.entries())
}
/**
* @deprecated storageLocation is always 'server' since
* https://github.com/comfyanonymous/ComfyUI/commit/53c8a99e6c00b5e20425100f6680cd9ea2652218
*/
get storageLocation() {
return 'server'
}
/**
* @deprecated storage migration is no longer needed.
*/
get isNewUserSession() {
return false
}
/**
* @deprecated Use useExtensionStore().extensions instead
*/
get extensions(): ComfyExtension[] {
return useExtensionStore().extensions
}
/**
* The progress on the current executing node, if the node reports any.
* @deprecated Use useExecutionStore().executingNodeProgress instead
*/
get progress() {
return useExecutionStore()._executingNodeProgress
}
/**
* @deprecated Use {@link isImageNode} from @/utils/litegraphUtil instead
*/
static isImageNode(node: LGraphNode) {
return isImageNode(node)
}
/**
* Resets the canvas view to the default
* @deprecated Use {@link useLitegraphService().resetView} instead
*/
resetView() {
useLitegraphService().resetView()
}
constructor() {
this.vueAppReady = false
this.ui = new ComfyUI(this)
this.api = api
// Dummy placeholder elements before GraphCanvas is mounted.
this.bodyTop = $el('div.comfyui-body-top')
this.bodyLeft = $el('div.comfyui-body-left')
this.bodyRight = $el('div.comfyui-body-right')
this.bodyBottom = $el('div.comfyui-body-bottom')
this.canvasContainer = $el('div.graph-canvas-container')
this.menu = new ComfyAppMenu(this)
/**
* Stores the execution output data for each node
* @type {Record<string, any>}
*/
this.nodeOutputs = {}
/**
* Stores the preview image data for each node
* @type {Record<string, Image>}
*/
this.nodePreviewImages = {}
}
get nodeOutputs() {
return this._nodeOutputs
}
set nodeOutputs(value) {
this._nodeOutputs = value
if (this.vueAppReady)
useExtensionService().invokeExtensions('onNodeOutputsUpdated', value)
}
/**
* If the user has specified a preferred format to receive preview images in,
* this function will return that format as a url query param.
* If the node's outputs are not images, this param should not be used, as it will
* force the server to load the output file as an image.
*/
getPreviewFormatParam() {
let preview_format = useSettingStore().get('Comfy.PreviewFormat')
if (preview_format) return `&preview=${preview_format}`
else return ''
}
getRandParam() {
if (isCloud) return ''
return '&rand=' + Math.random()
}
static onClipspaceEditorSave() {
if (ComfyApp.clipspace_return_node) {
ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)
}
}
static onClipspaceEditorClosed() {
ComfyApp.clipspace_return_node = null
}
static copyToClipspace(node: LGraphNode) {
var widgets = null
if (node.widgets) {
widgets = node.widgets.map(({ type, name, value }) => ({
type,
name,
value
}))
}
var imgs = undefined
var orig_imgs = undefined
if (node.imgs != undefined) {
imgs = []
orig_imgs = []
for (let i = 0; i < node.imgs.length; i++) {
imgs[i] = new Image()
imgs[i].src = node.imgs[i].src
orig_imgs[i] = imgs[i]
}
}
var selectedIndex = 0
if (node.imageIndex) {
selectedIndex = node.imageIndex
}
const paintedIndex = imgs ? imgs.length + 1 : 1
const combinedIndex = imgs ? imgs.length + 2 : 2
// for vueNodes mode
const images =
node.images ?? useNodeOutputStore().getNodeOutputs(node)?.images
ComfyApp.clipspace = {
widgets: widgets,
imgs: imgs,
original_imgs: orig_imgs,
images: images,
selectedIndex: selectedIndex,
img_paste_mode: 'selected', // reset to default im_paste_mode state on copy action
paintedIndex: paintedIndex,
combinedIndex: combinedIndex
}
ComfyApp.clipspace_return_node = null
if (ComfyApp.clipspace_invalidate_handler) {
ComfyApp.clipspace_invalidate_handler()
}
}
static pasteFromClipspace(node: LGraphNode) {
if (ComfyApp.clipspace) {
// image paste
let combinedImgSrc: string | undefined
if (
ComfyApp.clipspace.combinedIndex !== undefined &&
ComfyApp.clipspace.imgs &&
ComfyApp.clipspace.combinedIndex < ComfyApp.clipspace.imgs.length
) {
combinedImgSrc =
ComfyApp.clipspace.imgs[ComfyApp.clipspace.combinedIndex].src
}
if (ComfyApp.clipspace.imgs && node.imgs) {
// Update node.images even if it's initially undefined (vueNodes mode)
if (ComfyApp.clipspace.images) {
if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {
node.images = [
ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]
]
} else {
node.images = ComfyApp.clipspace.images
}
if (app.nodeOutputs[node.id + ''])
app.nodeOutputs[node.id + ''].images = node.images
}
if (ComfyApp.clipspace.imgs) {
// deep-copy to cut link with clipspace
if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {
const img = new Image()
img.src =
ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src
node.imgs = [img]
node.imageIndex = 0
} else {
const imgs = []
for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) {
imgs[i] = new Image()
imgs[i].src = ComfyApp.clipspace.imgs[i].src
node.imgs = imgs
}
}
}
}
// Paste the RGB canvas if paintedindex exists
if (
ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.paintedIndex] &&
node.imgs
) {
const paintedImg = new Image()
paintedImg.src =
ComfyApp.clipspace.imgs[ComfyApp.clipspace.paintedIndex].src
node.imgs.push(paintedImg) // Add the RGB canvas to the node's images
}
// Store only combined image inside the node if it exists
if (
ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.combinedIndex] &&
node.imgs &&
combinedImgSrc
) {
const combinedImg = new Image()
combinedImg.src = combinedImgSrc
node.imgs = [combinedImg]
}
if (node.widgets) {
if (ComfyApp.clipspace.images) {
const clip_image =
ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]
const index = node.widgets.findIndex((obj) => obj.name === 'image')
if (index >= 0) {
if (
node.widgets[index].type != 'image' &&
typeof node.widgets[index].value == 'string' &&
clip_image.filename
) {
node.widgets[index].value =
(clip_image.subfolder ? clip_image.subfolder + '/' : '') +
clip_image.filename +
(clip_image.type ? ` [${clip_image.type}]` : '')
} else {
node.widgets[index].value = clip_image
}
}
}
if (ComfyApp.clipspace.widgets && node.widgets) {
ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => {
const prop = node.widgets?.find(
(obj) => obj.type === type && obj.name === name
)
if (prop && prop.type != 'button') {
const valueObj = value as Record<string, unknown> | undefined
if (
prop.type != 'image' &&
typeof prop.value == 'string' &&
valueObj?.filename
) {
const resultItem = value as ResultItem
prop.value =
(resultItem.subfolder ? resultItem.subfolder + '/' : '') +
resultItem.filename +
(resultItem.type ? ` [${resultItem.type}]` : '')
} else {
prop.value = value
prop.callback?.(value)
}
}
})
}
}
app.canvas.setDirty(true)
useNodeOutputStore().updateNodeImages(node)
}
}
/**
* Adds a handler allowing drag+drop of files onto the window to load workflows
*/
private addDropHandler() {
// Get prompt from dropped PNG or json
useEventListener(document, 'drop', async (event: DragEvent) => {
try {
// Skip if already handled (e.g. file drop onto publish dialog tiles)
if (event.defaultPrevented) return
event.preventDefault()
event.stopPropagation()
// graph_mouse is only updated on mousemove, so when files are dragged
// in from another window the canvas-space cursor is stale. Sync it
// from the drop event so nodes created below land at the cursor.
this.canvas.adjustMouseEvent(event)
this.canvas.graph_mouse[0] = event.canvasX
this.canvas.graph_mouse[1] = event.canvasY
const n = this.dragOverNode
this.dragOverNode = null
// Node handles file drop, we dont use the built in onDropFile handler as its buggy
// If you drag multiple files it will call it multiple times with the same file
if (await n?.onDragDrop?.(event)) return
const files = await extractFilesFromDragEvent(event)
if (files.length === 0) return
const workspace = useWorkspaceStore()
try {
workspace.spinner = true
const imageFiles = files.filter(hasImageType)
const audioFiles = files.filter(hasAudioType)
const videoFiles = files.filter(hasVideoType)
const totalMedia =
imageFiles.length + audioFiles.length + videoFiles.length
const hasMultipleMedia = totalMedia > 1
const createdNodes: LGraphNode[] = []
const handleFileOptions = {
deferWarnings: true,
onNodeCreated: (node: LGraphNode) => createdNodes.push(node)
}
if (hasMultipleMedia) {
if (imageFiles.length > 0) {
await this.handleFileList(imageFiles)
}
if (audioFiles.length > 0) {
await this.handleAudioFileList(audioFiles)
}
if (videoFiles.length > 0) {
await this.handleVideoFileList(videoFiles)
}
for (const file of files.filter((f) => !isMediaFile(f))) {
await this.handleFile(file, 'file_drop', handleFileOptions)
}
} else {
for (const file of files) {
await this.handleFile(file, 'file_drop', handleFileOptions)
}
}
this.positionNodes(createdNodes)
} finally {
workspace.spinner = false
}
useWorkflowService().showPendingWarnings()
} catch (error: unknown) {
useToastStore().addAlert(t('toastMessages.dropFileError', { error }))
}
})
// Always clear over node on drag leave
useEventListener(this.canvasElRef, 'dragleave', async () => {
if (!this.dragOverNode) return
this.dragOverNode = null
this.canvas.setDirty(false, true)
})
// Add handler for dropping onto a specific node
useEventListener(
this.canvasElRef,
'dragover',
(event: DragEvent) => {
this.canvas.adjustMouseEvent(event)
const node = this.canvas.graph?.getNodeOnPos(
event.canvasX,
event.canvasY
)
if (!node?.onDragOver?.(event)) {
this.dragOverNode = null
return
}
this.dragOverNode = node
// dragover event is fired very frequently, run this on an animation frame
requestAnimationFrame(() => {
this.canvas.setDirty(false, true)
})
},
false
)
}
/**
* Handle keypress
*/
private addProcessKeyHandler() {
const origProcessKey = LGraphCanvas.prototype.processKey
LGraphCanvas.prototype.processKey = function (e: KeyboardEvent) {
if (!this.graph) return
if (e.target instanceof Element && e.target.localName == 'input') {
return
}
if (e.type == 'keydown' && !e.repeat) {
const keyCombo = KeyComboImpl.fromEvent(e)
const keybindingStore = useKeybindingStore()
const keybinding = keybindingStore.getKeybinding(keyCombo)
if (
keybinding &&
keybinding.targetElementId === 'graph-canvas-container'
) {
useCommandStore().execute(keybinding.commandId)
this.graph.change()
e.preventDefault()
e.stopImmediatePropagation()
return
}
}
// Fall through to Litegraph defaults
return origProcessKey.apply(this, [e])
}
}
/**
* Handles updates from the API socket
*/
private addApiUpdateHandlers() {
api.addEventListener('status', ({ detail }) => {
this.ui.setStatus(detail)
})
api.addEventListener('progress', () => {
this.canvas.setDirty(true, false)
})
api.addEventListener('executing', () => {
this.canvas.setDirty(true, false)
})
api.addEventListener('executed', ({ detail }) => {
const nodeOutputStore = useNodeOutputStore()
const executionId = tryNormalizeNodeExecutionId(
detail.display_node || detail.node
)
if (!executionId) return
nodeOutputStore.setNodeOutputsByExecutionId(executionId, detail.output, {
merge: detail.merge
})
const node = getNodeByExecutionId(this.rootGraph, executionId)
if (node && node.onExecuted) {
node.onExecuted(detail.output)
}
})
api.addEventListener('execution_start', () => {
triggerCallbackOnAllNodes(this.rootGraph, 'onExecutionStart')
})
api.addEventListener('execution_error', ({ detail }) => {
const precondition = resolveAccountPrecondition({
exceptionType: detail.exception_type ?? '',
exceptionMessage: detail.exception_message ?? ''
})
if (precondition) {
useAccountPreconditionDialog().open(precondition, {
nodeType: detail.node_type
})
} else if (useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')) {
useExecutionErrorStore().showErrorOverlay()
} else {
useDialogService().showExecutionErrorDialog(detail)
}
this.canvas.draw(true, true)
})
api.addEventListener('b_preview_with_metadata', ({ detail }) => {
// Enhanced preview with explicit node context
const { blob, displayNodeId, jobId } = detail
const { setNodePreviewsByExecutionId, revokePreviewsByExecutionId } =
useNodeOutputStore()
const displayNodeExecutionId = tryNormalizeNodeExecutionId(displayNodeId)
if (!displayNodeExecutionId) return
const blobUrl = createSharedObjectUrl(blob)
useJobPreviewStore().setPreviewUrl(jobId, blobUrl, displayNodeId)
// Ensure clean up if `executing` event is missed.
revokePreviewsByExecutionId(displayNodeExecutionId)
// Preview cleanup is handled in progress_state event to support multiple concurrent previews
for (const executionId of getAncestorExecutionIds(
displayNodeExecutionId
)) {
setNodePreviewsByExecutionId(executionId, [blobUrl])
}
releaseSharedObjectUrl(blobUrl)
})
api.addEventListener('feature_flags', () => {
void useNodeReplacementStore().load()
})
api.init()
}
/** Flag that the graph is configuring to prevent nodes from running checks while its still loading */
private addConfigureHandler() {
const app = this
const configure = LGraph.prototype.configure
LGraph.prototype.configure = function (...args) {
app.configuringGraphLevel++
try {
return configure.apply(this, args)
} finally {
app.configuringGraphLevel--
}
}
}
private addAfterConfigureHandler(graph: LGraph) {
const { onConfigure } = graph
graph.onConfigure = function (...args) {
// Set pending sync flag to suppress link rendering until slots are synced
if (LiteGraph.vueNodesMode) {
layoutStore.setPendingSlotSync(true)
}
try {
fixLinkInputSlots(this)
// Fire callbacks before the onConfigure, this is used by widget inputs to setup the config
triggerCallbackOnAllNodes(this, 'onGraphConfigured')
const r = onConfigure?.apply(this, args)
// Fire after onConfigure, used by primitives to generate widget using input nodes config
triggerCallbackOnAllNodes(this, 'onAfterGraphConfigured')
return r
} finally {
// Flush pending slot layout syncs to fix link alignment after undo/redo
// Using finally ensures links aren't permanently suppressed if an error occurs
if (LiteGraph.vueNodesMode) {
flushScheduledSlotLayoutSync()
app.canvas?.setDirty(true, true)
}
}
}
}
/**
* Set up the app on the page
*/
async setup(canvasEl: HTMLCanvasElement) {
this.bodyTop = document.getElementById('comfyui-body-top')!
this.bodyLeft = document.getElementById('comfyui-body-left')!
this.bodyRight = document.getElementById('comfyui-body-right')!
this.bodyBottom = document.getElementById('comfyui-body-bottom')!
this.canvasContainer = document.getElementById('graph-canvas-container')!
this.canvasElRef.value = canvasEl
await useWorkspaceStore().workflow.syncWorkflows()
//Doesn't need to block. Blueprints will load async
void useSubgraphStore().fetchSubgraphs()
await useExtensionService().loadExtensions()
this.addProcessKeyHandler()
this.addConfigureHandler()
this.addApiUpdateHandlers()
const graph = new LGraph()
// Register the subgraph - adds type wrapper for Litegraph's `createNode` factory
graph.events.addEventListener('subgraph-created', (e) => {
try {
const { subgraph, data } = e.detail
useSubgraphService().registerNewSubgraph(subgraph, data)
} catch (err) {
console.error('Failed to register subgraph', err)
useToastStore().add({
severity: 'error',
summary: 'Failed to register subgraph',
detail: err instanceof Error ? err.message : String(err)
})
}
})
this.addAfterConfigureHandler(graph)
this.rootGraphInternal = graph
installNodeAddedTelemetry(graph)
this.canvas = new LGraphCanvas(canvasEl, graph)
// Make canvas states reactive so we can observe changes on them.
this.canvas.state = reactive(this.canvas.state)
this.ctx = canvasEl.getContext('2d')!
LiteGraph.alt_drag_do_clone_nodes = true
LiteGraph.macGesturesRequireMac = false
this.canvas.canvas.addEventListener<'litegraph:set-graph'>(
'litegraph:set-graph',
(e) => {
const { newGraph } = e.detail
const widgetStore = useDomWidgetStore()
const activeWidgets: Record<
string,
BaseDOMWidget<object | string>
> = Object.fromEntries(
newGraph.nodes
.flatMap((node) => node.widgets ?? [])
.filter(
(w) =>
w instanceof DOMWidgetImpl || w instanceof ComponentWidgetImpl
)
.map((w) => [w.id, w])
)
for (const [
widgetId,
widgetState
] of widgetStore.widgetStates.entries()) {
if (widgetId in activeWidgets) {
widgetState.active = true
widgetState.widget = activeWidgets[widgetId]
} else {