comfy-ts 0.2.0 → 0.3.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 (158) 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 +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -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-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -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 +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,646 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
2
+ import { type } from 'arktype'
3
+ import type { MessageEvent } from 'ws'
4
+ import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
5
+ import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
6
+ import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
7
+ import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
8
+ import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
9
+ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
10
+ import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
11
+ import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
12
+ import {
13
+ type ComfyStatusData,
14
+ type PromptID,
15
+ type PromptRelated_WsMsg,
16
+ type WsMsg,
17
+ WsMsg_ark,
18
+ } from 'src/runner/ComfyWsApi.ts'
19
+ import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
20
+ import { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
21
+ import type { EmbeddingName } from 'src/sdk-generator/comfyui-types.ts'
22
+ import { type AbsolutePath, type Maybe, type number_Timestamp, type Tagged } from 'src/types/index.ts'
23
+ import { exhaust } from 'src/utils/exhaust.ts'
24
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
25
+ import { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'
26
+ import { readableStringify } from 'src/utils/stringifyReadable.ts'
27
+ import { logError as toastError, logInfo } from 'src/utils/log.ts'
28
+ import { writeFileAsync } from 'src/utils/writeFile.ts'
29
+ import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
30
+ import { ComfyManager } from 'src/host/ComfyManager.ts'
31
+ import { ComfyUploader } from 'src/host/ComfyUploader.ts'
32
+ import type { Requirements } from 'src/host/Requirements.ts'
33
+ import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
34
+ import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
35
+ import type { VarsSpec } from 'src/vars/ComfyVars.ts'
36
+
37
+ export type ComfyHostID = Tagged<string, { HostID: true }>
38
+ export type ComfyHostData = {
39
+ id: string
40
+ host: string
41
+ port: number
42
+ https?: boolean
43
+
44
+ // for extra features using path manipulation
45
+ installType?: ComfyInstallType
46
+
47
+ // misc
48
+ onWsMessageAny?: (e: MessageEvent) => void
49
+ onWsMessageArrayBuffer?: (e: ArrayBuffer) => void
50
+ onWsMessageJSON?: (e: WsMsg) => void
51
+ }
52
+
53
+ export type ConnectOptions = {
54
+ /** 'auto' (default): reuse cache when fresh · 'refresh': always fetch · 'cache': never fetch */
55
+ schema?: 'auto' | 'refresh' | 'cache'
56
+ /** max cache age for 'auto' (default 24h) */
57
+ maxAgeMs?: number
58
+ }
59
+
60
+ // biome-ignore format: misc
61
+ type SchemaUpdateResult = Maybe<{ type: 'success' } | { type: 'error'; error: unknown }>
62
+
63
+ type ServerLog = {
64
+ at: string
65
+ content: string
66
+ id: number
67
+ }
68
+
69
+ export class ComfyHost<ID extends string = string> {
70
+ // ----- misc paths where we'll store host-related files -----
71
+ cacheFolder: AbsolutePath
72
+
73
+ comfyJSONPath: AbsolutePath
74
+ embeddingsPath: AbsolutePath
75
+ sdkDTSPath: AbsolutePath
76
+
77
+ /** the schema instance with all methods to interract with the host schema */
78
+ schema: ComfySchema
79
+ uploader = new ComfyUploader(this)
80
+
81
+ constructor(public data: ComfyHostData & { id: ID }) {
82
+ /** folder where file related to the host config will be cached */
83
+ this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
84
+
85
+ // create the folder if it does not exist
86
+ const exists = existsSync(this.cacheFolder)
87
+ if (!exists) {
88
+ console.log('🟢 creating folder', this.cacheFolder)
89
+ mkdirSync(this.cacheFolder, { recursive: true })
90
+ }
91
+
92
+ this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)
93
+ this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`)
94
+ this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`)
95
+
96
+ /** create a new schema */
97
+ this.schema = new ComfySchema({ embeddings: [], spec: {} })
98
+ }
99
+
100
+ /** helper to check if your host have whatever it needs to run your workflow */
101
+ matchRequirements = (requirements: Requirements[]): boolean => {
102
+ const repo = comfyts.registry
103
+ for (const req of requirements) {
104
+ if (req.optional) continue
105
+ if (req.type === 'customNodesByNodeKey') {
106
+ const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []
107
+ if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {
108
+ // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)
109
+ return false
110
+ }
111
+ } else if (req.type === 'customNodesByTitle') {
112
+ const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)
113
+ if (plugin == null) continue
114
+ if (!this.manager.isPluginInstalled(plugin.title)) {
115
+ // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)
116
+ return false
117
+ }
118
+ } else if (req.type === 'customNodesByURI') {
119
+ const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)
120
+ if (plugin == null) continue
121
+ if (!this.manager.isPluginInstalled(plugin.title)) {
122
+ // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)
123
+ return false
124
+ }
125
+ } else if (req.type === 'modelInManager') {
126
+ if (!this.manager.isModelInstalled(req.modelName)) {
127
+ // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)
128
+ return false
129
+ }
130
+ } else {
131
+ // exhaust(req.type)
132
+ }
133
+ }
134
+ return true
135
+ }
136
+
137
+ // ----- Rotating srever logs -----
138
+
139
+ /** server sent by the comfy-manager plugin */
140
+ readonly serverLogs: ServerLog[] = []
141
+
142
+ /** if true, request ComfyUI to forward logs */
143
+ private wantLog: boolean = true
144
+
145
+ /** maximum amount of logs to keep in memory */
146
+ readonly maxLogs: number = 200
147
+
148
+ /** last log id received */
149
+ private logId: number = 0
150
+
151
+ /** toggle server log forwarding so comfy-ts can */
152
+ toggleServerLogs = (): Promise<unknown> => {
153
+ this.wantLog = !this.wantLog
154
+ return this.manager.configureLogging(this.wantLog)
155
+ }
156
+
157
+ addLog = (content: string): void => {
158
+ if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift()
159
+ const d = new Date().toISOString().slice(11, 19)
160
+ this.serverLogs.push({ content, id: this.logId++, at: d })
161
+ }
162
+
163
+ // ----- Misc helpers if you work with a local Comfy -----
164
+
165
+ /** root install of ComfyUI on the host filesystem */
166
+ get absolutePathToComfyUI(): Maybe<string> {
167
+ return this.data.installType?.absolutePathToComfyRoot
168
+ }
169
+
170
+ // ----- Misc helpers if you work with a local Comfy -----
171
+
172
+ get manager(): ComfyManager {
173
+ const value = new ComfyManager(this)
174
+ Object.defineProperty(this, 'manager', { value })
175
+ return value
176
+ }
177
+
178
+ // INIT -----------------------------------------------------------------------------
179
+ installCustomNodeByFile = async (customNodeFile: KnownComfyPluginURL): Promise<boolean> => {
180
+ const manager = comfyts.registry
181
+ const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byFile.get(customNodeFile)
182
+ if (plugin == null) throw new Error(`Unknown custom node for file: "${customNodeFile}"`)
183
+ return this.manager.installPlugin(plugin)
184
+ }
185
+
186
+ installCustomNodeByTitle = async (customNodeTitle: KnownComfyPluginTitle): Promise<boolean> => {
187
+ const manager = comfyts.registry
188
+ const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byTitle.get(customNodeTitle)
189
+ if (plugin == null) throw new Error(`Unknown custom node for title: "${customNodeTitle}"`)
190
+ return this.manager.installPlugin(plugin)
191
+ }
192
+
193
+ installCustomNode = async (customNode: ComfyManagerPluginInfo): Promise<boolean> => {
194
+ return this.manager.installPlugin(customNode)
195
+ }
196
+
197
+ // URLS -----------------------------------------------------------------------------
198
+ getServerHostHTTP(): string {
199
+ const method = this.data.https ? 'https' : 'http'
200
+ const host = this.data.host
201
+ const port = this.data.port
202
+ return `${method}://${host}:${port}`
203
+ }
204
+
205
+ getWSUrl = (): string => {
206
+ const method = this.data.https ? 'wss' : 'ws'
207
+ const host = this.data.host
208
+ const port = this.data.port
209
+ return `${method}://${host}:${port}/ws`
210
+ }
211
+
212
+ // LOGS -----------------------------------------------------------------------------
213
+ schemaRetrievalLogs: string[] = []
214
+
215
+ resetLog = (): void => {
216
+ this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length)
217
+ }
218
+
219
+ // STARTING -----------------------------------------------------------------------------
220
+ get isConnected(): boolean {
221
+ return this.ws?.isOpen ?? false
222
+ }
223
+
224
+ workflow = (p: { id?: string } = {}): ComfyWorkflow<ID> => {
225
+ return new ComfyWorkflow(this, {
226
+ metadata: {},
227
+ id: p.id ? asComfyWorkflowID(p.id) : undefined,
228
+ })
229
+ }
230
+
231
+ /**
232
+ * define a re-runnable workflow: `build` re-executes with the current var
233
+ * values on every run(). The standard contract for tweak & re-run drivers
234
+ * (scripts, the TUI).
235
+ */
236
+ defineWorkflow = <V extends VarsSpec>(spec: DefineWorkflowSpec<ID, V>): DefinedWorkflow<ID, V> => {
237
+ return new DefinedWorkflow(this, spec)
238
+ }
239
+
240
+ /** import a workflow.json (litegraph format) as a live, editable workflow */
241
+ importWorkflowJson = (json: LiteGraphJSON, p: { id?: string } = {}): ComfyWorkflow<ID> => {
242
+ const apiJson = convertLiteGraphToPrompt(this.schema, json)
243
+ return this.importApiJson(apiJson, p)
244
+ }
245
+
246
+ /** import an api.json (ComfyUI prompt format) as a live, editable workflow */
247
+ importApiJson = (json: ComfyApiJson, p: { id?: string } = {}): ComfyWorkflow<ID> => {
248
+ const wf = new ComfyWorkflow(this, {
249
+ apiJson: json,
250
+ metadata: {},
251
+ id: p.id ? asComfyWorkflowID(p.id) : undefined,
252
+ })
253
+ wf.onUpdate(null, wf.data) // hydrate ComfyNode instances from the json
254
+ return wf
255
+ }
256
+
257
+ private _ready: Promise<void> | null = null
258
+ private _readyResolve: (() => void) | null = null
259
+ private _readyReject: ((e: unknown) => void) | null = null
260
+ private _schemaStrategy: NonNullable<ConnectOptions['schema']> = 'auto'
261
+ private _schemaMaxAgeMs: number = 24 * 3600_000
262
+
263
+ /**
264
+ * open the websocket; resolves once connected AND the schema is loaded.
265
+ * Schema strategy:
266
+ * - 'auto' (default): reuse .comfy-ts/ cache when younger than maxAgeMs — fast starts
267
+ * - 'refresh': always fetch object_info + regen the sdk
268
+ * - 'cache': never fetch (throws when no cache exists)
269
+ */
270
+ connect = (p: ConnectOptions = {}): Promise<void> => {
271
+ if (this._ready == null) {
272
+ this._schemaStrategy = p.schema ?? 'auto'
273
+ this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 3600_000
274
+ this._ready = new Promise<void>((res, rej) => {
275
+ this._readyResolve = res
276
+ this._readyReject = rej
277
+ })
278
+ this.initWebsocket()
279
+ }
280
+ return this._ready
281
+ }
282
+
283
+ /** close the websocket (e.g. to let a script exit) */
284
+ disconnect = (): void => {
285
+ this.ws?.disconnectPermanently()
286
+ this.ws = null
287
+ this._ready = null
288
+ }
289
+
290
+ private markReady(): void {
291
+ this._readyResolve?.()
292
+ this._readyResolve = null
293
+ this._readyReject = null
294
+ }
295
+
296
+ private markFailed(error: unknown): void {
297
+ // reject the pending connect() so callers fail fast instead of hanging
298
+ this._readyReject?.(error)
299
+ this._readyResolve = null
300
+ this._readyReject = null
301
+ }
302
+
303
+ private async writeSDKToDisk(): Promise<void> {
304
+ const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
305
+ // skip the 4MB write when nothing changed (fast re-connects)
306
+ if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
307
+ await writeFileAsync(this.sdkDTSPath, comfySchemaTs, 'utf-8')
308
+ }
309
+
310
+ private shouldUseSchemaCache(): boolean {
311
+ if (this._schemaStrategy === 'refresh') return false
312
+ const exists = existsSync(this.comfyJSONPath)
313
+ if (this._schemaStrategy === 'cache') {
314
+ if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
315
+ return true
316
+ }
317
+ if (!exists) return false
318
+ const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs
319
+ return ageMs < this._schemaMaxAgeMs
320
+ }
321
+
322
+ // WEBSCKET -----------------------------------------------------------------------------
323
+ /**
324
+ * will be created only after we've loaded cnfig file
325
+ * so we don't attempt to connect to some default server
326
+ * */
327
+ ws: Maybe<ResilientWebSocketClient> = null
328
+
329
+ /** resolves once the server assigned us a session id (first ws 'status' message) */
330
+ private _sessionResolve: (() => void) | null = null
331
+ private waitForSession(timeoutMs: number = 5000): Promise<void> {
332
+ if (this.comfySessionId !== 'temp') return Promise.resolve()
333
+ return new Promise<void>((res) => {
334
+ this._sessionResolve = res
335
+ // some setups never send a sid — proceed after the timeout, loudly
336
+ setTimeout(() => {
337
+ if (this._sessionResolve != null) {
338
+ console.error(
339
+ `🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`,
340
+ )
341
+ this._sessionResolve = null
342
+ res()
343
+ }
344
+ }, timeoutMs).unref?.()
345
+ })
346
+ }
347
+
348
+ private initWebsocket(): ResilientWebSocketClient {
349
+ logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`)
350
+ this.ws = new ResilientWebSocketClient({
351
+ onConnectOrReconnect: async (): Promise<void> => {
352
+ logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)
353
+ if (this.shouldUseSchemaCache()) {
354
+ try {
355
+ await this.loadSchemaFromCache()
356
+ // the server routes execution events by client_id: without the
357
+ // session id from the first 'status' message, prompts we POST
358
+ // would report to nobody. The slow fetch path masked this race.
359
+ await this.waitForSession()
360
+ this.markReady()
361
+ return
362
+ } catch (error) {
363
+ console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error))
364
+ }
365
+ }
366
+ await this.fetchAndUpdateSchema()
367
+ await this.waitForSession()
368
+ this.markReady()
369
+ },
370
+ onMessage: (e: MessageEvent): void => this.onMessage(e),
371
+ url: () => this.getWSUrl(),
372
+ onClose: (): void => {
373
+ logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
374
+ },
375
+ })
376
+ return this.ws
377
+ }
378
+
379
+ _isUpdatingSchema: boolean = false
380
+ get isUpdatingSchema(): boolean {
381
+ return this._isUpdatingSchema
382
+ }
383
+ set isUpdatingSchema(v: boolean) {
384
+ this._isUpdatingSchema = v
385
+ }
386
+
387
+ schemaUpdateResult: SchemaUpdateResult = null
388
+
389
+ private _schemaFromCache: Promise<void> | null = null
390
+
391
+ /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
392
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
393
+ loadSchemaFromCache(): Promise<void> {
394
+ this._schemaFromCache ??= (async (): Promise<void> => {
395
+ const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)
396
+ const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])
397
+
398
+ // update schema
399
+ this.schema.update({ spec: object_info_json, embeddings: embeddings_json })
400
+ this.schema.RUN_BASIC_CHECKS()
401
+
402
+ // the on-disk sdk was generated from this same cache — only write when missing
403
+ if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()
404
+ })().catch((e: unknown) => {
405
+ this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)
406
+ throw e
407
+ })
408
+ return this._schemaFromCache
409
+ }
410
+
411
+ /** POST a JSON route, preferring the /api prefix, falling back to the bare route */
412
+ private postJSON_ = async (route: string, body: unknown): Promise<void> => {
413
+ const base = this.getServerHostHTTP()
414
+ for (const url of [`${base}/api${route}`, `${base}${route}`]) {
415
+ const res = await fetch(url, {
416
+ method: 'POST',
417
+ headers: { 'Content-Type': 'application/json' },
418
+ body: JSON.stringify(body),
419
+ })
420
+ if (res.ok) return
421
+ }
422
+ throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`)
423
+ }
424
+
425
+ /** drop every PENDING prompt from the server queue (the running one keeps going) */
426
+ clearQueue = (): Promise<void> => {
427
+ return this.postJSON_('/queue', { clear: true })
428
+ }
429
+
430
+ /** interrupt the CURRENTLY RUNNING prompt */
431
+ interrupt = (): Promise<void> => {
432
+ return this.postJSON_('/interrupt', {})
433
+ }
434
+
435
+ /** GET a JSON route, preferring the /api prefix, falling back to the bare route */
436
+ private fetchJSON_ = async <T>(route: string): Promise<T> => {
437
+ const base = this.getServerHostHTTP()
438
+ for (const url of [`${base}/api${route}`, `${base}${route}`]) {
439
+ const res = await fetch(url, { method: 'GET' })
440
+ if (!res.ok) continue
441
+ if (!(res.headers.get('content-type') ?? '').includes('json')) continue
442
+ return (await res.json()) as T
443
+ }
444
+ throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`)
445
+ }
446
+
447
+ /** retrieve the comfy spec from the schema*/
448
+ fetchAndUpdateSchema = async (): Promise<void> => {
449
+ try {
450
+ this.isUpdatingSchema = true
451
+ // 1 ------------------------------------
452
+ // download object_info (prefer /api/*: custom nodes hijack bare routes,
453
+ // e.g. lora-manager serves HTML at /embeddings)
454
+ const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')
455
+ const object_info_str = readableStringify(object_info_json, 4)
456
+ void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')
457
+ // use ark to check if payload match the type, and display errors if not
458
+ const res = ComfySchemaJSON_ark(object_info_json)
459
+ if (res instanceof type.errors) {
460
+ printArkResultInConsole(res)
461
+ }
462
+
463
+ // 2 ------------------------------------
464
+ // download embeddings
465
+ const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(
466
+ () => [] as EmbeddingName[],
467
+ )
468
+ void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')
469
+
470
+ // 3 ------------------------------------
471
+ // update schema
472
+ this.schema.update({ spec: object_info_json, embeddings: embeddings_json })
473
+ this.schema.RUN_BASIC_CHECKS()
474
+
475
+ // 3 ------------------------------------
476
+ // regen sdk
477
+ await this.writeSDKToDisk()
478
+ this.isUpdatingSchema = false
479
+ this.schemaUpdateResult = { type: 'success' }
480
+ } catch (error) {
481
+ this.isUpdatingSchema = false
482
+ this.schemaUpdateResult = { type: 'error', error: error }
483
+
484
+ console.error(error)
485
+ console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))
486
+
487
+ const schemaExists = existsSync(this.sdkDTSPath)
488
+ if (!schemaExists) await this.writeSDKToDisk()
489
+ this.markFailed(error)
490
+ } finally {
491
+ this.isUpdatingSchema = false
492
+ }
493
+ }
494
+
495
+ /** executions we started */
496
+ executions: Map<PromptID, ComfyExecution> = new Map()
497
+
498
+ /** buffer in case we receive packets out of order */
499
+ _pendingMsgs = new Map<PromptID, PromptRelated_WsMsg[]>()
500
+
501
+ /** the active prompt currently running on this host */
502
+ private activePromptID: PromptID | null = null
503
+
504
+ /** method to either execute or buffer the incoming message */
505
+ routeOrBuffer(prompt_id: PromptID, msg: PromptRelated_WsMsg): void {
506
+ this.activePromptID = prompt_id
507
+ const prompt = this.executions.get(prompt_id)
508
+
509
+ // case 1. no prompt yet => just store the messages
510
+ if (prompt == null) {
511
+ const msgs = this._pendingMsgs.get(prompt_id)
512
+ if (msgs) msgs.push(msg)
513
+ else this._pendingMsgs.set(prompt_id, [msg])
514
+ return
515
+ }
516
+ // case 2. prompt exists => send the messages
517
+ prompt.onPromptRelatedMessage(msg)
518
+ }
519
+
520
+ /** the latent image beeing generated, in case you want to display it */
521
+ latentPreview: Maybe<{
522
+ promptID: Maybe<PromptID>
523
+ receivedAt: number_Timestamp
524
+ blob: Blob
525
+ url: string
526
+ }> = null
527
+
528
+ /** byte-level latent-preview hook (e.g. TUI live preview panel) */
529
+ onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null
530
+
531
+ /** fires on every ws 'status' message (queue length lives there) */
532
+ onStatus: Maybe<(p: { queueRemaining: number }) => void> = null
533
+
534
+ /** the session assigned to us by the server */
535
+ comfySessionId: string = 'temp' /** send by ComfyUI server */
536
+
537
+ /** handy to keep around */
538
+ status: ComfyStatusData['status'] | null = null
539
+
540
+ onMessage(e: MessageEvent): void {
541
+ if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
542
+ if (e.data instanceof ArrayBuffer) {
543
+ // 🔴 console.log('[👢] WEBSOCKET: received ArrayBuffer', e.data)
544
+ const view = new DataView(e.data)
545
+ const eventType = view.getUint32(0)
546
+ const buffer = e.data.slice(4)
547
+ switch (eventType) {
548
+ case 1: {
549
+ const view2 = new DataView(e.data)
550
+ const imageType = view2.getUint32(4)
551
+ let imageMime: string
552
+ switch (imageType) {
553
+ case 1:
554
+ imageMime = 'image/jpeg'
555
+ break
556
+ case 2:
557
+ imageMime = 'image/png'
558
+ break
559
+ default:
560
+ imageMime = 'image/jpeg'
561
+ break
562
+ }
563
+ const imageBytes = buffer.slice(4)
564
+ const imageBlob = new Blob([imageBytes], { type: imageMime })
565
+ const imagePreview = URL.createObjectURL(imageBlob)
566
+ this.latentPreview = {
567
+ blob: imageBlob,
568
+ url: imagePreview,
569
+ receivedAt: Date.now() as number_Timestamp,
570
+ promptID: this.activePromptID,
571
+ }
572
+ this.onLatentPreview?.({
573
+ bytes: new Uint8Array(imageBytes),
574
+ mime: imageMime,
575
+ promptID: this.activePromptID,
576
+ })
577
+ break
578
+ }
579
+ default:
580
+ throw new Error(`Unknown binary websocket message of type ${eventType}`)
581
+ }
582
+ return
583
+ }
584
+
585
+ const msg_: unknown = JSON.parse(String(e.data))
586
+
587
+ // ----- crystools silent fix -----
588
+ if (typeof msg_ === 'object' && msg_ != null && 'type' in msg_) {
589
+ if (msg_.type === 'crystools.monitor') return
590
+ }
591
+
592
+ // ----- soft-validate against the schema -----
593
+ const res = WsMsg_ark(msg_)
594
+ if (res instanceof type.errors) {
595
+ console.log(`[🔴] /!\\ Websocket payload does not match schema.`)
596
+ printArkResultInConsole(res)
597
+ }
598
+ // wire tolerance (agent/coding.md): ComfyUI drifts faster than our schema;
599
+ // failures are logged above, then we still route best-effort
600
+ const msg = msg_ as WsMsg
601
+
602
+ if (msg.type === 'status') {
603
+ if (msg.data.sid) {
604
+ this.comfySessionId = msg.data.sid
605
+ this._sessionResolve?.()
606
+ this._sessionResolve = null
607
+ }
608
+ this.status = msg.data.status
609
+ this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })
610
+ return
611
+ }
612
+
613
+ // defer accumulation to ScriptStep_prompt
614
+ if (msg.type === 'progress') {
615
+ const activePromptID = this.activePromptID
616
+ if (activePromptID == null) {
617
+ console.log(`❌ received a 'progress' msg, but activePromptID is not set`)
618
+ return
619
+ }
620
+ this.routeOrBuffer(activePromptID, msg)
621
+ return
622
+ }
623
+ if (
624
+ msg.type === 'execution_start' ||
625
+ msg.type === 'execution_cached' ||
626
+ msg.type === 'execution_error' ||
627
+ msg.type === 'execution_success' ||
628
+ msg.type === 'executing' ||
629
+ msg.type === 'executed' ||
630
+ msg.type === 'progress_state'
631
+ ) {
632
+ this.routeOrBuffer(msg.data.prompt_id, msg)
633
+ return
634
+ }
635
+
636
+ if (msg.type === 'manager-terminal-feedback') {
637
+ this.addLog(msg.data.data)
638
+ return
639
+ }
640
+ exhaust(msg)
641
+ console.log('❌', 'Unknown message:', msg)
642
+
643
+ toastError('Unknown message type: ' + JSON.stringify(msg.type))
644
+ // throw new Error('Unknown message type: ' + JSON.stringify(msg))
645
+ }
646
+ }
@@ -0,0 +1,15 @@
1
+ import type { SSHHostConfig } from 'src/ssh-host-manager/ssh-config-manager.ts'
2
+
3
+ // biome-ignore format: misc
4
+ export type ComfyInstallType = ComfyInstallTypeLocal | ComfyInstallTypeRemote
5
+
6
+ export type ComfyInstallTypeLocal = {
7
+ type: 'local'
8
+ absolutePathToComfyRoot?: string
9
+ }
10
+
11
+ export type ComfyInstallTypeRemote = {
12
+ type: 'remote'
13
+ absolutePathToComfyRoot?: string
14
+ sshHostConfigd: SSHHostConfig
15
+ }