comfy-ts 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4171 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9910 -0
  8. package/dist/index.d.ts +9894 -58
  9. package/dist/index.js +4092 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-SDSJo1Qf.js +3896 -0
  14. package/dist/run-tui-SDSJo1Qf.js.map +1 -0
  15. package/package.json +103 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +56 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  24. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  25. package/src/cli/tui/components/OverlayList.tsx +25 -0
  26. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  27. package/src/cli/tui/components/PreviewPanel.tsx +78 -0
  28. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  29. package/src/cli/tui/components/StatusBar.tsx +171 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  31. package/src/cli/tui/components/TreePanel.tsx +51 -0
  32. package/src/cli/tui/components/TuiApp.tsx +246 -0
  33. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  34. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  35. package/src/cli/tui/keys.ts +20 -0
  36. package/src/cli/tui/protocolImagePainter.ts +95 -0
  37. package/src/cli/tui/run-tui.tsx +76 -0
  38. package/src/cli/tui/state/DraftsSt.ts +273 -0
  39. package/src/cli/tui/state/EditorSt.ts +289 -0
  40. package/src/cli/tui/state/ExecSt.ts +173 -0
  41. package/src/cli/tui/state/HostSt.ts +230 -0
  42. package/src/cli/tui/state/LogsSt.ts +107 -0
  43. package/src/cli/tui/state/LorasSt.ts +185 -0
  44. package/src/cli/tui/state/PickerSt.ts +112 -0
  45. package/src/cli/tui/state/PreviewSt.ts +288 -0
  46. package/src/cli/tui/state/QueueSt.ts +59 -0
  47. package/src/cli/tui/state/SettingsSt.ts +100 -0
  48. package/src/cli/tui/state/TreeSt.ts +122 -0
  49. package/src/cli/tui/state/TuiSt.ts +175 -0
  50. package/src/cli/tui/state/WorkflowsSt.ts +93 -0
  51. package/src/cli/tui-env.ts +8 -0
  52. package/src/errors/InvalidPromptError.ts +12 -0
  53. package/src/graph/ComfyNode.ts +403 -0
  54. package/src/graph/ComfyNodeID.ts +28 -0
  55. package/src/graph/ComfyNodeOutput.ts +16 -0
  56. package/src/graph/NodeSlotSize.ts +4 -0
  57. package/src/graph/autoValue.ts +17 -0
  58. package/src/host/ComfyHost.ts +690 -0
  59. package/src/host/ComfyInstallType.ts +15 -0
  60. package/src/host/ComfyManager.ts +232 -0
  61. package/src/host/ComfyUploader.ts +110 -0
  62. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  63. package/src/host/Requirements.ts +55 -0
  64. package/src/host/ResilientWebsocket.ts +147 -0
  65. package/src/host/loraManagerApi.ts +98 -0
  66. package/src/image-utils/_getPngMetadata.ts +53 -0
  67. package/src/image-utils/_getWebpMetadata.ts +38 -0
  68. package/src/image-utils/_parseExifData.ts +53 -0
  69. package/src/index.ts +89 -0
  70. package/src/litegraph/LiteGraphGroup.ts +22 -0
  71. package/src/litegraph/LiteGraphJSON.ts +46 -0
  72. package/src/litegraph/LiteGraphLink.ts +23 -0
  73. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  74. package/src/litegraph/LiteGraphNode.ts +69 -0
  75. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  76. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  77. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  78. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  79. package/src/manager/ComfyRegistry.ts +124 -0
  80. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  81. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  82. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  83. package/src/manager/generated/KnownModel_Base.ts +126 -0
  84. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  85. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  86. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  87. package/src/manager/generated/KnownModel_Type.ts +97 -0
  88. package/src/manager/json/alter-list.json +224 -0
  89. package/src/manager/json/custom-node-list.extra.ts +13 -0
  90. package/src/manager/json/custom-node-list.json +21948 -0
  91. package/src/manager/json/extension-node-map.json +31282 -0
  92. package/src/manager/json/github-stats.json +12602 -0
  93. package/src/manager/json/model-list.extra.ts +26 -0
  94. package/src/manager/json/model-list.json +5052 -0
  95. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  96. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  97. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  98. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  99. package/src/manager/script-update-manager.bun.ts +18 -0
  100. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  101. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  102. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  103. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  104. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  105. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  106. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  107. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  108. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  109. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  110. package/src/runner/ComfyExecution.ts +301 -0
  111. package/src/runner/ComfyExecutionStatus.ts +2 -0
  112. package/src/runner/ComfyWorkflow.ts +395 -0
  113. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  114. package/src/runner/ComfyWsApi.ts +170 -0
  115. package/src/runner/MediaImage.ts +262 -0
  116. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  117. package/src/sdk-generator/ComfySchema.ts +369 -0
  118. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  119. package/src/sdk-generator/Primitives.ts +76 -0
  120. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  121. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  122. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  123. package/src/sdk-generator/comfy-api-json.ts +16 -0
  124. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  125. package/src/sdk-generator/comfyui-types.ts +56 -0
  126. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  127. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  128. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  129. package/src/ssh-host-manager/ssh-manager.ts +114 -0
  130. package/src/state.ts +136 -0
  131. package/src/types/comfy-sdk.ts +106 -0
  132. package/src/types/index.ts +55 -0
  133. package/src/utils/CodeBuffer.ts +61 -0
  134. package/src/utils/ComfyColors.ts +38 -0
  135. package/src/utils/ansi.ts +33 -0
  136. package/src/utils/ansiImage.ts +36 -0
  137. package/src/utils/bang.ts +39 -0
  138. package/src/utils/deepCopyNaive.ts +1 -0
  139. package/src/utils/downloadFile.ts +77 -0
  140. package/src/utils/escapeJSKey.ts +32 -0
  141. package/src/utils/exhaust.ts +4 -0
  142. package/src/utils/extractErrorMessage.ts +11 -0
  143. package/src/utils/fuzzyMatch.ts +8 -0
  144. package/src/utils/githubRegexes.ts +2 -0
  145. package/src/utils/hashArrayBuffer.ts +6 -0
  146. package/src/utils/log.ts +9 -0
  147. package/src/utils/loraTag.ts +10 -0
  148. package/src/utils/mojibake.ts +60 -0
  149. package/src/utils/printArkResultInConsole.ts +16 -0
  150. package/src/utils/softValidate.ts +8 -0
  151. package/src/utils/stringifyReadable.ts +32 -0
  152. package/src/utils/toposort.ts +59 -0
  153. package/src/utils/tryExtracting.ts +41 -0
  154. package/src/utils/writeFile.ts +16 -0
  155. package/src/vars/ComfyVars.ts +531 -0
  156. package/src/vars/DefinedWorkflow.ts +112 -0
  157. package/src/vars/loraKeywords.ts +56 -0
  158. package/dist/index.d.mts +0 -74
  159. package/dist/index.mjs +0 -3
  160. package/dist/index.mjs.map +0 -1
  161. package/readme.md +0 -40
@@ -0,0 +1,395 @@
1
+ import { nanoid } from 'nanoid'
2
+ import { join } from 'pathe'
3
+ import { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
4
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
+ import { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
6
+ import { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
7
+ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
8
+ import { ComfyNode } from 'src/graph/ComfyNode.ts'
9
+ import type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
10
+ import { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
11
+ import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
12
+ import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
13
+ import { type AbsolutePath, type ImageSaveFormat, type Maybe, type Tagged } from 'src/types/index.ts'
14
+ import type { SdkForHost } from 'src/types/comfy-sdk.ts'
15
+ import { bang } from 'src/utils/bang.ts'
16
+ import { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'
17
+ import { softValidate } from 'src/utils/softValidate.ts'
18
+ import { comfyWorkflowAutoLayout } from 'src/runner/ComfyWorkflowLayout.ts'
19
+ import {
20
+ type ApiPromptInput,
21
+ type PromptInfo,
22
+ PromptInfo_ark,
23
+ type WsMsgExecuting,
24
+ type WsMsgExecutionCached,
25
+ type WsMsgProgress,
26
+ } from 'src/runner/ComfyWsApi.ts'
27
+
28
+ export type ProgressReport = {
29
+ percent: number
30
+ isDone: boolean
31
+ countDone: number
32
+ countTotal: number
33
+ }
34
+
35
+ export type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'
36
+
37
+ export type RunSettings = {
38
+ saveFormat?: ImageSaveFormat
39
+ idMode?: ComfyNodeIdMode
40
+ /** render a live single-line progress report to the console */
41
+ log?: boolean
42
+ /** called on every progress-relevant websocket message */
43
+ onProgress?: (p: ExecutionProgress) => void
44
+ }
45
+
46
+ /** exactly what was sent to the host for one execution, frozen at send time */
47
+ export type ExecutionSnapshot = {
48
+ apiJson: ComfyApiJson
49
+ workflowJson: LiteGraphJSON
50
+ }
51
+
52
+ /**
53
+ * ComfyWorkflowL
54
+ * - holds the nodes
55
+ * - can be instanciated in both extension and webview
56
+ * - so no link to workspace or run
57
+ */
58
+
59
+ // #region ComfyWorkflow
60
+ export type ComfyWorkflow_metadata = { [key: ComfyNodeId]: ComfyNodeMetadata }
61
+
62
+ export type ComfyWorkflowID = Tagged<string, { ComfyWorkflowID: true }>
63
+ export const asComfyWorkflowID = (x: string): ComfyWorkflowID => x
64
+
65
+ export type ComfyWorkflowData = {
66
+ id?: Maybe<ComfyWorkflowID>
67
+
68
+ apiJson?: ComfyApiJson
69
+ metadata: ComfyWorkflow_metadata
70
+ }
71
+
72
+ export class ComfyWorkflow<ID extends string = string> {
73
+ id: ComfyWorkflowID
74
+ apiJson: ComfyApiJson
75
+ outputFolder: AbsolutePath
76
+
77
+ constructor(
78
+ public host: ComfyHost<ID>,
79
+ public data: ComfyWorkflowData,
80
+ ) {
81
+ this.id = data.id ?? (nanoid(8) as ComfyWorkflowID)
82
+ // ONE json object, shared by the field and the data record (registerNode writes there)
83
+ this.apiJson = data.apiJson ?? {}
84
+ data.apiJson = this.apiJson
85
+ this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`)
86
+ }
87
+
88
+ /** nodes, in creation order */
89
+ nodes: ComfyNode[] = []
90
+
91
+ /** @internal every node constructor must call this */
92
+ registerNode = (node: ComfyNode): void => {
93
+ if (this.data.apiJson == null) throw new Error('graph not hydrated')
94
+ this.data.apiJson[node.uid] = node.json
95
+ this.data.metadata[node.uid] = node.meta
96
+ this.nodesIndex.set(node.uid, node)
97
+ this.nodes.push(node)
98
+ }
99
+
100
+ /** number of node in the graph */
101
+ get size(): number {
102
+ return this.nodes.length
103
+ }
104
+
105
+ setMetadata = (nodeID: ComfyNodeId, meta: ComfyNodeMetadata): void => {
106
+ this.data.metadata[nodeID] = meta
107
+ }
108
+
109
+ getMetadata = (nodeID: ComfyNodeId): Maybe<ComfyNodeMetadata> => {
110
+ return this.data.metadata[nodeID] ?? null
111
+ }
112
+
113
+ /** problem accumulator */
114
+ problems: { title: string; data?: unknown }[] = []
115
+
116
+ recordProblem = (title: string, data?: unknown): void => {
117
+ this.problems.push({ title, data })
118
+ }
119
+
120
+ /** workflow builder, typed from the generated per-host sdk when one is in scope */
121
+ private _builder: ComfyWorkflowBuilder | null = null
122
+ get builder(): SdkForHost<ID>['Builder'] {
123
+ if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)
124
+ // sanctioned cast (see agent/coding.md): the runtime builder defines its
125
+ // methods dynamically from the live schema; the static face comes from
126
+ // the generated per-host sdk. Both derive from the same object_info.
127
+ return this._builder as SdkForHost<ID>['Builder']
128
+ }
129
+
130
+ /** base (untyped) view of the same builder, for generic library code */
131
+ get builderBase(): Comfy.Builder {
132
+ if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)
133
+ return this._builder as Comfy.Builder
134
+ }
135
+
136
+ onUpdate = (prev: Maybe<ComfyWorkflowData>, next: ComfyWorkflowData): void => {
137
+ if (prev != null) {
138
+ this.nodes = []
139
+ this.nodesIndex.clear()
140
+ this.currentExecutingNode = null
141
+ }
142
+ for (const [uid, node] of Object.entries(bang(next.apiJson))) {
143
+ const meta: Maybe<ComfyNodeMetadata> = next.metadata?.[uid]
144
+ new ComfyNode(this, uid, node, meta)
145
+ }
146
+ }
147
+
148
+ /** proxy to this.db.schema */
149
+ get schema(): ComfySchema {
150
+ return this.host.schema
151
+ }
152
+
153
+ /** nodes that are still pending execution */
154
+ get pendingNodes(): ComfyNode[] {
155
+ return this.nodes.filter((n) => n.status == null || n.status === 'waiting')
156
+ }
157
+
158
+ get nodesByUpdatedAt(): ComfyNode[] {
159
+ return this.nodes //
160
+ .filter((n) => n.status != null && n.status !== 'waiting')
161
+ .sort((a, b) => b.updatedAt - a.updatedAt)
162
+ // return this.nodes.slice().sort((a, b) => b.updatedAt - a.updatedAt)
163
+ }
164
+
165
+ // findNodeByType = <T extends keyof ComfySetup>(nodeKey: T): Maybe<ReturnType<ComfySetup[T]>> => {
166
+ // return this.nodes.find((n) => n.$schema.nodeKey === nodeKey) as any
167
+ // }
168
+
169
+ /** nodes, indexed by nodeID */
170
+ nodesIndex = new Map<string, ComfyNode>()
171
+
172
+ /** convert to mermaid DSL expression for nice graph rendering */
173
+ toMermaid = (DIR: 'LR' | 'TD' = 'LR'): string => {
174
+ const out = [
175
+ `graph ${DIR}`,
176
+ this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join('\n'),
177
+ this.nodes
178
+ .map((n) =>
179
+ n
180
+ ._incomingEdges()
181
+ .map((i) => {
182
+ const from = this.nodesIndex.get(i.from)
183
+
184
+ return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${
185
+ n.$schema.nodeKey
186
+ }]`
187
+ })
188
+ .join('\n'),
189
+ )
190
+ .join('\n'),
191
+ ].join('\n')
192
+ return out
193
+ }
194
+
195
+ /** export the graph in ComfyUI's saved-workflow format (autolayouted by default) */
196
+ toWorkflowJson = async (p: { layout?: boolean } = {}): Promise<LiteGraphJSON> => {
197
+ if (p.layout !== false) this.autoLayout()
198
+ return convertFlowToLiteGraphJSON(this)
199
+ }
200
+
201
+ /** export the graph in ComfyUI's api format (what POST /prompt takes) */
202
+ toApiJson = (ns: ComfyNodeIdMode = 'use_stringified_numbers_only'): ComfyApiJson => {
203
+ const json: ComfyApiJson = {}
204
+ const keyOf = (uid: string): string =>
205
+ ns === 'use_stringified_numbers_only' ? uid : (this.nodesIndex.get(uid)?.uidPrefixed ?? uid)
206
+ for (const node of this.nodes) {
207
+ if (node.disabled) continue
208
+ const key = ns === 'use_stringified_numbers_only' ? node.uid : node.uidPrefixed
209
+ // links reference node keys — remap them to whatever key scheme we emit
210
+ const inputs: ComfyApiNodeJson['inputs'] = {}
211
+ for (const [name, value] of Object.entries(node.json.inputs)) {
212
+ inputs[name] =
213
+ Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'number'
214
+ ? [keyOf(value[0]), value[1]]
215
+ : value
216
+ }
217
+ json[key] = { class_type: node.json.class_type, inputs }
218
+ }
219
+ return json
220
+ }
221
+
222
+ /** @internal pointer to the currently executing node */
223
+ currentExecutingNode: ComfyNode | null = null
224
+
225
+ get progressCurrentNode(): Maybe<ProgressReport> {
226
+ return this.currentExecutingNode?.progressReport
227
+ }
228
+
229
+ get progressGlobal(): ProgressReport {
230
+ const totalNode = this.nodes.length
231
+ const doneNodes = this.nodes.filter((n) => n.status === 'done' || n.status === 'cached').length
232
+ const bonus = this.currentExecutingNode?.progressRatio ?? 0
233
+ const score = (doneNodes + bonus) / totalNode
234
+ const percent = this.done ? 100 : score * 100
235
+ const isDone = this.done
236
+ return { percent, isDone, countDone: doneNodes + bonus, countTotal: totalNode }
237
+ }
238
+
239
+ /** @internal update the progress value of the currently focused onde */
240
+ onProgress = (msg: WsMsgProgress): void => {
241
+ if (this.currentExecutingNode == null) return void console.log('❌ no current executing node', msg)
242
+ this.currentExecutingNode.progress = msg.data
243
+ this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1)
244
+ }
245
+
246
+ getTargetWorkflowFilePath = (): AbsolutePath => {
247
+ return join(this.cacheFolderPath, 'workflow.json')
248
+ }
249
+
250
+ getTargetPromptFilePath = (): AbsolutePath => {
251
+ return join(this.cacheFolderPath, 'prompt.json')
252
+ }
253
+
254
+ get cacheFolderPath(): AbsolutePath {
255
+ return comfyts.resolveFromOutput(`workflows/${this.id}`)
256
+ }
257
+
258
+ // private outputs: WsMsgExecuted[] = []
259
+ // images: ImageL[] = []
260
+
261
+ done: boolean = false
262
+
263
+ /** @internal update pointer to the currently executing node */
264
+ onExecuting = (msg: WsMsgExecuting): void => {
265
+ // 1. mark currentExecutingNode as done
266
+ if (this.currentExecutingNode) {
267
+ this.currentExecutingNode.status = 'done'
268
+ // this.currentExecutingNode.updatedAt = Date.now() + 1000
269
+ }
270
+ // 2. then two cases:
271
+ // 2.A. no node => the prompt is done
272
+ if (msg.data.node == null) {
273
+ this.currentExecutingNode = null
274
+ this.done = true
275
+ return
276
+ }
277
+
278
+ this.done = false
279
+ // 2.B. a node => node evaluation is starting
280
+ const node = this.getNodeOrCrash(msg.data.node)
281
+ this.currentExecutingNode = node
282
+ node.status = 'executing'
283
+ node.updatedAt = Date.now()
284
+ }
285
+
286
+ onExecutionCached = (msg: WsMsgExecutionCached): void => {
287
+ for (const x of msg.data.nodes) {
288
+ const node = this.getNodeOrCrash(x)
289
+ node.status = 'cached'
290
+ }
291
+ }
292
+
293
+ // onExecuted = (msg: WsMsgExecuted) => {
294
+ // const node = this.getNodeOrCrash(msg.data.node)
295
+ // const images = msg.data.output.images.map((i) => new PromptOutputImage(this, i))
296
+
297
+ // // console.log(`🟢 `, images.length, `CushyImages`)
298
+ // // accumulate in self
299
+ // this.outputs.push(msg)
300
+ // this.images.push(...images)
301
+ // // console.log(`🟢 `, this.uid, 'has', this.images.length, `CushyImages`)
302
+
303
+ // // accumulate in node
304
+ // node.artifacts.push(msg.data)
305
+ // node.images.push(...images)
306
+ // }
307
+
308
+ _uidNumber: number = 0
309
+
310
+ getNodeOrCrash = (nodeID: ComfyNodeId): ComfyNode => {
311
+ const node = this.nodesIndex.get(nodeID)
312
+ if (node == null) throw new Error('Node not found:' + nodeID)
313
+ return node
314
+ }
315
+
316
+ getNode = (nodeID: ComfyNodeId): Maybe<ComfyNode> => {
317
+ const node = this.nodesIndex.get(nodeID)
318
+ return node
319
+ }
320
+
321
+ width: number = 100
322
+ height: number = 100
323
+
324
+ /** compute autolayout **/
325
+ autoLayout = comfyWorkflowAutoLayout.bind(this)
326
+
327
+ /** send the workflow and wait for it to finish (with all outputs downloaded) */
328
+ run = async (p: RunSettings = {}): Promise<ComfyExecution> => {
329
+ const execution = await this.start(p)
330
+ await execution.done
331
+ return execution
332
+ }
333
+
334
+ /** reset per-run node state so the same workflow can run again cleanly */
335
+ private resetRunState(): void {
336
+ this.done = false
337
+ this.currentExecutingNode = null
338
+ for (const node of this.nodes) {
339
+ node.status = null
340
+ node.progress = null
341
+ node.progressRatio = 0
342
+ }
343
+ }
344
+
345
+ /** send the workflow; returns the live execution (await `execution.done` yourself) */
346
+ start = async (p: RunSettings = {}): Promise<ComfyExecution> => {
347
+ this.resetRunState()
348
+ // snapshot: exactly what runs, frozen at send time (the live workflow stays editable)
349
+ const snapshot: ExecutionSnapshot = {
350
+ apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),
351
+ workflowJson: await this.toWorkflowJson(),
352
+ }
353
+ const out: ApiPromptInput = {
354
+ client_id: this.host.comfySessionId,
355
+ prompt: snapshot.apiJson,
356
+ extra_data: {
357
+ extra_pnginfo: {
358
+ // regular ComfyUI metadata (drag the file in the editor -> the graph)
359
+ workflow: snapshot.workflowJson,
360
+ comfy_ts_workflow_id: this.id,
361
+ comfy_ts_version: comfyts.version,
362
+ },
363
+ },
364
+ }
365
+
366
+ const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`
367
+ const res = await fetch(promptEndpoint, {
368
+ method: 'POST',
369
+ body: JSON.stringify(out),
370
+ })
371
+ const promptInfoJson = await res.json()
372
+ const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)
373
+
374
+ if (res.status !== 200) {
375
+ throw new InvalidPromptError('ComfyUI /prompt request failed', snapshot, promptInfo)
376
+ }
377
+ // settings + snapshot go through the constructor: the ctor flushes ws
378
+ // messages that raced ahead, and those handlers need the settings
379
+ const execution = new ComfyExecution(
380
+ this,
381
+ {
382
+ id: promptInfo.prompt_id,
383
+ executed: false,
384
+ graphID: this.id,
385
+ },
386
+ {
387
+ snapshot,
388
+ saveFormat: p.saveFormat,
389
+ onProgress: p.onProgress,
390
+ logProgress: p.log ?? false,
391
+ },
392
+ )
393
+ return execution
394
+ }
395
+ }
@@ -0,0 +1,96 @@
1
+ /** biome-ignore-all lint/style/noNonNullAssertion: later */
2
+ import type { ComfyNode, ComfyNodeUID } from 'src/graph/ComfyNode.ts'
3
+ import { bang } from 'src/utils/bang.ts'
4
+ import { type TEdge, toposort } from 'src/utils/toposort.ts'
5
+ import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
6
+
7
+ /**
8
+ * compute autolayout
9
+ *
10
+ * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive
11
+ * libraries were pretty bad; ended up writing my own simple algorithm, and I'm
12
+ * happy with it. Feel free to improve it, but I think it works well enough.
13
+ * I will accept PRs for new layout algorithms if they don't have massive dependencies.
14
+ **/
15
+ export function comfyWorkflowAutoLayout(
16
+ this: ComfyWorkflow,
17
+ p?: {
18
+ /** @default: 20 */
19
+ node_vsep?: number
20
+ /** @default: 20 */
21
+ node_hsep?: number
22
+ /** @default false */
23
+ forceLeft?: boolean
24
+ },
25
+ ): ComfyWorkflow {
26
+ const nodeIds = toposort(
27
+ this.nodes.map((n) => n.uid),
28
+ this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid] as TEdge)),
29
+ )
30
+ const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`))
31
+ const cols: ComfyNode[][] = Array.from({ length: nodeIds.length })
32
+
33
+ type NodePlacement = {
34
+ node: ComfyNode
35
+ minCol: number
36
+ maxCol?: number
37
+ }
38
+ const ranges: {
39
+ [nodeId: ComfyNodeUID]: NodePlacement
40
+ } = {}
41
+
42
+ // console.log(`[🤠] 1/3 ----------------------------`)
43
+ for (const node of nodes) {
44
+ // must be at least 1 after the closest parent
45
+ const parentCols = node.parents.map((p) => ranges[p.uid]!.minCol)
46
+ const minCol = Math.max(...parentCols, -1) + 1
47
+ const range: NodePlacement = { node: node, minCol: minCol }
48
+ ranges[node.uid] = range
49
+ }
50
+
51
+ // console.log(`[🤠] 2/3 ----------------------------`)
52
+ if (!p?.forceLeft === true) {
53
+ for (const node of nodes) {
54
+ const range = ranges[node.uid]!
55
+ for (const p of node.parents) {
56
+ const parentRange = ranges[p.uid]!
57
+ parentRange.maxCol =
58
+ parentRange.maxCol != null
59
+ ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1)
60
+ : (range.maxCol ?? range.minCol) - 1
61
+ }
62
+ }
63
+ }
64
+
65
+ // console.log(`[🤠] 3/3 ----------------------------`)
66
+ for (const node of nodes) {
67
+ const range = ranges[node.uid]!
68
+ const at = range.maxCol ?? range.minCol
69
+ if (cols[at]) cols[at]!.push(node)
70
+ else cols[at] = [node]
71
+ }
72
+
73
+ const HSEP = p?.node_hsep ?? 20
74
+ const VSEP = p?.node_vsep ?? 20
75
+ // cols.reverse()
76
+ let colX = 0
77
+ let maxY = 0
78
+ for (const col of cols) {
79
+ if (col == null) continue
80
+ let colWidth = 0
81
+ let currNodeY = 32
82
+ const nodesSorted = col.toSorted((a, b) => b.height - a.height)
83
+ for (const node of nodesSorted) {
84
+ colWidth = Math.max(colWidth, node.width)
85
+ node.x = colX
86
+ node.y = currNodeY
87
+ currNodeY += node.height + VSEP /* V SEP */
88
+ }
89
+ maxY = Math.max(maxY, currNodeY)
90
+ colX += colWidth + HSEP /* H SEP */
91
+ }
92
+
93
+ this.height = maxY
94
+ this.width = colX
95
+ return this
96
+ }
@@ -0,0 +1,170 @@
1
+ import { scope, type } from 'arktype'
2
+ import { ComfyNodeId_ark } from 'src/graph/ComfyNodeID.ts'
3
+ import type { Tagged } from 'src/types/index.ts'
4
+
5
+ /** the id ComfyUI assigns to one queued execution (wire-level name kept) */
6
+ export type PromptID = Tagged<string, { PromptID: true }>
7
+ export const PromptID_ark = type.string.as<PromptID>()
8
+
9
+ // Define the scope and export its types for inference
10
+ const tempScope = scope({
11
+ PromptID: PromptID_ark,
12
+ ComfyNodeID: ComfyNodeId_ark, // Use the aliased schema
13
+ Timestamp: 'number', // Define Timestamp directly in the scope
14
+
15
+ ApiPromptInput: {
16
+ client_id: 'string',
17
+ extra_data: { extra_pnginfo: 'unknown' },
18
+ prompt: 'unknown',
19
+ },
20
+
21
+ NodeProgress: { value: 'number', max: 'number' },
22
+
23
+ ComfyStatusData: {
24
+ 'sid?': 'string',
25
+ status: {
26
+ exec_info: { queue_remaining: 'number' },
27
+ 'sid?': 'string',
28
+ },
29
+ },
30
+ WsMsgStatus: {
31
+ type: "'status'",
32
+ data: 'ComfyStatusData',
33
+ },
34
+
35
+ _WsMsgExecutionStartData: { prompt_id: 'PromptID' },
36
+ WsMsgExecutionStart: {
37
+ type: "'execution_start'",
38
+ data: '_WsMsgExecutionStartData',
39
+ },
40
+
41
+ _WsMsgExecutionCachedData: { nodes: 'ComfyNodeID[]', prompt_id: 'PromptID' },
42
+ WsMsgExecutionCached: {
43
+ type: "'execution_cached'",
44
+ data: '_WsMsgExecutionCachedData',
45
+ },
46
+
47
+ // node is null on the final 'executing' message (prompt done)
48
+ _WSMsgExecutingData: {
49
+ prompt_id: 'PromptID',
50
+ 'node?': 'ComfyNodeID | null',
51
+ },
52
+ WsMsgExecuting: {
53
+ type: "'executing'",
54
+ data: '_WSMsgExecutingData',
55
+ },
56
+
57
+ ComfyImageInfo: {
58
+ filename: 'string',
59
+ subfolder: 'string',
60
+ type: 'string',
61
+ },
62
+ _WsMsgExecutedData: {
63
+ node: 'ComfyNodeID',
64
+ output: {
65
+ 'previews?': [{ filepath: 'string' }, '[]'],
66
+ 'images?': 'ComfyImageInfo[]',
67
+ },
68
+ prompt_id: 'PromptID',
69
+ },
70
+ WsMsgExecuted: {
71
+ type: "'executed'",
72
+ data: '_WsMsgExecutedData',
73
+ },
74
+
75
+ WsMsgExecutionSuccessData: {
76
+ prompt_id: 'PromptID',
77
+ timestamp: 'Timestamp',
78
+ },
79
+ WsMsgExecutionSuccess: {
80
+ type: "'execution_success'",
81
+ data: 'WsMsgExecutionSuccessData',
82
+ },
83
+
84
+ _WsMsgExecutionErrorData: {
85
+ prompt_id: 'PromptID',
86
+ node_id: 'ComfyNodeID',
87
+ node_type: 'string',
88
+ executed: 'ComfyNodeID[]',
89
+ exception_message: 'string',
90
+ exception_type: 'string',
91
+ traceback: 'string[]',
92
+ current_inputs: 'Record<string, unknown>',
93
+ current_outputs: 'Record<string, unknown>',
94
+ },
95
+ WsMsgExecutionError: {
96
+ type: "'execution_error'",
97
+ data: '_WsMsgExecutionErrorData',
98
+ },
99
+
100
+ WSMsgManagerFeedbackData: { data: 'string' },
101
+ WSMsgManagerFeedback: {
102
+ type: "'manager-terminal-feedback'",
103
+ data: 'WSMsgManagerFeedbackData',
104
+ },
105
+
106
+ // server console stream (/internal/logs): entries are WRITE CHUNKS, not lines
107
+ LogEntry: { t: 'string', m: 'string' },
108
+ _WsMsgLogsData: { entries: 'LogEntry[]', 'size?': 'unknown' },
109
+ WsMsgLogs: {
110
+ type: "'logs'",
111
+ data: '_WsMsgLogsData',
112
+ },
113
+
114
+ // WsMsgProgress must be after NodeProgress
115
+ WsMsgProgress: { type: "'progress'", data: 'NodeProgress' },
116
+
117
+ // per-node progress map (ComfyUI ≥ 0.3.x)
118
+ _WsMsgProgressStateData: {
119
+ prompt_id: 'PromptID',
120
+ nodes: 'Record<string, unknown>',
121
+ },
122
+ WsMsgProgressState: {
123
+ type: "'progress_state'",
124
+ data: '_WsMsgProgressStateData',
125
+ },
126
+
127
+ // UNION TYPES
128
+ PromptRelated_WsMsg:
129
+ 'WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess',
130
+ WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg',
131
+ })
132
+
133
+ export const types = tempScope.export()
134
+
135
+ // REQUEST PAYLOADS ------------------------------------------------
136
+ export type ApiPromptInput = typeof types.ApiPromptInput.infer
137
+
138
+ // MISC -------------------------------------------------------------
139
+ export type NodeProgress = typeof types.NodeProgress.infer
140
+
141
+ // LIVE UPDATES ----------------------------------------------------
142
+ export type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer
143
+ export type WsMsg = typeof types.WsMsg.infer
144
+ export type ComfyStatusData = typeof types.ComfyStatusData.infer
145
+ export type WsMsgStatus = typeof types.WsMsgStatus.infer
146
+ export type WsMsgExecutionStart = typeof types.WsMsgExecutionStart.infer
147
+ export type WsMsgExecutionCached = typeof types.WsMsgExecutionCached.infer
148
+ export type _WSMsgExecutingData = typeof types._WSMsgExecutingData.infer
149
+ export type WsMsgExecuting = typeof types.WsMsgExecuting.infer
150
+ export type WsMsgProgress = typeof types.WsMsgProgress.infer
151
+ export type WsMsgProgressState = typeof types.WsMsgProgressState.infer
152
+ export type WsMsgExecuted = typeof types.WsMsgExecuted.infer
153
+ export type WsMsgExecutionSuccess = typeof types.WsMsgExecutionSuccess.infer
154
+ export type WsMsgExecutionError = typeof types.WsMsgExecutionError.infer
155
+ export type WSMsgManagerFeedback = typeof types.WSMsgManagerFeedback.infer
156
+ export type LogEntry = typeof types.LogEntry.infer
157
+ export type WsMsgLogs = typeof types.WsMsgLogs.infer
158
+ export type _WsMsgExecutionStartData = typeof types._WsMsgExecutionStartData.infer
159
+ export type _WsMsgExecutionCachedData = typeof types._WsMsgExecutionCachedData.infer
160
+ export type ComfyImageInfo = typeof types.ComfyImageInfo.infer
161
+ export type _WsMsgExecutedData = typeof types._WsMsgExecutedData.infer
162
+ export type _WsMsgExecutionErrorData = typeof types._WsMsgExecutionErrorData.infer
163
+ export type PromptId = typeof types.PromptID.infer
164
+
165
+ export type PromptInfo = { prompt_id: PromptID }
166
+ export const PromptInfo_ark = type({ prompt_id: types.PromptID }).as<PromptInfo>()
167
+
168
+ export const WsMsg_ark = types.WsMsg
169
+ export const ComfyImageInfo_ark = types.ComfyImageInfo
170
+ export const WsMsgLogsData_ark = types._WsMsgLogsData