Line data Source code
1 : import { defineStore } from 'pinia'
2 :
3 : import { t } from '@/i18n'
4 : import { reportError } from '@comfyorg/telemetry/reportError'
5 : import { SubgraphNode } from '@/lib/litegraph/src/litegraph'
6 : import { useSettingStore } from '@/platform/settings/settingStore'
7 : import { useToast } from '@/components/ui/toast/toastStore'
8 : import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
9 : import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow'
10 : import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow'
11 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
12 : import type {
13 : ComfyNode,
14 : ComfyWorkflowJSON
15 : } from '@comfyorg/graph-model/workflowSchema'
16 : import type { SerializedNodeId } from '@comfyorg/graph-model/nodeId'
17 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
18 : import type { NodeError } from '@comfyorg/api-client/types'
19 : import type {
20 : ComfyNodeDef as ComfyNodeDefV1,
21 : InputSpec
22 : } from '@comfyorg/object-info-parser'
23 : import { isCloud, isDesktop } from '@/platform/distribution/types'
24 : import { TemplateIncludeOnDistributionEnum } from '@comfyorg/api-client/templateTypes'
25 : import { api } from '@/scripts/api'
26 : import type { GlobalSubgraphData } from '@comfyorg/api-client/ComfyApi'
27 : import { useDialogService } from '@/services/dialogService'
28 : import { useExecutionErrorStore } from '@/stores/executionErrorStore'
29 : import { ComfyNodeDefImpl } from '@/core/graph/nodeDef/ComfyNodeDefImpl'
30 : import { useNodeDefStore } from '@/stores/nodeDefStore'
31 : import type { UserFile } from '@/stores/userFileStore'
32 : import { BLUEPRINT_TYPE_PREFIX } from '@/utils/blueprintUtils'
33 : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
34 :
35 1 : async function confirmOverwrite(name: string): Promise<boolean | null> {
36 1 : return await useDialogService().confirm({
37 : title: t('subgraphStore.overwriteBlueprintTitle'),
38 : type: 'overwriteBlueprint',
39 : message: t('subgraphStore.overwriteBlueprint'),
40 : itemList: [name]
41 : })
42 : }
43 :
44 2356 : export const useSubgraphStore = defineStore('subgraph', () => {
45 2355 : class SubgraphBlueprint extends ComfyWorkflow {
46 : static override readonly basePath = 'subgraphs/'
47 : override readonly tintCanvasBg = '#22227740'
48 :
49 : hasPromptedSave: boolean = false
50 :
51 : constructor(
52 : options: { path: string; modified: number; size: number },
53 : confirmFirstSave: boolean = false
54 : ) {
55 262894 : super(options)
56 262894 : this.hasPromptedSave = !confirmFirstSave
57 : }
58 :
59 : validateSubgraph() {
60 9 : if (!this.activeState?.definitions)
61 0 : throw new Error(
62 : 'The root graph of a subgraph blueprint must consist of only a single subgraph node'
63 : )
64 9 : const { subgraphs } = this.activeState.definitions
65 9 : const { nodes } = this.activeState
66 : //Instanceof doesn't function as nodes are serialized
67 9 : function isSubgraphNode(node: ComfyNode) {
68 9 : return subgraphs.some((s) => s.id === node.type)
69 : }
70 9 : if (nodes.length == 1 && isSubgraphNode(nodes[0])) return
71 0 : const errors: Record<SerializedNodeId, NodeError> = {}
72 : //mark errors for all but first subgraph node
73 0 : let firstSubgraphFound = false
74 0 : for (let i = 0; i < nodes.length; i++) {
75 0 : if (!firstSubgraphFound && isSubgraphNode(nodes[i])) {
76 0 : firstSubgraphFound = true
77 0 : continue
78 : }
79 0 : errors[nodes[i].id] = {
80 : errors: [],
81 : class_type: nodes[i].type,
82 : dependent_outputs: []
83 : }
84 : }
85 0 : useExecutionErrorStore().recordNodeErrors(errors)
86 0 : useCanvasStore().getCanvas().draw(true, true)
87 0 : throw new Error(
88 : 'The root graph of a subgraph blueprint must consist of only a single subgraph node'
89 : )
90 : }
91 :
92 : override async save(): Promise<UserFile> {
93 9 : this.validateSubgraph()
94 9 : if (
95 : !this.hasPromptedSave &&
96 : useSettingStore().get('Comfy.Workflow.WarnBlueprintOverwrite')
97 : ) {
98 1 : if (!(await confirmOverwrite(this.filename))) return this
99 1 : this.hasPromptedSave = true
100 : }
101 : // Extract metadata from subgraph.extra to workflow.extra before saving
102 9 : this.extractMetadataToWorkflowExtra()
103 9 : const ret = await super.save()
104 : // Force reload to update initialState with saved metadata
105 9 : registerNodeDef(await this.load({ force: true }), {
106 : category: 'Subgraph Blueprints/User'
107 : })
108 8 : return ret
109 : }
110 :
111 : /**
112 : * Moves all properties (except workflowRendererVersion) from subgraph.extra
113 : * to workflow.extra, then removes from subgraph.extra to avoid duplication.
114 : */
115 : private extractMetadataToWorkflowExtra(): void {
116 9 : if (!this.activeState) return
117 9 : const subgraph = this.activeState.definitions?.subgraphs[0]
118 9 : if (!subgraph?.extra) return
119 :
120 9 : const sgExtra = subgraph.extra as Record<string, unknown>
121 9 : const workflowExtra = (this.activeState.extra ??= {}) as Record<
122 : string,
123 : unknown
124 : >
125 :
126 9 : for (const key of Object.keys(sgExtra)) {
127 0 : if (key === 'workflowRendererVersion') continue
128 0 : workflowExtra[key] = sgExtra[key]
129 0 : delete sgExtra[key]
130 : }
131 : }
132 :
133 : override async saveAs(path: string) {
134 0 : this.validateSubgraph()
135 0 : this.hasPromptedSave = true
136 : // Extract metadata from subgraph.extra to workflow.extra before saving
137 0 : this.extractMetadataToWorkflowExtra()
138 0 : const ret = await super.saveAs(path)
139 : // Force reload to update initialState with saved metadata
140 0 : registerNodeDef(await this.load({ force: true }), {
141 : category: 'Subgraph Blueprints/User'
142 : })
143 0 : return ret
144 : }
145 : override async load({ force = false }: { force?: boolean } = {}): Promise<
146 : this & LoadedComfyWorkflow
147 : > {
148 262905 : if (!force && this.isLoaded) return await super.load({ force })
149 262903 : const loaded = await super.load({ force })
150 262889 : const st = loaded.activeState
151 262905 : const sg = (st.definitions?.subgraphs ?? []).find(
152 : (sg) => sg.id == st.nodes[0].type
153 : )
154 262905 : if (!sg)
155 0 : throw new Error(
156 : 'Loaded subgraph blueprint does not contain valid subgraph'
157 : )
158 262889 : sg.name = st.nodes[0].title = this.filename
159 :
160 : // Copy blueprint metadata from workflow extra to subgraph extra
161 : // so it's available when editing via canvas.subgraph.extra
162 262904 : if (st.extra) {
163 233476 : const sgExtra = (sg.extra ??= {}) as Record<string, unknown>
164 233476 : for (const [key, value] of Object.entries(st.extra)) {
165 231576 : if (key === 'workflowRendererVersion') continue
166 200070 : sgExtra[key] = value
167 : }
168 : }
169 :
170 262889 : return loaded
171 : }
172 : override readonly saveNamePrompt = {
173 : title: 'subgraphStore.saveBlueprint',
174 : message: 'subgraphStore.blueprintNamePrompt'
175 : }
176 : override unload(): void {
177 : //Skip unloading. Even if a workflow is closed after editing,
178 : //it must remain loaded in order to be added to the graph
179 : }
180 : }
181 2355 : const subgraphCache: Record<string, LoadedComfyWorkflow> = {}
182 2355 : const nodeDefStore = useNodeDefStore()
183 2355 : const canvasStore = useCanvasStore()
184 2335 : async function fetchSubgraphs() {
185 219 : async function loadBlueprint(options: {
186 : path: string
187 : modified: number
188 : size: number
189 : }): Promise<void> {
190 219 : options.path = SubgraphBlueprint.basePath + options.path
191 219 : const bp = await new SubgraphBlueprint(options, true).load()
192 206 : useWorkflowStore().attachWorkflow(bp)
193 206 : registerNodeDef(bp, { category: 'Subgraph Blueprints/User' })
194 : }
195 2335 : async function loadInstalledBlueprints() {
196 271558 : async function loadGlobalBlueprint([k, v]: [string, GlobalSubgraphData]) {
197 271558 : const data = await v.data
198 271558 : if (typeof data !== 'string' || data.trim().length === 0) {
199 0 : throw new Error(
200 : `Global blueprint '${v.name}' (${k}) returned empty content`
201 : )
202 : }
203 262669 : const path = SubgraphBlueprint.basePath + v.name + '.json'
204 262669 : const blueprint = new SubgraphBlueprint({
205 : path,
206 : modified: Date.now(),
207 : size: -1
208 : })
209 262669 : blueprint.originalContent = blueprint.content = data
210 262669 : blueprint.filename = v.name
211 262669 : useWorkflowStore().attachWorkflow(blueprint)
212 262669 : const loaded = await blueprint.load()
213 271558 : const category = v.info.category
214 : ? `Subgraph Blueprints/${v.info.category}`
215 : : undefined
216 271558 : registerNodeDef(
217 : loaded,
218 : {
219 : display_name: v.name,
220 : ...(category && { category }),
221 : ...(v.essentials_category && {
222 : essentials_category: v.essentials_category
223 : }),
224 : search_aliases: v.info.search_aliases,
225 : isGlobal: true
226 : },
227 : k
228 : )
229 : }
230 2335 : const subgraphs = await api.getGlobalSubgraphs()
231 2324 : const currentDistribution: TemplateIncludeOnDistributionEnum = isCloud
232 : ? TemplateIncludeOnDistributionEnum.Cloud
233 : : isDesktop
234 : ? TemplateIncludeOnDistributionEnum.Desktop
235 : : TemplateIncludeOnDistributionEnum.Local
236 2324 : const filteredEntries = Object.entries(subgraphs).filter(([, v]) => {
237 271558 : if (!isCloud && (v.info.requiresCustomNodes?.length ?? 0) > 0)
238 0 : return false
239 271558 : if (
240 : (v.info.includeOnDistributions?.length ?? 0) > 0 &&
241 : !v.info.includeOnDistributions!.includes(currentDistribution)
242 : )
243 0 : return false
244 271558 : return true
245 : })
246 2324 : return Promise.allSettled(filteredEntries.map(loadGlobalBlueprint))
247 : }
248 :
249 2335 : async function loadUserBlueprints() {
250 2335 : const userSubs = (
251 : await api.listUserDataFullInfo(SubgraphBlueprint.basePath)
252 : ).filter((f) => f.path.endsWith('.json'))
253 2327 : return Promise.allSettled(userSubs.map(loadBlueprint))
254 : }
255 :
256 : const results = await Promise.allSettled([
257 : loadInstalledBlueprints(),
258 : loadUserBlueprints()
259 : ])
260 : const settled = results.flatMap((result) =>
261 : result.status === 'fulfilled' ? result.value : [result]
262 : )
263 :
264 2335 : const errors = settled.filter((i) => 'reason' in i).map((i) => i.reason)
265 2184 : errors.forEach((e) => console.error('Failed to load subgraph blueprint', e))
266 2184 : if (errors.length > 0) {
267 0 : useToast().error(t('subgraphStore.loadFailure'), {
268 : description:
269 : errors.length > 3
270 : ? `x${errors.length}`
271 : : errors
272 : .map((e) => getErrorMessage(e) ?? t('g.unknownError'))
273 : .join(', ')
274 : })
275 : }
276 : }
277 262883 : function registerNodeDef(
278 : workflow: LoadedComfyWorkflow,
279 : overrides: Partial<ComfyNodeDefV1> = {},
280 : name: string = workflow.filename
281 : ) {
282 262883 : const subgraphNode = workflow.changeTracker.initialState.nodes[0]
283 262883 : subgraphNode.inputs ??= []
284 262883 : subgraphNode.outputs ??= []
285 262883 : const inputs = Object.fromEntries(
286 : subgraphNode.inputs.map((i) => [
287 : i.name,
288 : [`${i.type}`, undefined] satisfies InputSpec
289 : ])
290 : )
291 262883 : const workflowExtra = workflow.initialState.extra
292 262883 : const description =
293 : workflowExtra?.BlueprintDescription ??
294 : workflow.initialState.definitions?.subgraphs[0].description ??
295 : 'User generated subgraph blueprint'
296 262883 : const search_aliases = workflowExtra?.BlueprintSearchAliases
297 262883 : const subgraphDefCategory =
298 : workflow.initialState.definitions?.subgraphs[0]?.category
299 262883 : const subgraphDefEssentialsCategory =
300 : workflow.initialState.definitions?.subgraphs[0]?.essentials_category
301 262883 : const category = subgraphDefCategory
302 : ? `Subgraph Blueprints/${subgraphDefCategory}`
303 : : 'Subgraph Blueprints'
304 262883 : const nodedefv1: ComfyNodeDefV1 = {
305 : input: { required: inputs },
306 : output: subgraphNode.outputs.map((o) => `${o.type}`),
307 : output_name: subgraphNode.outputs.map((o) => o.name),
308 : name: BLUEPRINT_TYPE_PREFIX + name,
309 : display_name: name,
310 : description,
311 : category,
312 : output_node: false,
313 : python_module: 'blueprint',
314 : search_aliases,
315 : essentials_category: subgraphDefEssentialsCategory,
316 : ...overrides
317 : }
318 262883 : nodeDefStore.registerBlueprintNodeDef(
319 : new ComfyNodeDefImpl(nodedefv1, { validateInputs: true })
320 : )
321 262883 : subgraphCache[name] = workflow
322 : }
323 6 : async function publishSubgraph(providedName?: string) {
324 6 : const canvas = canvasStore.getCanvas()
325 6 : const subgraphNode = [...canvas.selectedItems][0]
326 6 : if (
327 : canvas.selectedItems.size !== 1 ||
328 : !(subgraphNode instanceof SubgraphNode)
329 : )
330 0 : throw new TypeError('Must have single SubgraphNode selected to publish')
331 :
332 6 : const { nodes = [], subgraphs = [] } = canvas._serializeItems([
333 : subgraphNode
334 : ])
335 6 : if (nodes.length != 1) {
336 0 : throw new TypeError('Must have single SubgraphNode selected to publish')
337 : }
338 :
339 6 : const workflowData = {
340 : revision: 0,
341 : last_node_id: subgraphNode.id,
342 : last_link_id: 0,
343 : nodes,
344 : links: [] as never[],
345 : version: 0.4,
346 : definitions: { subgraphs }
347 : }
348 6 : const name =
349 : providedName ??
350 : (await useDialogService().prompt({
351 : title: t('subgraphStore.saveBlueprint'),
352 : message: t('subgraphStore.blueprintNamePrompt'),
353 : defaultValue: subgraphNode.title
354 : }))
355 1 : if (!name) return
356 6 : const savedBlueprints = await api
357 : .listUserDataFullInfo(SubgraphBlueprint.basePath)
358 : .catch((error: unknown) => {
359 0 : reportError(error, {
360 : errorType: 'error_checking_blueprint_overwrite',
361 : surface: 'graph'
362 : })
363 0 : useToast().error(t('subgraphStore.loadFailure'), {
364 : description: getErrorMessage(error) ?? t('g.unknownError')
365 : })
366 : })
367 6 : if (!savedBlueprints) return
368 6 : if (
369 : savedBlueprints.some((file) => file.path === `${name}.json`) &&
370 : !(await confirmOverwrite(name))
371 : )
372 0 : return
373 :
374 6 : const path = SubgraphBlueprint.basePath + name + '.json'
375 6 : const workflow = new SubgraphBlueprint({
376 : path,
377 : size: -1,
378 : modified: Date.now()
379 : })
380 6 : workflow.originalContent = JSON.stringify(workflowData)
381 6 : const loadedWorkflow = await workflow.load()
382 6 : workflow.size = 1
383 6 : await workflow.save()
384 6 : useWorkflowStore().attachWorkflow(loadedWorkflow)
385 6 : useToast().success(t('subgraphStore.publishSuccess'), {
386 : description: t('subgraphStore.publishSuccessMessage'),
387 : duration: 4000
388 : })
389 : }
390 2 : async function editBlueprint(nodeType: string) {
391 2 : const name = nodeType.slice(BLUEPRINT_TYPE_PREFIX.length)
392 2 : if (!(name in subgraphCache))
393 : //As loading is blocked on in startup, this can likely be changed to invalid type
394 0 : throw new Error('not yet loaded')
395 2 : useWorkflowStore().attachWorkflow(subgraphCache[name])
396 2 : await useWorkflowService().openWorkflow(subgraphCache[name])
397 2 : const canvas = useCanvasStore().getCanvas()
398 2 : if (canvas.graph && 'subgraph' in canvas.graph.nodes[0])
399 2 : canvas.setGraph(canvas.graph.nodes[0].subgraph)
400 : }
401 3 : function getBlueprint(nodeType: string): ComfyWorkflowJSON {
402 3 : const name = nodeType.slice(BLUEPRINT_TYPE_PREFIX.length)
403 3 : if (!(name in subgraphCache))
404 : //As loading is blocked on in startup, this can likely be changed to invalid type
405 0 : throw new Error('not yet loaded')
406 3 : return structuredClone(subgraphCache[name].changeTracker.initialState)
407 : }
408 0 : async function deleteBlueprint(nodeType: string) {
409 0 : const name = nodeType.slice(BLUEPRINT_TYPE_PREFIX.length)
410 0 : if (!(name in subgraphCache)) throw new Error('not yet loaded')
411 :
412 0 : if (isGlobalBlueprint(name)) {
413 0 : useToast().warning(t('subgraphStore.cannotDeleteGlobal'), {
414 : duration: 4000
415 : })
416 0 : return
417 : }
418 :
419 0 : if (
420 : !(await useDialogService().confirm({
421 : title: t('subgraphStore.confirmDeleteTitle'),
422 : type: 'delete',
423 : message: t('subgraphStore.confirmDelete'),
424 : itemList: [name]
425 : }))
426 : )
427 0 : return
428 :
429 0 : await subgraphCache[name].delete()
430 0 : delete subgraphCache[name]
431 0 : nodeDefStore.removeBlueprintNodeDef(nodeType)
432 : }
433 17990 : function isSubgraphBlueprint(
434 : workflow: unknown
435 : ): workflow is SubgraphBlueprint {
436 17990 : return workflow instanceof SubgraphBlueprint
437 : }
438 :
439 72732 : function isGlobalBlueprint(name: string): boolean {
440 72732 : const nodeDef = nodeDefStore.blueprintNodeDefsByName.get(
441 : BLUEPRINT_TYPE_PREFIX + name
442 : )
443 72732 : return nodeDef !== undefined && nodeDef.isGlobal === true
444 : }
445 :
446 890487 : function isUserBlueprint(nodeType?: string): boolean {
447 890487 : if (!nodeType?.startsWith(BLUEPRINT_TYPE_PREFIX)) return false
448 72732 : const name = nodeType.slice(BLUEPRINT_TYPE_PREFIX.length)
449 890487 : return name in subgraphCache && !isGlobalBlueprint(name)
450 : }
451 :
452 2355 : return {
453 : deleteBlueprint,
454 : editBlueprint,
455 : fetchSubgraphs,
456 : getBlueprint,
457 : isGlobalBlueprint,
458 : isSubgraphBlueprint,
459 : isUserBlueprint,
460 : publishSubgraph
461 : }
462 : })
|